You are on page 1of 388

What is Android? | Android Developers 29.04.09 0:33 What is Android?

Android is a software stack for mobile devices that includes an operating system , middleware and key applications. The Android SDK provides the tools and APIs n ecessary to begin developing applications on the Android platform using the Java programming language. Features Application framework enabling reuse and replacement of components Dalvik virtua l machine optimized for mobile devices Integrated browser based on the open sour ce WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optiona l) SQLite for structured data storage Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environmen t including a device emulator, tools for debugging, memory and performance profi ling, and a plugin for the Eclipse IDE Android Architecture The following diagram shows the major components of the Android operating system . Each section is described in more detail below. http://developer.android.com/guide/basics/what-is-android.html Page 1 of 3

What is Android? | Android Developers 29.04.09 0:33 Applications Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are wr itten using the Java programming language. Application Framework Developers have full access to the same framework APIs used by the core applicat ions. The application architecture is designed to simplify the reuse of componen ts; any application can publish its capabilities and any other application may t hen make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user . Underlying all applications is a set of services and systems, including: A ric h and extensible set of Views that can be used to build an application, includin g lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files A Noti fication Manager that enables all applications to display custom alerts in the s tatus bar http://developer.android.com/guide/basics/what-is-android.html Page 2 of 3

What is Android? | Android Developers 29.04.09 0:33 An Activity Manager that manages the lifecycle of applications and provides a co mmon navigation backstack For more details and a walkthrough of an application, see the Notepad Tutorial. Libraries Android includes a set of C/C++ libraries used by various components of the Andr oid system. These capabilities are exposed to developers through the Android app lication framework. Some of the core libraries are listed below: System C librar y - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices Media Libraries - based on PacketVideo's OpenCO RE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG Surface Manager - manages access to the display subsystem and seaml essly composites 2D and 3D graphic layers from multiple applications LibWebCore - a modern web browser engine which powers both the Android browser and an embed dable web view SGL - the underlying 2D graphics engine 3D libraries - an impleme ntation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D accele ration (where available) or the included, highly optimized 3D software rasterize r FreeType - bitmap and vector font rendering SQLite - a powerful and lightweigh t relational database engine available to all applications Android Runtime Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtua l machine. Dalvik has been written so that a device can run multiple VMs efficie ntly. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs cl asses compiled by a Java language compiler that have been transformed into the . dex format by the included "dx" tool. The Dalvik VM relies on the Linux kernel f or underlying functionality such as threading and low-level memory management. Linux Kernel Android relies on Linux version 2.6 for core system services such as security, m emory management, process management, network stack, and driver model. The kerne l also acts as an abstraction layer between the hardware and the rest of the sof tware stack. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/basics/what-is-android.html Page 3 of 3

Application Fundamentals | Android Developers 29.04.09 0:33 Application Fundamentals Android applications are written in the Java programming language. The compiled Java code along with any data and resource files required by the application is bundled by the aapt tool into an Android package, an archive file marked by an . apk suffix. This file is the vehicle for distributing the application and instal ling it on mobile devices; it's the file users download to their devices. All th e code in a single .apk file is considered to be one application. In many ways, each Android application lives in its own world: By default, every application r uns in its own Linux process. Android starts the process when any of the applica tion's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications. Each process ha s its own Java virtual machine (VM), so application code runs in isolation from the code of all other applications. By default, each application is assigned a u nique Linux user ID. Permissions are set so that the application's files are vis ible only that user, only to the application itself although there are ways to e xport them to other applications as well. It's possible to arrange for two appli cations to share the same user ID, in which case they will be able to see each o ther's files. To conserve system resources, applications with the same ID can al so arrange to run in the same Linux process, sharing the same VM. Application Components A central feature of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if you r application needs to display a scrolling list of images and another applicatio n has developed a suitable scroller and made it available to others, you can cal l upon that scroller to do the work, rather than develop your own. Your applicat ion doesn't incorporate the code of the other application or link to it. Rather, it simply starts up that piece of the other application when the need arises. F or this to work, the system must be able to start an application process when an y part of it is needed, and instantiate the Java objects for that part. Therefor e, unlike applications on most other systems, Android applications don't have a single entry point for everything in the application (no main() function, for ex ample). Rather, they have essential components that the system can instantiate a nd run as needed. There are four types of components: Activities An activity pre sents a visual user interface for one focused endeavor the user can undertake. F or example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging app lication might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other acti vities to review old messages or change settings. Though they work together to f orm a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class. An application migh t consist of just one activity or, like the text messaging application just ment ioned, it may contain several. What the activities are, and how many there are d epends, of course, on the application and its design. Typically, one of the acti vities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the next one. http://developer.android.com/guide/topics/fundamentals.html Page 1 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other wi ndows. An activity can also make use of additional windows for example, a pop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vital information when they select a particular item o n-screen. The visual content of the window is provided by a hierarchy of views o bjects derived from the base View class. Each view controls a particular rectang ular space within the window. Parent views contain and organize the layout of th eir children. Leaf views (those at the bottom of the hierarchy) draw in the rect angles they control and respond to user actions directed at that space. Thus, vi ews are where the activity's interaction with the user takes place. For example, a view might display a small image and initiate an action when the user taps th at image. Android has a number of ready-made views that you can use including bu ttons, text fields, scroll bars, menu items, check boxes, and more. A view hiera rchy is placed within an activity's window by the Activity.setContentView() meth od. The content view is the View object at the root of the hierarchy. (See the s eparate User Interface document for more information on views and the hierarchy. ) Services A service doesn't have a visual user interface, but rather runs in th e background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data o ver the network or calculate something and provide the result to activities that need it. Each service extends the Service base class. A prime example is a medi a player playing songs from a play list. The player application would probably h ave one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity be cause users will expect the music to keep playing even after they leave the play er and begin something different. To keep the music going, the media player acti vity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leave s the screen. It's possible to connect to (bind to) an ongoing service (and star t the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music s ervice, this interface might allow users to pause, rewind, stop, and restart the playback. Like activities and the other components, services run in the main th read of the application process. So that they won't block other components or th e user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later. Broadcast receivers A broadc ast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code for example, announceme nts that the timezone has changed, that the battery is low, that a picture has b een taken, or that the user changed a language preference. Applications can also initiate broadcasts for example, to let other applications know that some data has been downloaded to the device and is available for them to use. An applicati on can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiver base class. Bro adcast receivers do not display a user interface. However, they may start an act ivity in response to the information they receive, or they may use the Notificat ionManager to alert the user. Notifications can get the user's attention in vari ous ways flashing the backlight, vibrating the device, playing a sound, and so o n. They typically place a persistent icon in the status bar, which users can ope n to get the message. Content providers A content provider makes a specific set of the application's data available to other applications. The data can be store d in the file system, in an SQLite database, or in any other manner that makes s ense. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store da ta of the type it controls. However, applications do not call these methods dire

ctly. Rather they use a ContentResolver object and call its methods instead. A C ontentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved. http://developer.android.com/guide/topics/fundamentals.html Page 2 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 provider; it cooperates with the provider to manage any interprocess communicati on that's involved. See the separate Content Providers document for more informa tion on using content providers. Whenever there's a request that should be handl ed by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate ins tance of the component is available, creating the instance if necessary. Activating components: intents Content providers are activated when they're targeted by a request from a Conten tResolver. The other three components activities, services, and broadcast receiv ers are activated by asynchronous messages called intents. An intent is an Inten t object that holds the content of the message. For activities and services, it names the action being requested and specifies the URI of the data to act on, am ong other things. For example, it might convey a request for an activity to pres ent an image to the user or let the user edit some text. For broadcast receivers , the Intent object names the action being announced. For example, it might anno unce to interested parties that the camera button has been pressed. There are se parate methods for activiating each type of component: An activity is launched ( or given something new to do) by passing an Intent object to Context.startActivi ty() or Activity.startActivityForResult(). The responding activity can look at t he initial intent that caused it to be launched by calling its getIntent() metho d. Android calls the activity's onNewIntent() method to pass it any subsequent i ntents. One activity often starts the next one. If it expects a result back from the activity it's starting, it calls startActivityForResult() instead of startA ctivity(). For example, if it starts an activity that lets the user pick a photo , it might expect to be returned the chosen photo. The result is returned in an Intent object that's passed to the calling activity's onActivityResult() method. A service is started (or new instructions are given to an ongoing service) by p assing an Intent object to Context.startService(). Android calls the service's o nStart() method and passes it the Intent object. Similarly, an intent can be pas sed to Context.bindService() to establish an ongoing connection between the call ing component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can option ally start it.) For example, an activity might establish a connection with the m usic playback service mentioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService() to set up that connection, and then call methods defined by the se rvice to affect the playback. A later section, Remote procedure calls, has more details about binding to a service. An application can initiate a broadcast by p assing an Intent object to methods like Context.sendBroadcast(), Context.sendOrd eredBroadcast(), and Context.sendStickyBroadcast() in any of their variations. A ndroid delivers the intent to all interested broadcast receivers by calling thei r onReceive() methods. For more on intent messages, see the separate article, In tents and Intent Filters. Shutting down components A content provider is active only while it's responding to a request from a Cont entResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components. Activities, on the other hand, provide the user interface. They're in a long-run ning conversation with the user and may remain active, even when idle, as long a s the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an ord erly way: An activity can be shut down by calling its finish() method. One activ ity can shut down another activity (one it started with startActivityForResult() ) by calling finishActivity(). A service can be stopped by calling its stopSelf(

) method, or by calling Context.stopService(). http://developer.android.com/guide/topics/fundamentals.html Page 3 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 Components might also be shut down by the system when they are no longer being u sed or when Android must reclaim memory for more active components. A later sect ion, Component Lifecycles, discusses this possibility and its ramifications in m ore detail. The manifest file Before Android can start an application component, it must learn that the compon ent exists. Therefore, applications declare their components in a manifest file that's bundled into the Android package, the .apk file that also holds the appli cation's code, files, and resources. The manifest is a structured XML file and i s always named AndroidManifest.xml for all applications. It does a number of thi ngs in addition to declaring the application's components, such as naming any li braries the application needs to be linked against (besides the default Android library) and identifying any permissions the application expects to be granted. But the principal task of the manifest is to inform Android about the applicatio n's components. For example, an activity might be declared as follows: <?xml ver sion="1.0" encoding="utf-8"?> <manifest . . . > <application . . . > <activity a ndroid:name="com.example.project.FreneticActivity" android:icon="@drawable/small _pic.png" android:label="@string/freneticLabel" . . . > </activity> . . . </appl ication> </manifest> The name attribute of the <activity> element names the Acti vity subclass that implements the activity. The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity. The other components are declared in a similar way <ser vice> elements for services, <receiver> elements for broadcast receivers, and <p rovider> elements for content providers. Activities, services, and content provi ders that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver o bjects) and registered with the system by calling Context.registerReceiver(). Fo r more on how to structure a manifest file for your application, see The Android Manifest.xml File. Intent filters An Intent object can explicitly name a target component. If it does, Android fin ds that component (based on the declarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the best compo nent to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. A component's intent filters inform Android of the kinds of intents the component is able to handle. Like other essential i nformation about the component, they're declared in the manifest file. Here's an extension of the previous example that adds two intent filters to the activity: <?xml version="1.0" encoding="utf-8"?> <manifest . . . > <application . . . > < activity android:name="com.example.project.FreneticActivity" android:icon="@draw able/small_pic.png" android:label="@string/freneticLabel" . . . > http://developer.android.com/guide/topics/fundamentals.html Page 4 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 . . . > <intent-filter . . . > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter > <intent-filter . . . > <action android:name="com.example.project.BOUNCE" /> <d ata android:type="image/jpeg" /> <category android:name="android.intent.category .DEFAULT" /> </intent-filter> </activity> . . . </application> </manifest> The f irst filter in the example the combination of the action "android.intent.action. MAIN" and the category "android.intent.category.LAUNCHER" is a common one. It ma rks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application, the initial one users would see when they choose the application in the launcher. The second filter declare s an action that the activity can perform on a particular type of data. A compon ent can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by inten ts that explicitly name the component as the target. For a broadcast receiver th at's created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest. For mor e on intent filters, see a separate document, Intents and Intent Filters. Activities and Tasks As noted earlier, one activity can start another, including one defined in a dif ferent application. Suppose, for example, that you'd like to let users display a street map of some location. There's already an activity that can do that, so a ll your activity needs to do is put together an Intent object with the required information and pass it to startActivity(). The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen. To the user, it will seem as if the map viewer is part of the same application as your activity, even though it's defined in another application and runs in that appli cation's process. Android maintains this user experience by keeping both activit ies in the same task. Simply put, a task is what the user experiences as an "app lication." It's a group of related activities, arranged in a stack. The root act ivity in the stack is the one that began the task typically, it's an activity th e user selected in the application launcher. The activity at the top of the stac k is one that's currently running the one that is the focus for user actions. Wh en one activity starts another, the new activity is pushed on the stack; it beco mes the running activity. The previous activity remains in the stack. When the u ser presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity. The stack contains objects, so if a task has more than one instance of the same Activity subclass open multiple m ap viewers, for example the stack has a separate entry for each instance. Activi ties in the stack are never rearranged, only pushed and popped. A task is a stac k of activities, not a class or an element in the manifest file. So there's no w ay to set values for a task independently of its activities. Values for the task as a whole are set in the root activity. For example, the next section will tal k about the "affinity of a task"; that value is read from the affinity set for t he task's root activity. All the activities in a task move together as a unit. T he entire task (the entire activity stack) can be brought to the foreground or s ent to the background. Suppose, for instance, that the current task has four act ivities in its stack three under the current activity. The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). The current task goes into the background and the root activity fo r the new task is http://developer.android.com/guide/topics/fundamentals.html Page 5 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key , the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed. The behavior just descr ibed is the default behavior for activities and tasks. But there are ways to mod ify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in t he activity's <activity> element in the manifest. Both requester and respondent have a say in what happens. In this regard, the principal Intent flags are: FLAG _ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_RESET_TASK_IF_NEEDED FL AG_ACTIVITY_SINGLE_TOP The principal <activity> attributes are: taskAffinity lau nchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTas kLaunch The following sections describe what some of these flags and attributes do, how they interact, and what considerations should govern their use. Affinities and new tasks By default, all the activities in an application have an affinity for each other that is, there's a preference for them all to belong to the same task. However, an individual affinity can be set for each activity with the taskAffinity attri bute of the <activity> element. Activities defined in different applications can share an affinity, or activities defined in the same application can be assigne d different affinities. The affinity comes into play in two circumstances: When the Intent object that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag, and when an activity has its allowTaskReparenting attribute set to "true". The FLAG_ACTIVITY_NEW_TASK flag As described earlier, a new activity is, by def ault, launched into the task of the activity that called startActivity(). It's p ushed onto the same stack as the caller. However, if the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, as the name of the flag impli es, it's a new task. However, it doesn't have to be. If there's already an exist ing task with the same affinity as the new activity, the activity is launched in to that task. If not, it begins a new task. The allowTaskReparenting attribute I f an activity has its allowTaskReparenting attribute set to "true", it can move from the task it starts in to the task it has an affinity for when that task com es to the fore. For example, suppose that an activity that reports weather condi tions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so it initially belongs to the same task as your activity. However, when the tra vel application next comes forward, the weather reporter will be reassigned to a nd displayed with that task. If an .apk file contains more than one "application " from the user's point of view, you will probably want to assign different affi nities to the activities associated with each of them. Launch modes http://developer.android.com/guide/topics/fundamentals.html Page 6 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 There are four different launch modes that can be assigned to an <activity> elem ent's launchMode attribute: "standard" (the default mode) "singleTop" "singleTas k" "singleInstance" The modes differ from each other on these four points: Which task will hold the activity that responds to the intent. For the "standard" and "singleTop" modes, it's the task that originated the intent (and called startAc tivity()) unless the Intent object contains the FLAG_ACTIVITY_NEW_TASK flag. In that case, a different task is chosen as described in the previous section, Affi nities and new tasks. In contrast, the "singleTask" and "singleInstance" modes m ark activities that are always at the root of a task. They define a task; they'r e never launched into another task. Whether there can be multiple instances of t he activity. A "standard" or "singleTop" activity can be instantiated many times . They can belong to multiple tasks, and a given task can have multiple instance s of the same activity. In contrast, "singleTask" and "singleInstance" activitie s are limited to just one instance. Since these activities are at the root of a task, this limitation means that there is never more than a single instance of t he task on the device at one time. Whether the instance can have other activitie s in its task. A "singleInstance" activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a d ifferent task regardless of its launch mode as if FLAG_ACTIVITY_NEW_TASK was in the intent. In all other respects, the "singleInstance" mode is identical to "si ngleTask". The other three modes permit multiple activities to belong to the tas k. A "singleTask" activity will always be the root activity of the task, but it can start other activities that will be assigned to its task. Instances of "stan dard" and "singleTop" activities can appear anywhere in a stack. Whether a new i nstance of the class will be launched to handle a new intent. For the default "s tandard" mode, a new instance is created to respond to every new intent. Each in stance handles just one intent. For the "singleTop" mode, an existing instance o f the class is re-used to handle a new intent if it resides at the top of the ac tivity stack of the target task. If it does not reside at the top, it is not reused. Instead, a new instance is created for the new intent and pushed on the st ack. For example, suppose a task's activity stack consists of root activity A wi th activities B, C, and D on top in that order, so the stack is A-B-C-D. An inte nt arrives for an activity of type D. If D has the default "standard" launch mod e, a new instance of the class is launched and the stack becomes A-B-C-D-D. Howe ver, if D's launch mode is "singleTop", the existing instance is expected to han dle the new intent (since it's at the top of the stack) and the stack remains AB-C-D. If, on the other hand, the arriving intent is for an activity of type B, a new instance of B would be launched no matter whether B's mode is "standard" o r "singleTop" (since B is not at the top of the stack), so the resulting stack w ould be A-B-C-D-B. As noted above, there's never more than one instance of a "si ngleTask" or "singleInstance" activity, so that instance is expected to handle a ll new intents. A "singleInstance" activity is always at the top of the stack (s ince it is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask" activity may or may not have other activiti es above it in the stack. If it does, it is not in position to handle the intent , and the intent is dropped. (Even though the intent is dropped, its arrival wou ld have caused the task to come to the foreground, where it would remain.) When an existing activity is asked to handle a new intent, the Intent object is passe d to the activity in an onNewIntent() call. (The intent object that originally s tarted the activity can be retrieved by calling getIntent().) Note that when a n ew instance of an Activity is created to handle a new intent, the user can alway s press the BACK key to return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent, the user can not press the BACK key to return to what that instance was doing before the new intent arrived. http://developer.android.com/guide/topics/fundamentals.html Page 7 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 intent, the user cannot press the BACK key to return to what that instance was d oing before the new intent arrived. For more on launch modes, see the descriptio n of the <activity> element. Clearing the stack If the user leaves a task for a long time, the system clears the task of all act ivities except the root activity. When the user returns to the task again, it's as the user left it, except that only the initial activity is present. The idea is that, after a time, users will likely have abandoned what they were doing bef ore and are returning to the task to begin something new. That's the default. Th ere are some activity attributes that can be used to control this behavior and m odify it: The alwaysRetainTaskState attribute If this attribute is set to "true" in the root activity of a task, the default behavior just described does not ha ppen. The task retains all activities in its stack even after a long period. The clearTaskOnLaunch attribute If this attribute is set to "true" in the root acti vity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the polar opposite of a lwaysRetainTaskState. The user always returns to the task in its initial state, even after a momentary absence. The finishOnTaskLaunch attribute This attribute is like clearTaskOnLaunch, but it operates on a single activity, not an entire t ask. And it can cause any activity to go away, including the root activity. When it's set to "true", the activity remains part of the task only for the current session. If the user leaves and then returns to the task, it no longer is presen t. There's another way to force activities to be removed from the stack. If an I ntent object includes the FLAG_ACTIVITY_CLEAR_TOP flag, and the target task alre ady has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and can respond to the intent. If the launch mode of the d esignated activity is "standard", it too will be removed from the stack, and a n ew instance will be launched to handle the incoming intent. That's because a new instance is always created for a new intent when the launch mode is "standard". FLAG_ACTIVITY_CLEAR_TOP is most often used in conjunction with FLAG_ACTIVITY_NE W_TASK. When used together, these flags are a way of locating an existing activi ty in another task and putting it in a position where it can respond to the inte nt. Starting tasks An activity is set up as the entry point for a task by giving it an intent filte r with "android.intent.action.MAIN" as the specified action and "android.intent. category.LAUNCHER" as the specified category. (There's an example of this type o f filter in the earlier Intent Filters section.) A filter of this kind causes an icon and label for the activity to be displayed in the application launcher, gi ving users a way both to launch the task and to return to it at any time after i t has been launched. This second ability is important: Users must be able to lea ve a task and then come back to it later. For this reason, the two launch modes that mark activities as always initiating a task, "singleTask" and "singleInstan ce", should be used only when the activity has a MAIN and LAUNCHER filter. Imagi ne, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time wo rking in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in th e application launcher, the user has no way to return to it. A similar difficult y attends the FLAG_ACTIVITY_NEW_TASK flag. If this flag causes an activity to be gin a new task and the user presses the HOME key to leave it, there must be some way for the user to navigate back to it again. Some entities (such as the notif ication manager) always start activities in an external task, never as part of t

heir own, so they always put FLAG_ACTIVITY_NEW_TASK in the intents they pass to startActivity(). If you have an activity that can be invoked by an external enti ty that might use this flag, take care that the user has a independent way to ge t http://developer.android.com/guide/topics/fundamentals.html Page 8 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 can be invoked by an external entity that might use this flag, take care that th e user has a independent way to get back to the task that's started. For those c ases where you don't want the user to be able to return to an activity, set the <activity> element's finishOnTaskLaunch to "true". See Clearing the stack, earli er. Processes and Threads When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all componen ts of the application run in that process and thread. However, you can arrange f or components to run in other processes, and you can spawn additional threads fo r any process. Processes The process where a component runs is controlled by the manifest file. The compo nent elements <activity>, <service>, <receiver>, and <provider> each have a proc ess attribute that can specify a process where that component should run. These attributes can be set so that each component runs in its own process, or so that some components share a process while others do not. They can also be set so th at components of different applications run in the same process provided that th e applications share the same Linux user ID and are signed by the same authoriti es. The <application> element also has a process attribute, for setting a defaul t value that applies to all components. All components are instantiated in the m ain thread of the specified process, and system calls to the component are dispa tched from that thread. Separate threads are not created for each instance. Cons equently, methods that respond to those calls methods like View.onKeyDown() that report user actions and the lifecycle notifications discussed later in the Comp onent Lifecycles section always run in the main thread of the process. This mean s that no component should perform long or blocking operations (such as networki ng operations or computation loops) when called by the system, since this will b lock any other components also in the process. You can spawn separate threads fo r long operations, as discussed under Threads, next. Android may decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in t he process are consequently destroyed. A process is restarted for those componen ts when there's again work for them to do. When deciding which processes to term inate, Android weighs their relative importance to the user. For example, it mor e readily shuts down a process with activities that are no longer visible on scr een than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that proce ss. Those states are the subject of a later section, Component Lifecycles. Threads Even though you may confine your application to a single process, there will lik ely be times when you will need to spawn a thread to do some background work. Si nce the user interface must always be quick to respond to user actions, the thre ad that hosts an activity should not also host time-consuming operations like ne twork downloads. Anything that may not be completed quickly should be assigned t o a different thread. Threads are created in code using standard Java Thread obj ects. Android provides a number of convenience classes for managing threads Loop er for running a message loop within a thread, Handler for processing messages, and HandlerThread for setting up a thread with a message loop. Remote procedure calls Android has a lightweight mechanism for remote procedure calls (RPCs) where a me thod is called locally, but executed remotely (in another process), with any res

ult returned back to the caller. This entails decomposing the http://developer.android.com/guide/topics/fundamentals.html Page 9 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 method call and all its attendant data to a level the operating system can under stand, transmitting it from the local process and address space to the remote pr ocess and address space, and reassembling and reenacting the call there. Return values have to be transmitted in the opposite direction. Android provides all th e code to do that work, so that you can concentrate on defining and implementing the RPC interface itself. An RPC interface can include only methods. All method s are executed synchronously (the local method blocks until the remote method fi nishes), even if there is no return value. In brief, the mechanism works as foll ows: You'd begin by declaring the RPC interface you want to implement using a si mple IDL (interface definition language). From that declaration, the aidl tool g enerates a Java interface definition that must be made available to both the loc al and the remote process. It contains two inner class, as shown in the followin g diagram: The inner classes have all the code needed to administer remote procedure calls for the interface you declared with the IDL. Both inner classes implement the IB inder interface. One of them is used locally and internally by the system; the c ode you write can ignore it. The other, called Stub, extends the Binder class. I n addition to internal code for effectuating the IPC calls, it contains declarat ions for the methods in the RPC interface you declared. You would subclass Stub to implement those methods, as indicated in the diagram. Typically, the remote p rocess would be managed by a service (because a service can inform the system ab out the process and its connections to other processes). It would have both the interface file generated by the aidl tool and the Stub subclass implementing the RPC methods. Clients of the service would have only the interface file generate d by the aidl tool. Here's how a connection between a service and its clients is set up: Clients of the service (on the local side) would implement onServiceCon nected() and onServiceDisconnected() methods so they can be notified when a succ essful connection to the remote service is established, and when it goes away. T hey would then call bindService() to set up the connection. The service's onBind () method would be implemented to either accept or reject the connection, depend ing on the intent it receives (the intent passed to bindService()). If the conne ction is accepted, it returns an instance of the Stub subclass. If the service a ccepts the connection, Android calls the client's onServiceConnected() method an d passes it an IBinder object, a proxy for the Stub subclass managed by the serv ice. Through the proxy, the client can make http://developer.android.com/guide/topics/fundamentals.html Page 10 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 an IBinder object, a proxy for the Stub subclass managed by the service. Through the proxy, the client can make calls on the remote service. This brief descript ion omits some details of the RPC mechanism. For more information, see Designing a Remote Interface Using AIDL and the IBinder class description. Thread-safe methods In a few contexts, the methods you implement may be called from more than one th read, and therefore must be written to be thread-safe. This is primarily true fo r methods that can be called remotely as in the RPC mechanism discussed in the p revious section. When a call on a method implemented in an IBinder object origin ates in the same process as the IBinder, the method is executed in the caller's thread. However, when the call originates in another process, the method is exec uted in a thread chosen from a pool of threads that Android maintains in the sam e process as the IBinder; it's not executed in the main thread of the process. F or example, whereas a service's onBind() method would be called from the main th read of the service's process, methods implemented in the object that onBind() r eturns (for example, a Stub subclass that implements RPC methods) would be calle d from threads in the pool. Since services can have more than one client, more t han one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe. Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the inte rprocess communication is managed, ContentProvider methods that respond to those requests the methods query(), insert(), delete(), update(), and getType() are c alled from a pool of threads in the content provider's process, not the main thr ead of the process. Since these methods may be called from any number of threads at the same time, they too must be implemented to be thread-safe. Component Lifecycles Application components have a lifecycle a beginning when Android instantiates th em to respond to intents through to an end when the instances are destroyed. In between, they may sometimes be active or inactive,or, in the case of activities, visible to the user or invisible. This section discusses the lifecycles of acti vities, services, and broadcast receivers including the states that they can be in during their lifetimes, the methods that notify you of transitions between st ates, and the effect of those states on the possibility that the process hosting them might be terminated and the instances destroyed. Activity lifecycle An activity has essentially three states: It is active or running when it is in the foreground of the screen (at the top of the activity stack for the current t ask). This is the activity that is the focus for the user's actions. It is pause d if it has lost focus but is still visible to the user. That is, another activi ty lies on top of it and that activity either is transparent or doesn't cover th e full screen, so some of the paused activity can show through. A paused activit y is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. It is stopped if it is completely obscured by another activi ty. It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the s ystem when memory is needed elsewhere. If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish () method), or simply killing its process. When it is displayed again to the use r, it must be completely restarted and restored to its previous state. http://developer.android.com/guide/topics/fundamentals.html Page 11 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 As an activity transitions from state to state, it is notified of the change by calls to the following protected methods: void void void void void void void onC reate(Bundle savedInstanceState) onStart() onRestart() onResume() onPause() onSt op() onDestroy() All of these methods are hooks that you can override to do appropriate work when the state changes. All activities must implement onCreate() to do the initial s etup when the object is first instantiated. Many will also implement onPause() t o commit data changes and otherwise prepare to stop interacting with the user. T aken together, these seven methods define the entire lifecycle of an activity. T here are three nested loops that you can monitor by implementing them: The entir e lifetime of an activity happens between the first call to onCreate() through t o a single final call to onDestroy(). An activity does all its initial setup of "global" state in onCreate(), and releases all remaining resources in onDestroy( ). For example, if it has a thread running in the background to download data fr om the network, it may create that thread in onCreate() and then stop the thread in onDestroy(). Calling into the superclass An implementation of any activity lifecycle method s hould always first call the superclass version. For example: protected void onPa use() { super.onPause(); . . . } The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods, you can maintain resources that are needed to show t he activity to the user. For example, you can register a BroadcastReceiver in on Start() to monitor for changes that impact your UI, and unregister it in onStop( ) when the user can no longer see what you are displaying. The onStart() and onS top() methods can be called multiple times, as the activity alternates between b eing visible and hidden to the user. The foreground lifetime of an activity happ ens between a call to onResume() until a corresponding call to onPause(). During this time, the activity is in front of all other activities on screen and is in teracting with the user. An activity can frequently transition between the resum ed and paused states for example, onPause() is called when the device goes to sl eep or when a new activity is started, onResume() is called when an activity res ult or a new intent is delivered. Therefore, the code in these two methods shoul d be fairly lightweight. The following diagram illustrates these loops and the p aths an activity may take between states. The colored ovals are major states the activity can be in. The square rectangles represent the callback methods you ca n implement to perform operations when the activity transitions between states. http://developer.android.com/guide/topics/fundamentals.html Page 12 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 The following table describes each of these methods in more detail and locates i t within the activity's overall lifecycle: Method onCreate() Description Called when the activity is first created. This is where you should do all of your norm al static set up create views, bind data to lists, and so on. This method is pas sed a Bundle object containing the activity's Killable? No Next onStart() http://developer.android.com/guide/topics/fundamentals.html Page 13 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 previous state, if that state was captured (see Saving Activity State, later). A lways followed by onStart(). onRestart() Called after the activity has been stop ped, just prior to it being started again. Always followed by onStart() Called j ust before the activity becomes visible to the user. Followed by onResume() if t he activity comes to the foreground, or onStop() if it becomes hidden. Called ju st before the activity starts interacting with the user. At this point the activ ity is at the top of the activity stack, with user input going to it. Always fol lowed by onPause(). Called when the system is about to start resuming another ac tivity. This method is typically used to commit unsaved changes to persistent da ta, stop animations and other things that may be consuming CPU, and so on. It sh ould do whatever it does very quickly, because the next activity will not be res umed until it returns. Followed either by onResume() if the activity returns bac k to the front, or by onStop() if it becomes invisible to the user. Called when the activity is no longer visible to the user. This may happen because it is bei ng destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it. Followed either by onRestart() if the activ ity is coming back to interact with the user, or by onDestroy() if this activity is going away. No onStart() onStart() No onResume() or onStop() onResume() No onPause() onPause() Yes onResume() or onStop() onStop() Yes onRestart() or onDestroy() http://developer.android.com/guide/topics/fundamentals.html Page 14 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 onDestroy() Called before the activity is destroyed. This is the final call that the activit y will receive. It could be called either because the activity is finishing (som eone called finish() on it), or because the system is temporarily destroying thi s instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Yes nothing Note the Killable column in the table above. It indicates whether or not the sys tem can kill the process hosting the activity at any time after the method retur ns, without executing another line of the activity's code. Three methods (onPaus e(), onStop(), and onDestroy()) are marked "Yes." Because onPause() is the first of the three, it's the only one that's guaranteed to be called before the proce ss is killed onStop() and onDestroy() may not be. Therefore, you should use onPa use() to write any persistent data (such as user edits) to storage. Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called. Thus an activity is in a kil lable state, for example, from the time onPause() returns to the time onResume() is called. It will not again be killable until onPause() again returns. As note d in a later section, Processes and lifecycle, an activity that's not technicall y "killable" by this definition might still be killed by the system but that wou ld happen only in extreme and dire circumstances when there is no other recourse . Saving activity state When the system, rather than the user, shuts down an activity to conserve memory , the user may expect to return to the activity and find it in its previous stat e. To capture that state before the activity is killed, you can implement an onS aveInstanceState() method for the activity. Android calls this method before mak ing the activity vulnerable to being destroyed that is, before onPause() is call ed. It passes the method a Bundle object where you can record the dynamic state of the activity as name-value pairs. When the activity is again started, the Bun dle is passed both to onCreate() and to a method that's called after onStart(), onRestoreInstanceState(), so that either or both of them can recreate the captur ed state. Unlike onPause() and the other methods discussed earlier, onSaveInstan ceState() and onRestoreInstanceState() are not lifecycle methods. They are not a lways called. For example, Android calls onSaveInstanceState() before the activi ty becomes vulnerable to being destroyed by the system, but does not bother call ing it when the instance is actually being destroyed by a user action (such as p ressing the BACK key). In that case, the user won't expect to return to the acti vity, so there's no reason to save its state. Because onSaveInstanceState() is n ot always called, you should use it only to record the transient state of the ac tivity, not to store persistent data. Use onPause() for that purpose instead. Coordinating activities When one activity starts another, they both experience lifecycle transitions. On e pauses and may stop, while the other starts up. On occasion, you may need to c oordinate these activities, one with the other. The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process: 1. The current activity's onPause() method is called. 2. Next, the starting acti vity's onCreate(), onStart(), and onResume() methods are called in sequence. 3. Then, if the starting activity is no longer visible on screen, its onStop() meth

od is called. http://developer.android.com/guide/topics/fundamentals.html Page 15 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 Service lifecycle A service can be used in two ways: It can be started and allowed to run until so meone stops it or it stops itself. In this mode, it's started by calling Context .startService() and stopped by calling Context.stopService(). It can stop itself by calling Service.stopSelf() or Service.stopSelfResult(). Only one stopService () call is needed to stop the service, no matter how many times startService() w as called. It can be operated programmatically using an interface that it define s and exports. Clients establish a connection to the Service object and use that connection to call into the service. The connection is established by calling C ontext.bindService(), and is closed by calling Context.unbindService(). Multiple clients can bind to the same service. If the service has not already been launc hed, bindService() can optionally launch it. The two modes are not entirely sepa rate. You can bind to a service that was started with startService(). For exampl e, a background music service could be started by calling startService() with an Intent object that identifies the music to play. Only later, possibly when the user wants to exercise some control over the player or get information about the current song, would an activity establish a connection to the service by callin g bindService(). In cases like this, stopService() will not actually stop the se rvice until the last binding is closed. Like an activity, a service has lifecycl e methods that you can implement to monitor changes in its state. But they are f ewer than the activity methods only three and they are public, not protected: vo id onCreate() void onStart(Intent intent) void onDestroy() By implementing these methods, you can monitor two nested loops of the service's lifecycle: The entir e lifetime of a service happens between the time onCreate() is called and the ti me onDestroy() returns. Like an activity, a service does its initial setup in on Create(), and releases all remaining resources in onDestroy(). For example, a mu sic playback service could create the thread where the music will be played in o nCreate(), and then stop the thread in onDestroy(). The active lifetime of a ser vice begins with a call to onStart(). This method is handed the Intent object th at was passed to startService(). The music service would open the Intent to disc over which music to play, and begin the playback. There's no equivalent callback for when the service stops no onStop() method. The onCreate() and onDestroy() m ethods are called for all services, whether they're started by Context.startServ ice() or Context.bindService(). However, onStart() is called only for services s tarted by startService(). If a service permits others to bind to it, there are a dditional callback methods for it to implement: IBinder onBind(Intent intent) bo olean onUnbind(Intent intent) void onRebind(Intent intent) The onBind() callback is passed the Intent object that was passed to bindService and onUnbind() is ha nded the intent that was passed to unbindService(). If the service permits the b inding, onBind() returns the communications channel that clients use to interact with the service. The onUnbind() method can ask for onRebind() to be called if a new client connects to the service. The following diagram illustrates the call back methods for a service. Although, it separates services that are created via startService from those created by bindService(), keep in mind that any service , no matter how it's started, can potentially allow clients to bind to it, so an y service may receive onBind() and onUnbind() calls. http://developer.android.com/guide/topics/fundamentals.html Page 16 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 Broadcast receiver lifecycle A broadcast receiver has single callback method: void onReceive(Context curConte xt, Intent broadcastMsg) When a broadcast message arrives for the receiver, Andr oid calls its onReceive() method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is exec uting this method. When onReceive() returns, it is inactive. A process with an a ctive broadcast receiver is protected from being killed. But a process with only inactive components can be killed by the system at any time, when the memory it consumes is needed by other processes. This presents a problem when the respons e to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. If onReceive() spawns the thread and then returns, th e entire process, including the new thread, is judged to be inactive (unless oth er application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is for onReceive() to start a service and let the service do the job, so the system knows that there is still active work being done in the process. The next section has more on the vulnerability o f processes to being killed. http://developer.android.com/guide/topics/fundamentals.html Page 17 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 Processes and lifecycles The Android system tries to maintain an application process for as long as possi ble, but eventually it will need to remove old processes when memory runs low. T o determine which processes to keep and which to kill, Android places each proce ss into an "importance hierarchy" based on the components running in it and the state of those components. Processes with the lowest importance are eliminated f irst, then those with the next lowest, and so on. There are five levels in the h ierarchy. The following list presents them in order of importance: 1. A foregrou nd process is one that is required for what the user is currently doing. A proce ss is considered to be in the foreground if any of the following conditions hold : It is running an activity that the user is interacting with (the Activity obje ct's onResume() method has been called). It hosts a service that's bound to the activity that the user is interacting with. It has a Service object that's execu ting one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()). It has a BroadcastReceiver object that's executing its onReceive() method. Only a f ew foreground processes will exist at any given time. They are killed only as a last resort if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some fo reground processes is required to keep the user interface responsive. 2. A visib le process is one that doesn't have any foreground components, but still can aff ect what the user sees on screen. A process is considered to be visible if eithe r of the following conditions holds: It hosts an activity that is not in the for eground, but is still visible to the user (its onPause() method has been called) . This may occur, for example, if the foreground activity is a dialog that allow s the previous activity to be seen behind it. It hosts a service that's bound to a visible activity. A visible process is considered extremely important and wil l not be killed unless doing so is required to keep all foreground processes run ning. 3. A service process is one that is running a service that has been starte d with the startService() method and that does not fall into either of the two h igher categories. Although service processes are not directly tied to anything t he user sees, they are generally doing things that the user cares about (such as playing an mp3 in the background or downloading data on the network), so the sy stem keeps them running unless there's not enough memory to retain them along wi th all foreground and visible processes. 4. A background process is one holding an activity that's not currently visible to the user (the Activity object's onSt op() method has been called). These processes have no direct impact on the user experience, and can be killed at any time to reclaim memory for a foreground, vi sible, or service process. Usually there are many background processes running, so they are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be kil led. If an activity implements its lifecycle methods correctly, and captures its current state, killing its process will not have a deleterious effect on the us er experience. 5. An empty process is one that doesn't hold any active applicati on components. The only reason to keep such a process around is as a cache to im prove startup time the next time a component needs to run in it. The system ofte n kills these processes in order to balance overall system resources between pro cess caches and the underlying kernel caches. Android ranks a process at the hig hest level it can, based upon the importance of the components currently active in the process. For example, if a process hosts a service and a visible activity , the process will be ranked as a visible process, not a service process. In add ition, a process's ranking may be increased because other processes are dependen t on it. A process that is serving another process can never be ranked lower tha n the process it is serving. For example, if a content provider in http://developer.android.com/guide/topics/fundamentals.html Page 18 of 19

Application Fundamentals | Android Developers 29.04.09 0:33 serving another process can never be ranked lower than the process it is serving . For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A will always be considered at least as important as process B. Because a process running a service is ranked higher than one with background activities, an acti vity that initiates a long-running operation might do well to start a service fo r that operation, rather than simply spawn a thread particularly if the operatio n will likely outlast the activity. Examples of this are playing music in the ba ckground and uploading a picture taken by the camera to a web site. Using a serv ice guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle section earlier, this is the same reason that broadcast receivers shou ld employ services rather than simply put timeconsuming operations in a thread. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/fundamentals.html Page 19 of 19

User Interface | Android Developers 29.04.09 0:34 User Interface In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a desce ndant of the View class. View objects are the basic units of user interface expr ession on the Android platform. The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields an d buttons. The ViewGroup class serves as the base for subclasses called "layouts ," which offer different kinds of layout architecture, like linear, tabular and relative. A View object is a data structure whose properties store the layout pa rameters and content for a specific rectangular area of the screen. A View objec t handles its own measurement, layout, drawing, focus change, scrolling, and key /gesture interactions for the rectangular area of the screen in which it resides . As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events. View Hierarchy On the Android platform, you define an Activity's UI using a hierarchy of View a nd ViewGroup nodes, as shown in the diagram below. This hierarchy tree can be as simple or complex as you need it to be, and you can build it up using Android's set of predefined widgets and layouts, or with custom Views that you create you rself. In order to attach the view hierarchy tree to the screen for rendering, your Act ivity must call the setContentView() method and pass a reference to the root nod e object. The Android system receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests that its chi ld nodes draw themselves in turn, each view group node is responsible for callin g upon each of its own child views to draw themselves. The children may request a size and location within the parent, but the parent object has the final decis ion on where how big each child can be. Android parses the elements of your layo ut in-order (from the top of the hierarchy tree), instantiating the Views and ad ding them to their parent(s). Because these are drawn in-order, if there are ele ments that overlap positions, the last one to be drawn will lie on top of others previously drawn to that space. For a more detailed discussion on how view hier archies are measured and drawn, read How Android Draws Views. Layout http://developer.android.com/guide/topics/ui/index.html Page 1 of 4

User Interface | Android Developers 29.04.09 0:34 The most common way to define your layout and express the view hierarchy is with an XML layout file. XML offers a human-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object (or descende nt thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree (see the View Hierarchy figure above). The name of an XML element i s respective to the Java class that it represents. So a <TextView> element creat es a TextView in your UI, and a <LinearLayout> element creates a LinearLayout vi ew group. When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout. For example, a s imple vertical layout with a text view and a button looks like this: <?xml versi on="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android. com/apk/res/android" android:layout_width="fill_parent" android:layout_height="f ill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" an droid:layout_width="wrap_content" android:layout_height="wrap_content" android:t ext="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_ width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> Notice that the LinearLayout element contains b oth the TextView and the Button. You can nest another LinearLayout (or other typ e of view group) inside here, to lengthen the view hierarchy and create a more c omplex layout. For more on building a UI layout, read Declaring Layout. There ar e a variety of ways in which you can layout your views. Using more and different kinds of view groups, you can structure child views and view groups in an infin ite number of ways. Some pre-defined view groups offered by Android (called layo uts) include LinearLayout, RelativeLayout, AbsoluteLayout, TableLayout, GridLayo ut and others. Each offers a unique set of layout parameters that are used to de fine the positions of child views and layout structure. Tip: You can also draw View and ViewGroups objects in Java code, using the addVi ew(View) methods to dynamically insert new View and ViewGroup objects. To learn about some of the different kinds of view groups used for a layout, rea d Common Layout Objects. Widgets A widget is a View object that serves as an interface for interaction with the u ser. Android provides a set of fully implemented widgets, like buttons, checkbox es, and text-entry fields, so you can quickly build your UI. Some widgets provid ed by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kinds of widgets provided by the Android platform. If you'd like to do something more customized and create your own actionable el ements, you can, by defining your own View object or by extending and combining existing widgets. Read more in Building Custom Components. For a list of the wid gets provided by Android, see the android.widget package. UI Events http://developer.android.com/guide/topics/ui/index.html Page 2 of 4

User Interface | Android Developers 29.04.09 0:34 Once you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, so you can perform actions. To be informed of UI events, you need to do one of two things: Define an event listener and regist er it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On<something>Lis tener, each with a callback method called On<something>(). For example, View.OnC lickListener (for handling "clicks" on a View), View.OnTouchListener (for handli ng touch screen events in a View), and View.OnKeyListener (for handling device k ey presses within a View). So if you want your View to be notified when it is "c licked" (such as when a button is selected), implement OnClickListener and defin e its onClick() callback method (where you perform the action upon click), and r egister it to the View with setOnClickListener(). Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it. Example events you can handle include when the screen is touched (onTouchEvent()), when the trackball is moved (onTrackballEvent()), or when a key on the device is pre ssed (onKeyDown()). This allows you to define the default behavior for each even t inside your custom View and determine whether the event should be passed on to some other child View. Again, these are callbacks to the View class, so your on ly chance to define them is when you build a custom component. Continue reading about handling user interaction with Views in the Handling UI Events document. Menus Application menus are another important part of an application's UI. Menus offer s a reliable interface that reveals application functions and settings. The most common application menu is revealed by pressing the MENU key on the device. How ever, you can also add Context Menus, which may be revealed when the user presse s and holds down on an item. Menus are also structured using a View hierarchy, b ut you don't define this structure yourself. Instead, you define the onCreateOpt ionsMenu() or onCreateContextMenu() callback methods for your Activity and decla re the items that you want to include in your menu. At the appropriate time, And roid will automatically create the necessary View hierarchy for the menu and dra w each of your menu items in it. Menus also handle their own events, so there's no need to register event listeners on the items in your menu. When an item in y our menu is selected, the onOptionsItemSelected() or onContextItemSelected() met hod will be called by the framework. And just like your application layout, you have the option to declare the items for you menu in an XML file. Read Creating Menus to learn more. Advanced Topics Once you've grappled the fundamentals of creating a user interface, you can expl ore some advanced features for creating a more complex application interface. Adapters Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, you want to bind your view to an external source of data . To do this, you use an AdapterView as your view group and each child View is i nitialized and populated with data from the Adapter. The AdapterView object is a n implementation of ViewGroup that determines its child views based on a given A dapter object. The Adapter acts like a courier between your data source (perhaps an array of external strings) and the AdapterView, which displays it. There are several implementations of the Adapter class, for specific tasks, such as the http://developer.android.com/guide/topics/ui/index.html Page 3 of 4

User Interface | Android Developers 29.04.09 0:34 AdapterView, which displays it. There are several implementations of the Adapter class, for specific tasks, such as the CursorAdapter for reading database data from a Cursor, or an ArrayAdapter for reading from an arbitrary array. To learn more about using an Adapter to populate your views, read Binding to Data with Ad apterView. Styles and Themes Perhaps you're not satisfied with the look of the standard widgets. To revise th em, you can create some of your own styles and themes. A style is a set of one o r more formatting attributes that you can apply as a unit to individual elements in your layout. For example, you could define a style that specifies a certain text size and color, then apply it to only specific View elements. A theme is a set of one or more formatting attributes that you can apply as a unit to all act ivities in an application, or just a single activity. For example, you could def ine a theme that sets specific colors for the window frame and the panel backgro und, and sets text sizes and colors for menus. This theme can then be applied to specific activities or the entire application. Styles and themes are resources. Android provides some default style and theme resources that you can use, or yo u can declare your own custom style and theme resources. Learn more about using styles and themes in the Applying Styles and Themes document. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/index.html Page 4 of 4

Declaring Layout | Android Developers 29.04.09 0:36 User Interface > Declaring Layout Your layout is the architecture for the user interface in an Activity. It define s the layout structure and holds all the elements that appear to the user. You c an declare your layout in two ways: Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subcl asses, such as those for widgets and layouts. Instantiate layout elements at run time. Your application can create View and ViewGroup objects (and manipulate the ir properties) programmatically. The Android framework gives you the flexibility to use either or both of these methods for declaring and managing your applicat ion's UI. For example, you could declare your application's default layouts in X ML, including the screen elements that will appear in them and their properties. You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time. The advantage to d eclaring your UI in XML is that it enables you to better separate the presentati on of your application from the code that controls its behavior. Your UI descrip tions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, y ou can create XML layouts for different screen orientations, different device sc reen sizes, and different languages. Additionally, declaring the layout in XML m akes it easier to visualize the structure of your UI, so it's easier to debug pr oblems. As such, this document focuses on teaching you how to declare your layou t in XML. If you're interested in instantiating View objects at runtime, refer t o the ViewGroup and View class references. The Android Development Tools (ADT) plugin for Eclipse offers a layout preview o f your XML with the XML file opened, select the Layout tab. You should also try the Hierarchy Viewer tool, for debugging layouts it reveals layout property valu es, draws wireframes with padding/margin indicators, and full rendered views whi le you debug on the emulator or device. In general, the XML vocabulary for declaring UI elements closely follows the str ucture and naming of the classes and methods, where element names correspond to class names and attribute names correspond to methods. In fact, the corresponden ce is often so direct that you can guess what XML attribute corresponds to a cla ss method, or guess what class corresponds to a given xml element. However, note that not all vocabulary is identical. In some cases, there are slight naming di fferences. For example, the EditText element has a text attribute that correspon ds to EditText.setText(). Tip: Learn more about different layout types in Common Layout Objects. There are also a collection of tutorials on building various la youts in the Hello Views tutorial guide. Write the XML Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML with a seri es of nested elements. Each layout file must contain exactly one root element, w hich must be a View or ViewGroup object. Once you've defined the root element, y ou can add additional layout objects or widgets as child elements to gradually b uild a View hierarchy that defines your layout. For example, here's an XML layou t that uses a vertical http://developer.android.com/guide/topics/ui/declaring-layout.html For your convenience, the API reference documentation for UI related classes lis ts the available XML attributes that correspond to the class methods, including inherited attributes. To learn more about the available XML elements and attribu tes, as well as the format of the XML file, see Layout Resources.

Page 1 of 5

Declaring Layout | Android Developers 29.04.09 0:36 layout. For example, here's an XML layout that uses a vertical LinearLayout to h old a TextView and a Button: <?xml version="1.0" encoding="utf-8"?> <LinearLayou t xmlns:android="http://schemas.android.com/apk/res/android" android:layout_widt h="fill_parent" android:layout_height="fill_parent" android:orientation="vertica l" > <TextView android:id="@+id/text" android:layout_width="wrap_content" androi d:layout_height="wrap_content" android:text="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_heig ht="wrap_content" android:text="Hello, I am a Button" /> </LinearLayout> After y ou've declared your layout in XML, save the file with the .xml extension, in you r Android project's res/layout/ directory, so it will properly compile. We'll di scuss each of the attributes shown here a little later. Load the XML Resource When you compile your application, each XML layout file is compiled into a View resource. You should load the layout resource from your application code, in you r Activity.onCreate() callback implementation. Do so by calling setContentView() , passing it the reference to your layout resource in the form of: R.layout.layo ut_file_name For example, if your XML layout is saved as main_layout.xml, you wo uld load it for your Activity like so: public void onCreate(Bundle savedInstance State) { super.onCreate(savedInstanceState); setContentView.(R.layout.main_layou t); } The onCreate() callback method in your Activity is called by the Android f ramework when your Activity is launched (see the discussion on Lifecycles, in th e Application Fundamantals, for more on this). Attributes Every View and ViewGroup object supports their own variety of XML attributes. So me attributes are specific to a View object (for example, TextView supports the textSize attribute), but these attributes are also inherited by any View objects that may extend this class. Some are common to all View objects, because they a re inherited from the root View class (like the id attribute). And, other attrib utes are considered "layout parameters," which are attributes that describe cert ain layout orientations of the View object, as defined by that object's parent V iewGroup object. ID Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. When the application is compiled, this ID is reference d as an integer, but the ID is typically assigned in the layout XML file as a st ring, in the id attribute. This is an XML attribute common to all View objects ( defined by the View class) and you will use it very often. The syntax for an ID, inside an XML tag is: http://developer.android.com/guide/topics/ui/declaring-layout.html Page 2 of 5

Declaring Layout | Android Developers 29.04.09 0:36 android:id="@+id/my_button" The at-symbol (@) at the beginning of the string ind icates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+) means that this is a new res ource name that must be created and added to our resources (in the R.java file). There are a number of other ID resources that are offered by the Android framew ork. When referencing an Android resource ID, you do not need the plus-symbol, b ut must add the android package namespace, like so: android:id="@android:id/empt y" With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class. In order to create views and reference them from the application, a common pattern is to: 1. Define a view/widget in the layout file and assign it a unique ID: <Button a ndroid:id="@+id/my_button" android:layout_width="wrap_content" android:layout_he ight="wrap_content" android:text="@string/my_button_text"/> 2. Then create an in stance of the view object and capture it from the layout (typically in the onCre ate() method): Button myButton = (Button) findViewById(R.id.my_button); Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID. An ID need not be unique throughout the e ntire tree, but it should be unique within the part of the tree you are searchin g (which may often be the entire tree, so it's best to be completely unique when possible). Layout Parameters XML layout attributes named layout_something define layout parameters for the Vi ew that are appropriate for the ViewGroup in which it resides. Every ViewGroup c lass implements a nested class that extends ViewGroup.LayoutParams. This subclas s contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in the figure below, the pare nt view group defines layout parameters for each child view (including the child view group). http://developer.android.com/guide/topics/ui/declaring-layout.html Page 3 of 5

Declaring Layout | Android Developers 29.04.09 0:36 Note that every LayoutParams subclass has its own syntax for setting values. Eac h child element must define LayoutParams that are appropriate for its parent, th ough it may also define different LayoutParams for its own children. All view gr oups include a width and height (layout_width and layout_height), and each view is required to define them. Many LayoutParams also include optional margins and borders. You can specify width and height with exact measurements, though you pr obably won't want to do this often. More often, you will tell your view to size itself either to the dimensions required by its content, or to become as big as its parent view group will allow (with the wrap_content and fill_parent values, respectively). The accepted measurement types are defined in the Available Resou rces document. Layout Position The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel. It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop( ). The former returns the left, or X, coordinate of the rectangle representing t he view. The latter returns the top, or Y, coordinate of the rectangle represent ing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent. In addition, seve ral convenience methods are offered to avoid unnecessary computations, namely ge tRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRi ght() is similar to the following computation: getLeft() + getWidth(). Size, Padding and Margins The size of a view is expressed with a width and a height. A view actually posse ss two pairs of width and height values. The first pair is known as measured wid th and measured height. These dimensions define how big a view wants to be withi n its parent. The measured dimensions can be obtained by calling getMeasuredWidt h() and getMeasuredHeight(). The second pair is simply known as width and height , or sometimes drawing width and drawing height. These dimensions define the act ual size of the view on screen, at drawing time and after layout. These values m ay, but do not have to, be different from the measured width and height. The wid th and height can be obtained by calling http://developer.android.com/guide/topics/ui/declaring-layout.html Page 4 of 5

Declaring Layout | Android Developers 29.04.09 0:36 getWidth() and getHeight(). To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bo ttom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the vi ew's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft (), getPaddingTop(), getPaddingRight() and getPaddingBottom(). Even though a vie w can define a padding, it does not provide any support for margins. However, vi ew groups provide such a support. Refer to ViewGroup and ViewGroup.MarginLayoutP arams for further information. For more information about dimensions, see Dimens ion Values. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/declaring-layout.html Page 5 of 5

Creating Menus | Android Developers 29.04.09 0:37 User Interface > Creating Menus Menus are an important part of any application. They provide familiar interfaces that reveal application functions and settings. Android offers an easy programm ing interface for developers to provide standardized application menus for vario us situations. Android offers three fundamental types of application menus: Opti ons Menu This is the primary set of menu items for an Activity. It is revealed b y pressing the device MENU key. Within the Options Menu are two groups of menu i tems: Icon Menu This is the collection of items initially visible at the bottom of the screen at the press of the MENU key. It supports a maximum of six menu it ems. These are the only menu items that support icons and the only menu items th at do not support checkboxes or radio buttons. Expanded Menu This is a vertical list of items exposed by the "More" menu item from the Icon Menu. It exists only when the Icon Menu becomes over-loaded and is comprised of the sixth Option Men u item and the rest. Context Menu This is a floating list of menu items that may appear when you perform a long-press on a View (such as a list item). Submenu T his is a floating list of menu items that is revealed by an item in the Options Menu or a Context Menu. A Submenu item cannot support nested Submenus. Options Menu The Options Menu is opened by pressing the device MENU key. When opened, the Ico n Menu is displayed, which holds the first six menu items. If more than six item s are added to the Options Menu, then those that can't fit in the Icon Menu are revealed in the Expanded Menu, via the "More" menu item. The Expanded Menu is au tomatically added when there are more than six items. The Options Menu is where you should include basic application functions and any necessary navigation item s (e.g., to a home screen or application settings). You can also add Submenus fo r organizing topics and including extra menu functionality. When this menu is op ened for the first time, the Android system will call the Activity onCreateOptio nsMenu() callback method. Override this method in your Activity and populate the Menu object given to you. You can populate the menu by inflating a menu resourc e that was defined in XML, or by calling add() for each item you'd like in the m enu. This method adds a MenuItem, and returns the newly created object to you. Y ou can use the returned MenuItem to set additional properties like an icon, a ke yboard shortcut, an intent, and other settings for the item. http://developer.android.com/guide/topics/ui/menus.html Page 1 of 8

Creating Menus | Android Developers 29.04.09 0:37 for the item. There are multiple add() methods. Usually, you'll want to use one that accepts an itemId argument. This is a unique integer that allows you to ide ntify the item during a callback. When a menu item is selected from the Options Menu, you will recieve a callback to the onOptionsItemSelected() method of your Activity. This callback passes you the MenuItem that has been selected. You can identify the item by requesting the itemId, with getItemId(), which returns the integer that was assigned with the add() method. Once you identify the menu item , you can take the appropriate action. Here's an example of this procedure, insi de an Activity, wherein we create an Options Menu and handle item selections: /* Creates the menu items */ public boolean onCreateOptionsMenu(Menu menu) { menu. add(0, MENU_NEW_GAME, 0, "New Game"); menu.add(0, MENU_QUIT, 0, "Quit"); return true; } /* Handles item selections */ public boolean onOptionsItemSelected(MenuI tem item) { switch (item.getItemId()) { case MENU_NEW_GAME: newGame(); return tr ue; case MENU_QUIT: quit(); return true; } return false; } The add() method used in this sample takes four arguments: groupId, itemId, order, and title. The gro upId allows you to associate this menu item with a group of other items (more ab out Menu groups, below) in this example, we ignore it. itemId is a unique intege r that we give the MenuItem so that can identify it in the next callback. order allows us to define the display order of the item by default, they are displayed by the order in which we add them. title is, of course, the name that goes on t he menu item (this can also be a string resource, and we recommend you do it tha t way for easier localization). Tip: If you have several menu items that can be grouped together with a title, consider organizing them into a Submenu. Adding icons Icons can also be added to items that appears in the Icon Menu with setIcon(). F or example: menu.add(0, MENU_QUIT, 0, "Quit") .setIcon(R.drawable.menu_quit_icon ); Modifying the menu If you want to sometimes re-write the Options Menu as it is opened, override the onPrepareOptionsMenu() method, which is called each time the menu is opened. Th is will pass you the Menu object, just like the onCreateOptionsMenu() callback. This is useful if you'd like to add or remove menu options depending on the curr ent state of an application or game. Note: When changing items in the menu, it's bad practice to do so based on the currently selected item. Keep in mind that, when in touch mode, there will not be a selected (or focused) item. Instead, you should use a Context Menu for such behaviors, when you want to provide function ality based on a particular item in the UI. http://developer.android.com/guide/topics/ui/menus.html Page 2 of 8

Creating Menus | Android Developers 29.04.09 0:37 Context Menu for such behaviors, when you want to provide functionality based on a particular item in the UI. Context Menu The Android context menu is similar, in concept, to the menu revealed with a "ri ght-click" on a PC. When a view is registered to a context menu, performing a "l ong-press" (press and hold for about two seconds) on the object will reveal a fl oating menu that provides functions relating to that item. Context menus can be registered to any View object, however, they are most often used for items in a ListView, which helpfully indicates the presence of the context menu by transfor ming the background color of the ListView item when pressed. (The items in the p hone's contact list offer an example of this feature.) Note: Context menu items do not support icons or shortcut keys. To create a context menu, you must overri de the Activity's context menu callback methods: onCreateContextMenu() and onCon textItemSelected(). Inside the onCreateContextMenu() callback method, you can ad d menu items using one of the add() methods, or by inflating a menu resource tha t was defined in XML. Then, register a ContextMenu for the View, with registerFo rContextMenu(). For example, here is some code that can be used with the Notepad application to add a context menu for each note in the list: public void onCrea teContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCrea teContextMenu(menu, v, menuInfo); menu.add(0, EDIT_ID, 0, "Edit"); menu.add(0, D ELETE_ID, 0, "Delete"); } public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switc h (item.getItemId()) { case EDIT_ID: editNote(info.id); return true; case DELETE _ID: deleteNote(info.id); return true; default: return super.onContextItemSelect ed(item); } } In onCreateContextMenu(), we are given not only the ContextMenu to which we will add MenuItems, but also the View that was selected and a ContextM enuInfo object, which provides additional information about the object that was selected. In this example, nothing special is done in onCreateContextMenu() just a couple items are added as usual. In the onContextItemSelected() callback, we request the AdapterContextMenuInfo from the MenuItem, which provides information about the currently selected item. All we need from this is the list ID for the selected item, so whether editing a note or deleting it, we find the ID with th e AdapterContextMenuInfo.info field of the object. This ID is passed to the edit Note() and deleteNote() methods to perfrom the respective action. Now, to regist er this context menu for all the items in a ListView, we pass the entire ListVie w to the registerForContextMenu(View) method: registerForContextMenu(getListView ()); Remember, you can pass any View object to register a context menu. Here, ge tListView() returns the ListView object used in the Notepad application's ListAc tivity. As such, each item in the list is registered to this context menu. http://developer.android.com/guide/topics/ui/menus.html Page 3 of 8

Creating Menus | Android Developers 29.04.09 0:37 Submenus A sub menu can be added within any menu, except another sub menu. These are very useful when your application has a lot of functions that may be organized in to pics, like the items in a PC application's menu bar (File, Edit, View, etc.). A sub menu is created by adding it to an existing Menu with addSubMenu(). This ret urns a SubMenu object (an extension of Menu). You can then add additional items to this menu, with the normal routine, using the add() methods. For example: pub lic boolean onCreateOptionsMenu(Menu menu) { boolean result = super.onCreateOpti onsMenu(menu); SubMenu fileMenu = menu.addSubMenu("File"); SubMenu editMenu = me nu.addSubMenu("Edit"); fileMenu.add("new"); fileMenu.add("open"); fileMenu.add(" save"); editMenu.add("undo"); editMenu.add("redo"); } Callbacks for items select ed in a sub menu are made to the parent menu's callback method. For the example above, selections in the sub menu will be handled by the onOptionsItemSelected() callback. You can also add Submenus when you define the parent menu in XML. ret urn result; Define Menus in XML Just like Android UI layouts, you can define application menus in XML, then infl ate them in your menu's onCreate...() callback method. This makes your applicati on code cleaner and separates more interface design into XML, which is easier to visualize. To start, create a new folder in your project res/ directory called menu. This is where you should keep all XML files that define your application m enus. In a menu XML layout, there are three valid elements: <menu>, <group> and <item>. The item and group elements must be children of a menu, but item element s may also be the children of a group, and another menu element may be the child of an item (to create a Submenu). Of course, the root node of any file must be a menu element. As an example, we'll define the same menu created in the Options Menu section, above. We start with an XML file named options_menu.xml inside th e res/menu/ folder: <menu xmlns:android="http://schemas.android.com/apk/res/andr oid"> <item android:id="@+id/new_game" android:title="New Game" /> <item android :id="@+id/quit" android:title="Quit" /> </menu> Then, in the onCreateOptionsMenu () method, we inflate this resource using MenuInflater.inflate(): http://developer.android.com/guide/topics/ui/menus.html Page 4 of 8

Creating Menus | Android Developers 29.04.09 0:37 public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuI nflater(); inflater.inflate(R.menu.options_menu, menu); return true; } The getMe nuInflater() method returns the MenuInflater for our activity's context. We then call inflate(), passing it a pointer to our menu resource and the Menu object g iven by the callback. While this small sample may seem like more effort, compare d to creating the menu items in the onCreateOptionsMenu() method, this will save a lot of trouble when dealing with more items and it keeps your application cod e clean. You can define menu groups by wrapping item elements in a group element , and create Submenus by nesting another menu inside an item. Each element also supports all the necessary attributes to control features like shortcut keys, ch eckboxes, icons, and more. To learn about these attributes and more about the XM L syntax, see the Menus topic in the Available Resource Types document. Menu Features Here are some other features that can be applied to most menu items. Menu groups When adding new items to a menu, you can optionally include each item in a group . A menu group is a collection of menu items that can share certain traits, like whether they are visible, enabled, or checkable. A group is defined by an integ er (or a resource id, in XML). A menu item is added to the group when it is adde d to the menu, using one of the add() methods that accepts a groupId as an argum ent, such as add(int, int, int, int). You can show or hide the entire group with setGroupVisible(); enable or disable the group with setGroupEnabled(); and set whether the items can be checkable with setGroupCheckable(). Checkable menu items Any menu item can be used as an interface for turning options on and off. This c an be indicated with a checkbox for stand-alone options, or radio buttons for gr oups of mutually exlusive options (see the screenshot, to the right). Note: Menu items in the Icon Menu cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, then you must personally indicate the state by swapping the icon and/or text each time the state changes between on a nd off. To make a single item checkable, use the setCheckable() method, like so: menu.add(0, VIBRATE_SETTING_ID, 0, "Vibrate") .setCheckable(true); This will di splay a checkbox with the menu item (unless it's in the Icon Menu). When the ite m is selected, the onOptionsItemSelected() callback is called as usual. It is he re that you must set the state of the checkbox. You can query the current state of the item with isChecked() and set the checked state with setChecked(). Here's what this looks like inside the onOptionsItemSelected() callback: http://developer.android.com/guide/topics/ui/menus.html Page 5 of 8

Creating Menus | Android Developers 29.04.09 0:37 onOptionsItemSelected() callback: switch (item.getItemId()) { case VIBRATE_SETTI NG_ID: if (item.isChecked()) item.setChecked(false); else item.setChecked(true); return true; ... } To make a group of mutually exclusive radio button items, si mply assign the same group ID to each menu item and call setGroupCheckable(). In this case, you don't need to call setCheckable() on each menu items, because th e group as a whole is set checkable. Here's an example of two mutually exclusive options in a Submenu: SubMenu subMenu = menu.addSubMenu("Color"); subMenu.add(C OLOR_MENU_GROUP, COLOR_RED_ID, 0, "Red"); subMenu.add(COLOR_MENU_GROUP, COLOR_BL UE_ID, 0, "Blue"); subMenu.setGroupCheckable(COLOR_MENU_GROUP, true, true); In t he setGroupCheckable() method, the first argument is the group ID that we want t o set checkable. The second argument is whether we want the group items to be ch eckable. The last one is whether we want each item to be exclusively checkable ( if we set this false, then all the items will be checkboxes instead of radio but tons). When the group is set to be exclusive (radio buttons), each time a new it em is selected, all other are automatically de-selected. Note: Checkable menu it ems are intended to be used only on a per-session basis and not saved to the dev ice (e.g., the Map mode setting in the Maps application is not saved screenshot above). If there are application settings that you would like to save for the us er, then you should store the data using Preferences, and manage them with a Pre ferenceActivity. Shortcut keys Quick access shortcut keys using letters and/or numbers can be added to menu ite ms with setAlphabeticShortcut(char) (to set char shortcut), setNumericShortcut(i nt) (to set numeric shortcut), or setShortcut(char,int) (to set both). Case is n ot sensitive. For example: menu.add(0, MENU_QUIT, 0, "Quit") .setAlphabeticShort cut('q'); Now, when the menu is open (or while holding the MENU key), pressing t he "q" key will select this item. This shortcut key will be displayed as a tip i n the menu item, below the menu item name (except for items in the Icon Menu). N ote: Shortcuts cannot be added to items in a Context Menu. Menu item intents If you've read the Application Fundamentals, then you're at least a little famil iar with Android Intents. These allow applications to bind with each other, shar e information, and perform user tasks cooperatively. Just like your application might fire an Intent to launch a web browser, an email client, or another Activi ty in your application, you can perform such actions from within a menu. There a re two ways to do this: define an Intent and assign it to a single menu item, or define an Intent and allow Android to search the device for activities and dyna mically add a menu item for each one that meets the Intent criteria. For more in formation on creating Intents and providing your application's services to other applications, read the Intents and Intent Filters document. http://developer.android.com/guide/topics/ui/menus.html Page 6 of 8

Creating Menus | Android Developers 29.04.09 0:37 Set an intent for a single menu item If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the setIntent() method . For example, inside the onCreateOptionsMenu() method, you can define a new men u item with an Intent like this: MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID , 0, "Select Photo"); menuItem.setIntent(new Intent(this, PhotoPicker.class)); A ndroid will automatically launch the Activity when the item is selected. Note: T his will not return a result to your Activity. If you wish to be returned a resu lt, then do not use setIntent(). Instead, handle the selection as usual in the o nOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call star tActivityForResult(). Dynamically add intents If there are potentially multiple activities that are relevant to your current A ctivity or selected item, then the application can dynamically add menu items th at execute other services. During menu creation, define an Intent with the categ ory Intent.ALTERNATIVE_CATEGORY and/or Intent.SELECTED_ALTERNATIVE, the MIME typ e currently selected (if any), and any other requirements, the same way as you w ould satisfy an intent filter to open a new Activity. Then call addIntentOptions () to have Android search for any services meeting those requirements and add th em to the menu for you. If there are no applications installed that satisfy the Intent, then no additional menu items are added. Note: SELECTED_ALTERNATIVE is u sed to handle the currently selected element on the screen. So, it should only b e used when creating a Menu in onCreateContextMenu() or onPrepareOptionsMenu(), which is called every time the Options Menu is opened. Here's an example demonst rating how an application would search for additional services to display on its menu. public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu( menu); // Create an Intent that describes the requirements to fulfill, to be inc luded // in our menu. The offering app must include a category value of Intent.C ATEGORY_ALTERNATIVE. Intent intent = new Intent(null, getIntent().getData()); in tent.addCategory(Intent.CATEGORY_ALTERNATIVE); // Search for, and populate the m enu with, acceptable offering applications. menu.addIntentOptions( thisClass.INT ENT_OPTIONS, // Menu group 0, // Unique item ID (none) 0, // Order for the items (none) this.getComponentName(), // The current Activity name null, // Specific items to place first (none) intent, // Intent created above that describes our r equirements 0, // Additional flags to control items (none) null); // Array of Me nuItems that corrolate to specific items (none) } For each Activity found that p rovides an Intent Filter matching the Intent defined, a menu item will be added, using the android:label value of the intent filter as the text for the menu ite m. The addIntentOptions() method will also return the number of menu items added . Also be aware that, when addIntentOptions() is called, it will override any an d all menu items in the menu group specified in the first argument. http://developer.android.com/guide/topics/ui/menus.html Page 7 of 8 return true;

Creating Menus | Android Developers 29.04.09 0:37 If you wish to offer the services of your Activity to other application menus, t hen you only need to define an intent filter as usual. Just be sure to include t he ALTERNATIVE and/or SELECTED_ALTERNATIVE values in the name attribute of a <ca tegory> element in the intent filter. For example: <intent-filter label="Resize Image"> ... <category android:name="android.intent.category.ALTERNATIVE" /> <cat egory android:name="android.intent.category.SELECTED_ALTERNATIVE" /> ... </inten t-filter> read more about writing intent filters in the Intents and Intent Filte rs document. For a sample application using this technique, see the Note Pad sam ple code. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/menus.html Page 8 of 8

Creating Dialogs | Android Developers 29.04.09 0:37 User Interface > Creating Dialogs A dialog is usually a small window that appears in front of the current Activity . The underlying Activity loses focus and the dialog accepts all user interactio n. Dialogs are normally used for notifications and short activities that directl y relate to the application in progress. The Android API supports the following types of Dialog objects: AlertDialog A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user inte rfaces and is the suggested dialog type. See Creating an AlertDialog below. Prog ressDialog A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons. See Creating a Progr essDialog below. DatePickerDialog A dialog that allows the user to select a date . See the Hello DatePicker tutorial. TimePickerDialog A dialog that allows the u ser to select a time. See the Hello TimePicker tutorial. If you would like to cu stomize your own dialog, you can extend the base Dialog object or any of the sub classes listed above and define a new layout. See the section on Creating a Cust om Dialog below. Showing a Dialog A dialog is always created and displayed as a part of an Activity. You should no rmally create dialogs from within your Activity's onCreateDialog(int) callback m ethod. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the " owner" of each dialog. As such, each dialog inherits certain properties from the Activity. For example, when a dialog is open, the Menu key reveals the options menu defined for the Activity and the volume keys modify the audio stream used b y the Activity. Note: If you decide to create a dialog outside of the onCreateDi alog() method, it will not be attached to an Activity. You can, however, attach it to an Activity with setOwnerActivity(Activity). When you want to show a dialo g, call showDialog(int) and pass it an integer that uniquely identifies the dial og that you want to display. When a dialog is requested for the first time, Andr oid calls onCreateDialog(int) from your Activity, which is where you should inst antiate the Dialog. This callback method is passed the same ID that you passed t o showDialog(int). After you create the Dialog, return the object at the end of the method. Before the dialog is displayed, Android also calls the optional call back method onPrepareDialog(int, Dialog). Define this method if you want to chan ge any properties of the dialog each time it is opened. This method is called ev ery time a dialog is opened, whereas onCreateDialog(int) is only called the very first time a dialog is opened. If you don't define onPrepareDialog(), then the dialog will remain the same as it was the previous time it was opened. This meth od is also passed the dialog's ID, along with the Dialog object you created in o nCreateDialog(). http://developer.android.com/guide/topics/ui/dialogs.html Page 1 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 The best way to define the onCreateDialog(int) and onPrepareDialog(int, Dialog) callback methods is with a switch statement that checks the id parameter that's passed into the method. Each case should check for a unique dialog ID and then c reate and define the respective Dialog. For example, imagine a game that uses tw o different dialogs: one to indicate that the game has paused and another to ind icate that the game is over. First, define an integer ID for each dialog: static final int DIALOG_PAUSED_ID = 0; static final int DIALOG_GAMEOVER_ID = 1; Then, define the onCreateDialog(int) callback with a switch case for each ID: protecte d Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_PAUSED _ID: // do the work to define the pause Dialog break; case DIALOG_GAMEOVER_ID: / / do the work to define the game over Dialog break; default: dialog = null; } re turn dialog; } Note: In this example, there's no code inside the case statements because the procedure for defining your Dialog is outside the scope of this sec tion. See the section below about Creating an AlertDialog, offers code suitable for this example. When it's time to show one of the dialogs, call showDialog(int ) with the ID of a dialog: showDialog(DIALOG_PAUSED_ID); Dismissing a Dialog When you're ready to close your dialog, you can dismiss it by calling dismiss() on the Dialog object. If necessary, you can also call dismissDialog(int) from th e Activity, which effectively calls dismiss() on the Dialog for you. If you are using onCreateDialog(int) to manage the state of your dialogs (as discussed in t he previous section), then every time your dialog is dismissed, the state of the Dialog object is retained by the Activity. If you decide that you will no longe r need this object or it's important that the state is cleared, then you should call removeDialog(int). This will remove any internal references to the object a nd if the dialog is showing, it will dismiss it. Using dismiss listeners If you'd like your applcation to perform some procedures the moment that a dialo g is dismissed, then you should attach an on-dismiss listener to your Dialog. Fi rst define the DialogInterface.OnDismissListener interface. This interface has j ust one method, onDismiss(DialogInterface), which will be called when the dialog is dismissed. Then simply pass your OnDismissListener implementation to setOnDi smissListener(). However, note that dialogs can also be "cancelled." This is a s pecial case that indicates the dialog was explicitly cancelled by the user. This will occur if the user presses the "back" button to close the dialog, or if the dialog explicitly calls cancel() (perhaps from a "Cancel" button in the dialog) . When a dialog is cancelled, the OnDismissListener will still be notified, but if you'd like to be informed that the dialog was explicitly cancelled (and not d ismissed normally), http://developer.android.com/guide/topics/ui/dialogs.html Page 2 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 still be notified, but if you'd like to be informed that the dialog was explicit ly cancelled (and not dismissed normally), then you should register an DialogInt erface.OnCancelListener with setOnCancelListener(). Creating an AlertDialog An AlertDialog is an extension of the Dialog class. It is capable of constructin g most dialog user interfaces and is the suggested dialog type. You should use i t for dialogs that use any of the following features: A title A text message One , two, or three buttons A list of selectable items (with optional checkboxes or radio buttons) To create an AlertDialog, use the AlertDialog.Builder subclass. G et a Builder with AlertDialog.Builder(Context) and then use the class's public m ethods to define all of the AlertDialog properties. After you're done with the B uilder, retrieve the AlertDialog object with create(). The following topics show how to define various properties of the AlertDialog using the AlertDialog.Build er class. If you use any of the following sample code inside your onCreateDialog () callback method, you can return the resulting Dialog object to display the di alog. Adding buttons To create an AlertDialog with side-by-side buttons like the one shown in the scr eenshot to the right, use the set...Button() methods: AlertDialog.Builder builde r = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnCl ickListener() { public void onClick(DialogInterface dialog, int id) { MyActivity .this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListene r() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } } ); AlertDialog alert = builder.create(); First, add a message for the dialog wit h setMessage(CharSequence). Then, begin method-chaining and set the dialog to be not cancelable (so the user cannot close the dialog with the back button) with setCancelable(boolean). For each button, use one of the set...Button() methods, such as setPositiveButton(), that accepts the name for the button and a DialogIn terface.OnClickListener that defines the action to take when the user selects th e button. Note: You can only add one of each button type to the AlertDialog. Tha t is, you cannot have more than one "positive" button. This limits the number of possible buttons to three: positive, neutral, and negative. These names are tec hnically irrelevant to the actual functionality of your buttons, but should help you keep track of which one does what. Adding a list To create an AlertDialog with a list of selectable items like the one shown to t he right, use the setItems() method: http://developer.android.com/guide/topics/ui/dialogs.html Page 3 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 right, use the setItems() method: final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.se tTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListe ner() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(g etApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDial og alert = builder.create(); First, add a title to the dialog with setTitle(Char Sequence). Then, add a list of selectable items with setItems(), which accepts t he array of items to display and a DialogInterface.OnClickListener that defines the action to take when the user selects an item. Adding checkboxes and radio buttons To create a list of multiple-choice items (checkboxes) or single-choice items (r adio buttons) inside the dialog, use the setMultiChoiceItems() and setSingleChoi ceItems() methods, respectively. If you create one of these selectable lists in the onCreateDialog() callback method, Android manages the state of the list for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is los t. Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout the Activity Lifecycle. To permanently save the selections, even when the Activity process is completely s hutdown, you need to save the settings with one of the Data Storage techniques. To create an AlertDialog with a list of single-choice items like the one shown t o the right, use the same code from the previous example, but replace the setIte ms() method with setSingleChoiceItems(): final CharSequence[] items = {"Red", "G reen", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); bui lder.setTitle("Pick a color"); builder.setSingleChoiceItems(items, -1, new Dialo gInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i tem) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT). show(); } }); AlertDialog alert = builder.create(); The second parameter in the setSingleChoiceItems() method is an integer value for the checkedItem, which ind icates the zero-based list position of the default selected item. Use "-1" to in dicate that no item should be selected by default. Creating a ProgressDialog A ProgressDialog is an extension of the AlertDialog class that can display a pro gress animation in the form of a spinning wheel, for a task with progress that's undefined, or a progress bar, for a task that has a defined progression. The di alog http://developer.android.com/guide/topics/ui/dialogs.html Page 4 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 undefined, or a progress bar, for a task that has a defined progression. The dia log can also provide buttons, such as one to cancel a download. Opening a progre ss dialog can be as simple as calling ProgressDialog.show(). For example, the pr ogress dialog shown to the right can be easily achieved without managing the dia log through the onCreateDialog(int) callback, as shown here: ProgressDialog dial og = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true); The first parameter is the application Context, the second is a title for the di alog (left empty), the third is the message, and the last parameter is whether t he progress is indeterminate (this is only relevant when creating a progress bar , which is discussed in the next section). The default style of a progress dialo g is the spinning wheel. If you want to create a progress bar that shows the loa ding progress with granularity, some more code is required, as discussed in the next section. Showing a progress bar To show the progression with an animated progress bar: 1. Initialize the Progres sDialog with the class constructor, ProgressDialog(Context). 2. Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other proper ties, such as the message. 3. When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback. 4. You can i ncrement the amount of progress displayed in the bar by calling either setProgre ss(int) with a value for the total percentage completed so far or incrementProgr essBy(int) with an incremental value to add to the total percentage completed so far. For example, your setup might look like this: ProgressDialog progressDialo g; progressDialog = new ProgressDialog(mContext); progressDialog.setProgressStyl e(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading..."); pro gressDialog.setCancelable(false); The setup is simple. Most of the code needed t o create a progress dialog is actually involved in the process that updates it. You might find that it's necessary to create a second thread in your application for this work and then report the progress back to the Activity's UI thread wit h a Handler object. If you're not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread to increment a progress dialog managed by the Activity. Example ProgressDialog with a second t hread Creating a Custom Dialog If you want a customized design for a dialog, you can create your own layout for the dialog window with layout and widget elements. After you've defined your la yout, pass the root View object or layout resource ID to setContentView(View). F or example, to create the dialog shown to the right: http://developer.android.com/guide/topics/ui/dialogs.html Page 5 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 1. Create an XML layout saved as custom_dialog.xml: <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:id="@+id/layout_root" andro id:orientation="horizontal" android:layout_width="fill_parent" android:layout_he ight="fill_parent" android:padding="10dp" > <ImageView android:id="@+id/image" a ndroid:layout_width="wrap_content" android:layout_height="fill_parent" android:l ayout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_widt h="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /> </LinearLayout> This XML defines an ImageView and a TextView inside a LinearLay out. 2. Set the above layout as the dialog's content view and define the content for the ImageView and TextView elements: Context mContext = getApplicationConte xt(); Dialog dialog = new Dialog(mContext); dialog.setContentView(R.layout.custo m_dialog); dialog.setTitle("Custom Dialog"); TextView text = (TextView) dialog.f indViewById(R.id.text); text.setText("Hello, this is a custom dialog!"); ImageVi ew image = (ImageView) dialog.findViewById(R.id.image); image.setImageResource(R .drawable.android); After you instantiate the Dialog, set your custom layout as the dialog's content view with setContentView(int), passing it the layout resour ce ID. Now that the Dialog has a defined layout, you can capture View objects fr om the layout with findViewById(int) and modify their content. 3. That's it. You can now show the dialog as described in Showing A Dialog. A dialog made with th e base Dialog class must have a title. If you don't call setTitle(), then the sp ace used for the title remains empty, but still visible. If you don't want a tit le at all, then you should create your custom dialog using the AlertDialog class . However, because an AlertDialog is created easiest with the AlertDialog.Builde r class, you do not have access to the setContentView(int) method used above. In stead, you must use setView(View). This method accepts a View object, so you nee d to inflate the layout's root View object from XML. To inflate the XML layout, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), an d then call inflate(int, ViewGroup), where the first parameter is the layout res ource ID and the second is the ID of the root View. At this point, you can use t he inflated layout to find View objects in the layout and define the content for the ImageView and TextView elements. Then instantiate the AlertDialog.Builder a nd set the inflated layout for the dialog with setView(View). Here's an example, creating a custom layout in an AlertDialog: AlertDialog.Builder builder; AlertD ialog alertDialog; Context mContext = getApplicationContext(); LayoutInflater in flater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER); View layou t = inflater.inflate(R.layout.custom_dialog, http://developer.android.com/guide/topics/ui/dialogs.html Page 6 of 7

Creating Dialogs | Android Developers 29.04.09 0:37 View layout = inflater.inflate(R.layout.custom_dialog, (ViewGroup) findViewById( R.id.layout_root)); TextView text = (TextView) layout.findViewById(R.id.text); t ext.setText("Hello, this is a custom dialog!"); ImageView image = (ImageView) la yout.findViewById(R.id.image); image.setImageResource(R.drawable.android); build er = new AlertDialog.Builder(mContext); builder.setView(layout); alertDialog = b uilder.create(); Using an AlertDialog for your custom layout lets you take advan tage of built-in AlertDialog features like managed buttons, selectable lists, a title, an icon and so on. For more information, refer to the reference documenta tion for the Dialog and AlertDialog.Builder classes. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/dialogs.html Page 7 of 7

Handling UI Events | Android Developers 29.04.09 0:37 User Interface > Handling UI Events On Android, there's more than one way to intercept the events from a user's inte raction with your application. When considering events within your user interfac e, the approach is to capture the events from the specific View object that the user interacts with. The View class provides the means to do so. Within the vari ous View classes that you'll use to compose your layout, you may notice several public callback methods that look useful for UI events. These methods are called by the Android framework when the respective action occurs on that object. For instance, when a View (such as a Button) is touched, the onTouchEvent() method i s called on that object. However, in order to intercept this, you must extend th e class and override the method. Obviously, extending every View object you want to use (just to handle an event) would be obsurd. This is why the View class al so contains a collection of nested interfaces with callbacks that you can much m ore easily define. These interfaces, called event listeners, are your ticket to capturing the user interaction with your UI. While you will more commonly use th e event listeners to listen for user interaction, there may come a time when you do want to extend a View class, in order to build a custom component. Perhaps y ou want to extend the Button class to make something more fancy. In this case, y ou'll be able to define the default event behaviors for your class using the cla ss event handlers. Event Listeners An event listener is an interface in the View class that contains a single callb ack method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI. Included in the event listener interfaces are the following callback methods: onClick() From View.OnClickListener. This is called when the u ser either touches the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses the suitable "enter" key or presses down on the trackball. onLongClick() From View.OnLongClickListener. This is cal led when the user either touches and holds the item (when in touch mode), or foc uses upon the item with the navigation-keys or trackball and presses and holds t he suitable "enter" key or presses and holds down on the trackball (for one seco nd). onFocusChange() From View.OnFocusChangeListener. This is called when the us er navigates onto or away from the item, using the navigation-keys or trackball. onKey() From View.OnKeyListener. This is called when the user is focused on the item and presses or releases a key on the device. onTouch() From View.OnTouchLi stener. This is called when the user performs an action qualified as a touch eve nt, including a press, a release, or any movement gesture on the screen (within the bounds of the item). onCreateContextMenu() http://developer.android.com/guide/topics/ui/ui-events.html Page 1 of 4

Handling UI Events | Android Developers 29.04.09 0:37 From View.OnCreateContextMenuListener. This is called when a Context Menu is bei ng built (as the result of a sustained "long click"). See the discussion on cont ext menus in Creating Menus for more information. These methods are the sole inh abitants of their respective interface. To define one of these methods and handl e your events, implement the nested interface in your Activity or define it as a n anonymous class. Then, pass an instance of your implementation to the respecti ve View.set...Listener() method. (E.g., call setOnClickListener() and pass it yo ur implementation of the OnClickListener.) The example below shows how to regist er an on-click listener for a Button. // Create an anonymous implementation of O nClickListener private OnClickListener mCorkyListener = new OnClickListener() { public void onClick(View v) { // do something when the button is clicked } }; pr otected void onCreate(Bundle savedValues) { ... // Capture our button from layou t Button button = (Button)findViewById(R.id.corky); // Register the onClick list ener with the implementation above button.setOnClickListener(mCorkyListener); .. . } You may also find it more conventient to implement OnClickListener as a part of your Activity. This will avoid the extra class load and object allocation. F or example: public class ExampleActivity extends Activity implements OnClickList ener { protected void onCreate(Bundle savedValues) { ... Button button = (Button )findViewById(R.id.corky); button.setOnClickListener(this); } // Implement the O nClickListener callback public void onClick(View v) { // do something when the b utton is clicked } ... } Notice that the onClick() callback in the above example has no return value, but some other event listener methods must return a boolea n. The reason depends on the event. For the few that do, here's why: onLongClick () - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, return true to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-click listeners. onKey() This returns a boolean to indicate whether you have consumed the event and it sh ould not be carried further. That is, return true to indicate that you have hand led the event and it should stop here; return false if you have not handled it a nd/or the event should continue to any other on-key listeners. onTouch() - This returns a boolean to indicate whether your listener consumes this event. The imp ortant thing is that this event can have multiple actions that follow each other . So, if you return false when the down action event is received, you indicate t hat you have not consumed the event and are also not interested in subsequent ac tions from this event. Thus, you will not be called for any other actions within the event, such as a fingure gesture, or the eventual up action event. Remember that key events are always delivered to the View currently in focus. They are d ispatched starting from the top of the View hierarchy, and then down, until they reach the appropriate destination. If your View (or a child of your View) curre ntly has focus, then you can see the event travel through the dispatchKeyEvent() method. As an http://developer.android.com/guide/topics/ui/ui-events.html Page 2 of 4

Handling UI Events | Android Developers 29.04.09 0:37 View) currently has focus, then you can see the event travel through the dispatc hKeyEvent() method. As an alternative to capturing key events through your View, you can also receive all of the events inside your Activity with onKeyDown() an d onKeyUp(). Note: Android will call event handlers first and then the appropria te default handlers from the class definition second. As such, returning true fr om these event listeners will stop the propagation of the event to other event l isteners and will also block the callback to the default event handler in the Vi ew. So be certain that you want to terminate the event when you return true. Event Handlers If you're building a custom component from View, then you'll be able to define s everal callback methods used as default event handlers. In the document on Build ing Custom Components, you'll learn see some of the common callbacks used for ev ent handling, including: onKeyDown(int, KeyEvent) - Called when a new key event occurs. onKeyUp(int, KeyEvent) - Called when a key up event occurs. onTrackballE vent(MotionEvent) - Called when a trackball motion event occurs. onTouchEvent(Mo tionEvent) - Called when a touch screen motion event occurs. onFocusChanged(bool ean, int, Rect) - Called when the view gains or loses focus. There are some othe r methods that you should be awere of, which are not part of the View class, but can directly impact the way you're able to handle events. So, when managing mor e complex events inside a layout, consider these other methods: Activity.dispatc hTouchEvent(MotionEvent) - This allows your Activity to intercept all touch even ts before they are dispatched to the window. ViewGroup.onInterceptTouchEvent(Mot ionEvent) - This allows a ViewGroup to watch events as they are dispatched to ch ild Views. ViewParent.requestDisallowInterceptTouchEvent(boolean) - Call this up on a parent View to indicate that it should not intercept touch events with onIn terceptTouchEvent(MotionEvent). Touch Mode When a user is navigating a user interface with directional keys or a trackball, it is necessary to give focus to actionable items (like buttons) so the user ca n see what will accept input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, then it is no lo nger necessary to highlight items, or give focus to a particular View. Thus, the re is a mode for interaction named "touch mode." For a touch-capable device, onc e the user touches the screen, the device will enter touch mode. From this point onward, only Views for which isFocusableInTouchMode() is true will be focusable , such as text editing widgets. Other Views that are touchable, like buttons, wi ll not take focus when touched; they will simply fire their on-click listeners w hen pressed. Any time a user hits a directional key or scrolls with a trackball, the device will exit touch mode, and find a view to take focus. Now, the user m ay resume interacting with the user interface without touching the screen. The t ouch mode state is maintained throughout the entire system (all windows and acti vities). To query the current state, you can call isInTouchMode() to see whether the device is currently in touch mode. http://developer.android.com/guide/topics/ui/ui-events.html Page 3 of 4

Handling UI Events | Android Developers 29.04.09 0:37 Handling Focus The framework will handle routine focus movement in response to user input. This includes changing the focus as Views are removed or hidden, or as new Views bec ome available. Views indicate their willingness to take focus through the isFocu sable() method. To change whether a View can take focus, call setFocusable(). Wh en in touch mode, you may query whether a View allows focus with isFocusableInTo uchMode(). You can change this with setFocusableInTouchMode(). Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the de veloper. In these situations, you can provide explicit overrides with the follow ing XML attributes in the layout file: nextFocusDown, nextFocusLeft, nextFocusRi ght, and nextFocusUp. Add one of these attributes to the View from which the foc us is leaving. Define the value of the attribute to be the id of the View to whi ch focus should be given. For example: <LinearLayout android:orientation="vertic al" ... > <Button android:id="@+id/top" android:nextFocusUp="@+id/bottom" ... /> <Button android:id="@+id/bottom" android:nextFocusDown="@+id/top" ... /> </Line arLayout> Ordinarily, in this vertical layout, navigating up from the first Butt on would not go anywhere, nor would navigating down from the second Button. Now that the top Button has defined the bottom one as the nextFocusUp (and vice vers a), the navigation focus will cycle from top-to-bottom and bottom-to-top. If you 'd like to declare a View as focusable in your UI (when it is traditionally not) , add the android:focusable XML attribute to the View, in your layout declaratio n. Set the value true. You can also declare a View as focusable while in Touch M ode with android:focusableInTouchMode. To request a particular View to take focu s, call requestFocus(). To listen for focus events (be notified when a View rece ives or looses focus), use onFocusChange(), as discussed in the Event Listeners section, above. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/ui-events.html Page 4 of 4

Notifying the User | Android Developers 29.04.09 0:37 Notifying the User Several types of situations may arise that require you to notify the user about an event that occurs in your application. Some events require the user to respon d and others do not. For example: When an event such as saving a file is complet e, a small message should appear to confirm that the save was successful. If the application is running in the background and needs the user's attention, the ap plication should create a notificaiton that allows the user to respond at his or her convenience. If the application is performing work that the user must wait for (such as loading a file), the application should show a hovering progress wh eel or bar. Each of these notification tasks can be achieved using a different t echnique: A Toast Notification, for brief messages that come from the background . A Status Bar Notification, for persistent reminders that come from the backgro und and request the user's response. A Dialog Notification, for Activity-related notifications. This document summarizes each of these techniques for notifying the user and includes links to full documentation. Toast Notification A toast notificaiton is a message that pops up on the surface of the window. It only fills the amount of space required for the message and the user's current a ctivity remains visible and interactive. The notification automatically fades in and out, and does not accept interaction events. Because a toast can be created from a background Service, it appears even if the application isn't visible. A toast is best for short text messages, such as "File saved," when you're fairly certain the user is paying attention to the screen. A toast can not accept user interaction events; if you'd like the user to respond and take action, consider using a Status Bar Notification instead. For more information, refer to Creating Toast Notifications. Status Bar Notification A status bar notification adds an icon to the system's status bar (with an optio nal ticker-text message) and an expanded message in the "Notifications" window. When the user selects the expanded message, Android fires an Intent that is defi ned by the notification (usually to launch an Activity). You can also configure the notification to alert the user with a sound, a vibration, and flashing light s on the device. http://developer.android.com/guide/topics/ui/notifiers/index.html Page 1 of 2

Notifying the User | Android Developers 29.04.09 0:37 This kind of notification is ideal when your application is working in a backgro und Service and needs to notify the user about an event. If you need to alert th e user about an event that occurs while your Activity is still in focus, conside r using a Dialog Notification instead. For more information, refer to Creating S tatus Bar Notifications. Dialog Notification A dialog is usually a small window that appears in front of the current Activity . The underlying Activity loses focus and the dialog accepts all user interactio n. Dialogs are normally used for notifications and short activities that directl y relate to the application in progress. You should use a dialog when you need t o show a progress bar or a short message that requires confirmation from the use r (such as an alert with "OK" and "Cancel" buttons). You can use also use dialog s as integral componenents in your application's UI and for other purposes besid es notifications. For a complete discussion on all the available types of dialog s, including its uses for notifications, refer to Creating Dialogs. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/notifiers/index.html Page 2 of 2

Applying Styles and Themes | Android Developers 29.04.09 0:37 User Interface > Applying Styles and Themes When designing your application, you can use styles and themes to apply uniform formatting to its various screens and UI elements. A style is a set of one or mo re formatting attributes that you can apply as a unit to single elements in your layout XML file(s). For example, you could define a style that specifies a cert ain text size and color, then apply it to instances of a certain type of View el ement. A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in an application or just a single activity. For exa mple, you could define a theme that sets specific colors for the window frame an d the panel foreground and background, and sets text sizes and colors for menus, then apply it to the activities of your application. Styles and themes are reso urces. Android provides some default style and theme resources that you can use, or you can declare your own custom style and theme resources. To create custom styles and themes: 1. Create a file named styles.xml in the your application's r es/values directory. Add a root <resources> node. 2. For each style or theme, ad d a <style> element with a unique name and, optionally, a parent attribute. The name is used for referencing these styles later, and the parent indicates what s tyle resource to inherit from. 3. Inside the <style> element, declare format val ues in one or more <item> element(s). Each <item> identifies its style property with a name attribute and defines its style value inside the element. 4. You can then reference the custom resources from other XML resources, your manifest or application code. Styles Here's an example declaration of a style: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="SpecialText" parent="@style/Text"> <item name="android :textSize">18sp</item> <item name="android:textColor">#008</item> </style> </res ources> As shown, you can use <item> elements to set specific formatting values for the style. The name attribute in the item can refer to a standard string, a hex color value, or a reference to any other resource type. Notice the parent at tribute in the <style> element. This attribute lets you specify a resource from which the current style will inherit values. The style can inherit from any type of resource that contains the style(s) you want. In general, your styles should always inherit (directly or indirectly) from a standard Android style resource. This way, you only have to define the values that you want to change. Here's ho w you would reference the custom style from an XML layout, in this case, for an EditText element: http://developer.android.com/guide/topics/ui/themes.html Page 1 of 3

Applying Styles and Themes | Android Developers 29.04.09 0:37 <EditText id="@+id/text1" style="@style/SpecialText" android:layout_width="fill_ parent" android:layout_height="wrap_content" android:text="Hello, World!" /> Now this EditText widget will be styled as defined by the XML example above. Themes Just like styles, themes are also declared in XML <style> elements, and are refe renced in the same manner. The difference is that you add a theme to an entire a pplication or activity, via the <application> and <activity> elements in the And roid Manifest themes cannot be applied to individual Views. Here's an example de claration of a theme: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CustomTheme"> <item name="android:windowNoTitle">true</item> <item name="w indowFrame">@drawable/screen_frame</item> <item name="windowBackground">@drawabl e/screen_background_white</item> <item name="panelForegroundColor">#FF000000</it em> <item name="panelBackgroundColor">#FFFFFFFF</item> <item name="panelTextColo r">?panelForegroundColor</item> <item name="panelTextSize">14</item> <item name= "menuItemTextColor">?panelTextColor</item> <item name="menuItemTextSize">?panelT extSize</item> </style> </resources> Notice the use of the at-symbol (@) and the question-mark (?) to reference resources. The at-symbol indicates that we're re ferencing a resource previously defined elsewhere (which may be from this projec t or from the Android framework). The question-mark indicates that we're referen cing a resource value in the currently loaded theme. This is done by referring t o a specific <item> by its name value. (E.g., panelTextColor uses the same color assigned to panelForegroundColor, defined beforehand.) This technique can be us ed only in XML resources. Set the theme in the manifest To set this theme for all the activites of your application, open the AndroidMan ifest.xml file and edit the <application> tag to include the android:theme attri bute with the theme name: <application android:theme="@style/CustomTheme"> If yo u want the theme applied to just one Activity in your application, then add the theme attribute to the <activity> tag, instead. Just as Android provides other b uilt-in resources, there are several themes that you swap in without having to w rite one yourself. For example, you can use the Dialog theme to make your Activi ty appear like a dialog box. In the manifest, reference an Android theme like so : <activity android:theme="@android:style/Theme.Dialog"> If you like a theme, bu t want to slightly tweak it, just add the theme as the parent of your custom the me. For example, we'll modify the Theme.Dialog theme. To do so, create a style w ith Theme.Dialog as the parent: http://developer.android.com/guide/topics/ui/themes.html Page 2 of 3

Applying Styles and Themes | Android Developers 29.04.09 0:37 <style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> There it i s. We've inherited the Android Dialog theme so we can adjust its styles as we li ke. So, for each item in the Dialog theme that we want to change, we re-define t he value here and use CustomDialogTheme instead of Theme.Dialog inside the Andro id Manifest. Set the theme from the application You can also load a theme for an Activity programmatically, if needed. To do so, use the setTheme() method. Note that, when doing so, you must be sure to set th e theme before instantiating any Views in the context, for example, before calli ng setContentView(View) or inflate(int, ViewGroup). This ensures that the system applies the same theme for all of your UI screens. Here's an example: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... setTheme(android.R.style.Theme_Light); setContentView(R.layout.linear_layout _3); } If you are considering loading a theme programmatically for the main scre en of your application, note that the theme would not be applied in any animatio ns the system would use to start the activity, which would take place before you r application opens. In most cases, if you want to apply a theme to your main sc reen, doing so in XML is a better approach. For detailed information about custo m styles and themes and referencing them from your application, see Available Re source Types: Style and Themes. For information about default themes and styles available, see R.style. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/themes.html Page 3 of 3

Building Custom Components | Android Developers 29.04.09 0:37 User Interface > Building Custom Components Android offers a sophisticated and powerful componentized model for building you r UI, based on the fundamental layout classes: View and ViewGroup. To start with , the platform includes a variety of prebuilt View and ViewGroup subclasses call ed widgets and layouts, respectively that you can use to construct your UI. A pa rtial list of available widgets includes Button, TextView, EditText, ListView, C heckBox, RadioButton, Gallery, Spinner, and the more special-purpose AutoComplet eTextView, ImageSwitcher, and TextSwitcher. Among the layouts available are Line arLayout, FrameLayout, AbsoluteLayout, and others. For more examples, see Common Layout Objects. If none of the prebuilt widgets or layouts meets your needs, yo u can create your own View subclass. If you only need to make small adjustments to an existing widget or layout, you can simply subclass the widget or layout an d override its methods. Creating your own View subclasses gives you precise cont rol over the appearance and function of a screen element. To give an idea of the control you get with custom views, here are some examples of what you could do with them: You could create a completely custom-rendered View type, for example a "volume control" knob rendered using 2D graphics, and which resembles an analo g electronic control. You could combine a group of View components into a new si ngle component, perhaps to make something like a ComboBox (a combination of popu p list and free entry text field), a dual-pane selector control (a left and righ t pane with a list in each where you can re-assign which item is in which list), and so on. You could override the way that an EditText component is rendered on the screen (the Notepad Tutorial uses this to good effect, to create a lined-no tepad page). You could capture other events like key presses and handle them in some custom way (such as for a game). The sections below explain how to create c ustom Views and use them in your application. For detailed reference information , see the View class. The Basic Approach Here is a high level overview of what you need to know to get started in creatin g your own View components: 1. Extend an existing View class or subclass with yo ur own class. 2. Override some of the methods from the superclass. The superclas s methods to override start with 'on', for example, onDraw(), onMeasure(), and o nKeyDown(). This is similar to the on... events in Activity or ListActivity that you override for lifecycle and other functionality hooks. 3. Use your new exten sion class. Once completed, your new extension class can be used in place of the view upon which it was based. Tip: Extension classes can be defined as inner cl asses inside the activities that use them. This is useful because it controls ac cess to them but isn't necessary (perhaps you want to create a new public View f or wider use in your application). http://developer.android.com/guide/topics/ui/custom-components.html Page 1 of 6

Building Custom Components | Android Developers 29.04.09 0:37 Fully Customized Components Fully customized components can be used to create graphical components that appe ar however you wish. Perhaps a graphical VU meter that looks like an old analog gauge, or a sing-a-long text view where a bouncing ball moves along the words so you can sing along with a karaoke machine. Either way, you want something that the built-in components just won't do, no matter how you combine them. Fortunate ly, you can easily create components that look and behave in any way you like, l imited perhaps only by your imagination, the size of the screen, and the availab le processing power (remember that ultimately your application might have to run on something with significantly less power than your desktop workstation). To c reate a fully customized component: 1. The most generic view you can extend is, unsurprisingly, View, so you will usually start by extending this to create your new super component. 2. You can supply a constructor which can take attributes and parameters from the XML, and you can also consume your own such attributes a nd parameters (perhaps the color and range of the VU meter, or the width and dam ping of the needle, etc.) 3. You will probably want to create your own event lis teners, property accessors and modifiers, and possibly more sophisticated behavi or in your component class as well. 4. You will almost certainly want to overrid e onMeasure() and are also likely to need to override onDraw() if you want the c omponent to show something. While both have default behavior, the default onDraw () will do nothing, and the default onMeasure() will always set a size of 100x10 0 which is probably not what you want. 5. Other on... methods may also be overri dden as required. Extend onDraw() and onMeasure() The onDraw() method delivers you a Canvas upon which you can implement anything you want: 2D graphics, other standard or custom components, styled text, or anyt hing else you can think of. Note: This does not apply to 3D graphics. If you wan t to use 3D graphics, you must extend SurfaceView instead of View, and draw from a seperate thread. See the GLSurfaceViewActivity sample for details. onMeasure( ) is a little more involved. onMeasure() is a critical piece of the rendering co ntract between your component and its container. onMeasure() should be overridde n to efficiently and accurately report the measurements of its contained parts. This is made slightly more complex by the requirements of limits from the parent (which are passed in to the onMeasure() method) and by the requirement to call the setMeasuredDimension() method with the measured width and height once they h ave been calculated. If you fail to call this method from an overridden onMeasur e() method, the result will be an exception at measurement time. At a high level , implementing onMeasure() looks something like this: 1. The overridden onMeasur e() method is called with width and height measure specifications (widthMeasureS pec and heightMeasureSpec parameters, both are integer codes representing dimens ions) which should be treated as requirements for the restrictions on the width and height measurements you should produce. A full reference to the kind of rest rictions these specifications can require can be found in the reference document ation under View.onMeasure(int, int) (this reference documentation does a pretty good job of explaining the whole measurement operation as well). 2. Your compon ent's onMeasure() method should calculate a measurement width and height which w ill be required to render the component. It should try to stay within the specif ications passed in, although it can choose to exceed them (in this case, the par ent can choose what to do, including clipping, scrolling, throwing an exception, or asking the onMeasure() to try again, perhaps with different measurement spec ifications). 3. Once the width and height are calculated, the setMeasuredDimensi on(int width, int height) method must be called with the calculated measurements . Failure to do this will result in an exception being thrown. http://developer.android.com/guide/topics/ui/custom-components.html

Page 2 of 6

Building Custom Components | Android Developers 29.04.09 0:37 Here's a summary of some of the other standard methods that the framework calls on views: Category Creation Methods Constructors Description There is a form of the constructor that are called when the view is created from code and a form th at is called when the view is inflated from a layout file. The second form shoul d parse and apply any attributes defined in the layout file. Called after a view and all of its children has been inflated from XML. Called to determine the siz e requirements for this view and all of its children. Called when this view shou ld assign a size and position to all of its children. Called when the size of th is view has changed. Called when the view should render its content. Called when a new key event occurs. Called when a key up event occurs. Called when a trackb all motion event occurs. Called when a touch screen motion event occurs. Called when the view gains or loses focus. Called when the window containing the view g ains or loses focus. Called when the view is attached to a window. Called when t he view is detached from its window. Called when the visibility of the window co ntaining the view has changed. onFinishInflate() Layout onMeasure(int, int) onLayout(boolean, int, int, int, int) onSizeChanged(int, int, int, int) Drawing Event processing onDraw(Canvas) onKeyDown(int, KeyEvent) onKeyUp(int, KeyEvent) onTrackballEvent(MotionEvent) onTouchEvent(MotionEvent) Focus onFocusChanged(boo lean, int, Rect) onWindowFocusChanged(boolean) Attaching onAttachedToWindow() on DetachedFromWindow() onWindowVisibilityChanged(int) A Custom View Example The CustomView sample in the API Demos provides an example of a customized View. The custom View is defined in the LabelView class. http://developer.android.com/guide/topics/ui/custom-components.html Page 3 of 6

Building Custom Components | Android Developers 29.04.09 0:37 The LabelView sample demonstrates a number of different aspects of custom compon ents: Extending the View class for a completely custom component. Parameterized constructor that takes the view inflation parameters (parameters defined in the XML). Some of these are passed through to the View superclass, but more importan tly, there are some custom attributes defined and used for LabelView. Standard p ublic methods of the type you would expect to see for a label component, for exa mple setText(), setTextSize(), setTextColor() and so on. An overridden onMeasure method to determine and set the rendering size of the component. (Note that in LabelView, the real work is done by a private measureWidth() method.) An overrid den onDraw() method to draw the label onto the provided canvas. You can see some sample usages of the LabelView custom View in custom_view_1.xml from the sample s. In particular, you can see a mix of both android: namespace parameters and cu stom app: namespace parameters. These app: parameters are the custom ones that t he LabelView recognizes and works with, and are defined in a styleable inner cla ss inside of the samples R resources definition class. Compound Controls If you don't want to create a completely customized component, but instead are l ooking to put together a reusable component that consists of a group of existing controls, then creating a Compound Component (or Compound Control) might fit th e bill. In a nutshell, this brings together a number of more atomic controls (or views) into a logical group of items that can be treated as a single thing. For example, a Combo Box can be thought of as a combination of a single line EditTe xt field and an adjacent button with an attached PopupList. If you press the but ton and select something from the list, it populates the EditText field, but the user can also type something directly into the EditText if they prefer. In Andr oid, there are actually two other Views readily available to do this: Spinner an d AutoCompleteTextView, but regardless, the concept of a Combo Box makes an easy -to-understand example. To create a compound component: 1. The usual starting po int is a Layout of some kind, so create a class that extends a Layout. Perhaps i n the case of a Combo box we might use a LinearLayout with horizontal orientatio n. Remember that other layouts can be nested inside, so the compound component c an be arbitrarily complex and structured. Note that just like with an Activity, you can use either the declarative (XML-based) approach to creating the containe d components, or you can nest them programmatically from your code. 2. In the co nstructor for the new class, take whatever parameters the superclass expects, an d pass them through to the superclass constructor first. Then you can set up the other views to use within your new component; this is where you would create th e EditText field and the PopupList. Note that you also might introduce your own attributes and parameters into the XML that can be pulled out and used by your c onstructor. 3. You can also create listeners for events that your contained view s might generate, for example, a listener method for the List Item Click Listene r to update the contents of the EditText if a list selection is made. 4. You mig ht also create your own properties with accessors and modifiers, for example, al low the EditText value to be set initially in the component and query for its co ntents when needed. 5. In the case of extending a Layout, you don't need to over ride the onDraw() and onMeasure() methods since the layout will have default beh avior that will likely work just fine. However, you can still override them if y ou need to. 6. You might override other on... methods, like onKeyDown(), to perh aps choose certain default values from the popup list of a combo box when a cert ain key is pressed. To summarize, the use of a Layout as the basis for a Custom Control has a number of advantages, including: http://developer.android.com/guide/topics/ui/custom-components.html Page 4 of 6

Building Custom Components | Android Developers 29.04.09 0:37 You can specify the layout using the declarative XML files just like with an act ivity screen, or you can create views programmatically and nest them into the la yout from your code. The onDraw() and onMeasure() methods (plus most of the othe r on... methods) will likely have suitable behavior so you don't have to overrid e them. In the end, you can very quickly construct arbitrarily complex compound views and re-use them as if they were a single component. Examples of Compound Controls In the API Demos project that comes with the SDK, there are two List examples Ex ample 4 and Example 6 under Views/Lists demonstrate a SpeechView which extends L inearLayout to make a component for displaying Speech quotes. The corresponding classes in the sample code are List4.java and List6.java. Modifying an Existing View Type There is an even easier option for creating a custom View which is useful in cer tain circumstances. If there is a component that is already very similar to what you want, you can simply extend that component and just override the behavior t hat you want to change. You can do all of the things you would do with a fully c ustomized component, but by starting with a more specialized class in the View h eirarchy, you can also get a lot of behavior for free that probably does exactly what you want. For example, the SDK includes a NotePad application in the sampl es. This demonstrates many aspects of using the Android platform, among them is extending an EditText View to make a lined notepad. This is not a perfect exampl e, and the APIs for doing this might change from this early preview, but it does demonstrate the principles. If you haven't done so already, import the NotePad sample into Eclipse (or just look at the source using the link provided). In par ticular look at the definition of MyEditText in the NoteEditor.java file. Some p oints to note here 1. The Definition The class is defined with the following lin e: public static class MyEditText extends EditText It is defined as an inner cla ss within the NoteEditor activity, but it is public so that it could be accessed as NoteEditor.MyEditText from outside of the NoteEditor class if desired. It is static, meaning it does not generate the so-called "synthetic methods" that all ow it to access data from the parent class, which in turn means that it really b ehaves as a separate class rather than something strongly related to NoteEditor. This is a cleaner way to create inner classes if they do not need access to sta te from the outer class, keeps the generated class small, and allows it to be us ed easily from other classes. It extends EditText, which is the View we have cho sen to customize in this case. When we are finished, the new class will be able to substitute for a normal EditText view. 2. Class Initialization As always, the super is called first. Furthermore, this is not a default constructor, but a pa rameterized one. The EditText is created with these parameters when it is inflat ed from an XML layout file, thus, our constructor needs to both take them and pa ss them to the superclass constructor as well. 3. Overridden Methods In this exa mple, there is only one method to be overridden: onDraw() but there could easily be others needed when you create your own custom components. For the NotePad sa mple, overriding the onDraw() method allows us to paint the blue lines on the Ed itText view canvas (the canvas is passed into the overridden onDraw() method). T he super.onDraw() method is called before the method ends. The superclass method should be invoked, but in this case, we do it at the end after we have painted the lines we want to include. http://developer.android.com/guide/topics/ui/custom-components.html Page 5 of 6

Building Custom Components | Android Developers 29.04.09 0:37 have painted the lines we want to include. 4. Use the Custom Component We now ha ve our custom component, but how can we use it? In the NotePad example, the cust om component is used directly from the declarative layout, so take a look at not e_editor.xml in the res/layout folder. <view class="com.android.notepad.NoteEdit or$MyEditText" id="@+id/note" android:layout_width="fill_parent" android:layout_ height="fill_parent" android:background="@android:drawable/empty" android:paddin g="10dip" android:scrollbars="vertical" android:fadingEdge="vertical" /> The cus tom component is created as a generic view in the XML, and the class is specifie d using the full package. Note also that the inner class we defined is reference d using the NoteEditor$MyEditText notation which is a standard way to refer to i nner classes in the Java programming language. If your custom View component is not defined as an inner class, then you can, alternatively, declare the View com ponent with the XML element name, and exclude the class attribute. For example: <com.android.notepad.MyEditText id="@+id/note" ... /> Notice that the MyEditText class is now a separate class file. When the class is nested in the NoteEditor class, this technique will not work. The other attributes and parameters in the definition are the ones passed into the custom component constructor, and then p assed through to the EditText constructor, so they are the same parameters that you would use for an EditText view. Note that it is possible to add your own par ameters as well, and we will touch on this again below. And that's all there is to it. Admittedly this is a simple case, but that's the point creating custom co mponents is only as complicated as you need it to be. A more sophisticated compo nent may override even more on... methods and introduce some of its own helper m ethods, substantially customizing its properties and behavior. The only limit is your imagination and what you need the component to do. " Back to User Interfac e Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/custom-components.html Page 6 of 6

Binding to Data with AdapterView | Android Developers 29.04.09 0:38 User Interface > Binding to Data with AdapterView The AdapterView is a ViewGroup subclass whose child Views are determined by an A dapter that binds to data of some type. AdapterView is useful whenever you need to display stored data (as opposed to resource strings or drawables) in your lay out. Gallery, ListView, and Spinner are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way. AdapterView objects have two main responsibilities: Filling the layout with data Handling user selections Filling the Layout with Data Inserting data into the layout is typically done by binding the AdapterView clas s to an Adapter, which retireves data from an external source (perhaps a list th at the code supplies or query results from the device's database). The following code sample does the following: 1. Creates a Spinner with an existing View and binds it to a new ArrayAdapter that reads an array of colors from the local reso urces. 2. Creates another Spinner object from a View and binds it to a new Simpl eCursorAdapter that will read people's names from the device contacts (see Conta cts.People). // Get a Spinner and bind it to an ArrayAdapter that // references a String array. Spinner s1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors, android.R.layo ut.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple _spinner_dropdown_item); s1.setAdapter(adapter); // Load a Spinner and bind it t o a data query. private static String[] PROJECTION = new String[] { People._ID, People.NAME }; Spinner s2 = (Spinner) findViewById(R.id.spinner2); Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null); SimpleCursorAdapter ad apter2 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, // Use a template // that displays a // text view cur, // Give the cursor to the li st adatper new String[] {People.NAME}, // Map the NAME column in the // people d atabase to... new int[] {android.R.id.text1}); // The "text1" view defined in // the XML template http://developer.android.com/guide/topics/ui/binding.html Page 1 of 2

Binding to Data with AdapterView | Android Developers 29.04.09 0:38 adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s2.setAdapter(adapter2); Note that it is necessary to have the People._ID colum n in projection used with CursorAdapter or else you will get an exception. If, d uring the course of your application's life, you change the underlying data that is read by your Adapter, you should call notifyDataSetChanged(). This will noti fy the attached View that the data has been changed and it should refresh itself . Handling User Selections You handle the user's selecction by setting the class's AdapterView.OnItemClickL istener member to a listener and catching the selection changes. // Create a mes sage handling object as an anonymous class. private OnItemClickListener mMessage ClickedHandler = new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Display a messagebox. Toast.makeTex t(mContext,"You've got an event",Toast.LENGTH_SHORT).show(); } }; // Now hook in to our object and set its onItemClickListener member // to our class handler obj ect. mHistoryView = (ListView)findViewById(R.id.history); mHistoryView.setOnItem ClickListener(mMessageClickedHandler); For more discussion on how to create different AdapterViews, read the following tutorials: Hello Spinner, Hello ListView, and Hello GridView. " Back to User Int erface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/binding.html Page 2 of 2

Common Layout Objects | Android Developers 29.04.09 0:38 User Interface > Common Layout Objects This section describes some of the more common types of layout objects to use in your applications. Like all layouts, they are subclasses of ViewGroup. Also see the Hello Views tutorials for some guidance on using more Android View layouts. FrameLayout FrameLayout is the simplest type of layout object. It's basically a blank space on your screen that you can later fill with a single object for example, a pictu re that you'll swap in and out. All child elements of the FrameLayout are pinned to the top left corner of the screen; you cannot specify a different location f or a child view. Subsequent child views will simply be drawn over previous ones, partially or totally obscuring them (unless the newer object is transparent). LinearLayout LinearLayout aligns all children in a single direction vertically or horizontall y, depending on how you define the orientation attribute. All children are stack ed one after the other, so a vertical list will only have one child per row, no matter how wide they are, and a horizontal list will only be one row high (the h eight of the tallest child, plus padding). A LinearLayout respects margins betwe en children and the gravity (right, center, or left alignment) of each child. Li nearLayout also supports assigning a weight to individual children. This attribu te assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Child views can specify an integer weight va lue, and then any remaining space in the view group is assigned to children in t he proportion of their declared weight. Default weight is zero. For example, if there are three text boxes and two of them declare a weight of 1, while the othe r is given no weight (0), the third text box without weight will not grow and wi ll only occupy the area required by its content. The other two will expand equal ly to fill the space remaining after all three boxes are measured. If the third box is then given a weight of 2 (instead of 0), then it is now declared "more im portant" than both the others, so it gets half the total remaining space, while the first two share the rest equally. The following two forms represent a Linear Layout with a set of elements: a button, some labels and text boxes. The text bo xes have their width set to fill_parent; other elements are set to wrap_content. The gravity, by default, is left. The difference between the two versions of th e form is that the form on the left has weight values unset (0 by default), whil e the form on the right has the comments text box weight set to 1. If the Name t extbox had also been set to 1, the Name and Comments text boxes would be the sam e height. Tip: To create a proportionate size layout on the screen, create a container vie w group object with the layout_width and layout_height attributes set to fill_pa rent; assign the children height or width to 0 (zero); then assign relative weig ht values to each child, depending on what proportion of the screen each should have. http://developer.android.com/guide/topics/ui/layout-objects.html Page 1 of 4

Common Layout Objects | Android Developers 29.04.09 0:38 Within a horizontal LinearLayout, items are aligned by the position of their tex t base line (the first line of the first list element topmost or leftmost is con sidered the reference line). This is so that people scanning elements in a form shouldn't have to jump up and down to read element text in neighboring elements. This can be turned off by setting android:baselineAligned="false" in the layout XML. To view other sample code, see the Hello LinearLayout tutorial. TableLayout TableLayout positions its children into rows and columns. TableLayout containers do not display border lines for their rows, columns, or cells. The table will h ave as many columns as the row with the most cells. A table can leave cells empt y, but cells cannot span columns, as they can in HTML. TableRow objects are the child views of a TableLayout (each TableRow defines a single row in the table). Each row has zero or more cells, each of which is defined by any kind of other V iew. So, the cells of a row may be composed of a variety of View objects, like I mageView or TextView objects. A cell may also be a ViewGroup object (for example , you can nest another TableLayout as a cell). The following sample layout has t wo rows and two cells in each. The accompanying screenshot shows the result, wit h cell borders displayed as dotted lines (added for visual effect). <?xml versio n="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.co m/apk/res/android" android:layout_width="fill_parent" android:layout_height="fil l_parent" android:stretchColumns="1"> <TableRow> <TextView android:text="@string /table_layout_4_open" android:padding="3dip" /> <TextView android:text="@string/ table_layout_4_open_shortcut" android:gravity="right" android:padding="3dip" /> </TableRow> <TableRow> <TextView android:text="@string/table_layout_4_save" andr oid:padding="3dip" /> <TextView android:text="@string/table_layout_4_save_shortc ut" android:gravity="right" android:padding="3dip" /> </TableRow> </TableLayout> Columns can be hidden, marked to stretch and fill the available screen space, or can be marked as shrinkable to force the column to shrink until the table fits the screen. See the TableLayout reference documentation for more details. http://developer.android.com/guide/topics/ui/layout-objects.html Page 2 of 4

Common Layout Objects | Android Developers 29.04.09 0:38 the column to shrink until the table fits the screen. See the TableLayout refere nce documentation for more details. To view sample code, see the Hello TableLayo ut tutorial. AbsoluteLayout AbsoluteLayout enables child views to specify their own exact x/y coordinates on the screen. Coordinates (0,0) is the upper left corner, and values increase as you move down and to the right. Margins are not supported, and overlapping eleme nts are allowed (although not recommended). We generally recommend against using AbsoluteLayout unless you have good reasons to use it, because it is fairly rig id and does not adjust to different types of displays. RelativeLayout RelativeLayout lets child views specify their position relative to the parent vi ew or to each other (specified by ID). So you can align two elements by right bo rder, or make one below another, centered in the screen, centered left, and so o n. Elements are rendered in the order given, so if the first element is centered in the screen, other elements aligning themselves to that element will be align ed relative to screen center. Also, because of this ordering, if using XML to sp ecify this layout, the element that you will reference (in order to position oth er view objects) must be listed in the XML file before you refer to it from the other views via its reference ID. The example below shows an XML file and the re sulting screen in the UI. Note that the attributes that refer to relative elemen ts (e.g., layout_toLeft) refer to the ID using the syntax of a relative resource (@id/id). <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android android:layout_width="fill_parent" a ndroid:layout_height="wrap_content" android:background="@drawable/blue" android: padding="10px" > <TextView android:id="@+id/label" android:layout_width="fill_pa rent" android:layout_height="wrap_content" android:text="Type here:" /> <EditTex t android:id="@+id/entry" android:layout_width="fill_parent" android:layout_heig ht="wrap_content" android:background="@android:drawable/editbox_background" andr oid:layout_below="@id/label" /> <Button android:id="@+id/ok" android:layout_widt h="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/ entry" android:layout_alignParentRight="true" android:layout_marginLeft="10px" a ndroid:text="OK" /> <Button android:layout_width="wrap_content" android:layout_h eight="wrap_content" android:layout_toLeftOf="@id/ok" android:layout_alignTop="@ id/ok" android:text="Cancel" /> </RelativeLayout> Some of these properties are supported directly by the element, and some are sup ported by its LayoutParams member (subclass RelativeLayout for all the elements in this screen, because all elements are children of a RelativeLayout parent obj ect). The defined RelativeLayout parameters are: width, height, below, alignTop, toLeft, padding[Bottom|Left|Right|Top], and margin[Bottom|Left|Right|Top]. Note that some of these parameters specifically support relative layout positions th eir values must be the ID of the element to which you'd like this view laid rela tive. For example, assigning the parameter toLeft="my_button" to a TextView woul d place the TextView to the left of the View with the ID my_button (which must b e written in the XML before the TextView). To view this sample code, see the Hel lo RelativeLayout tutorial. http://developer.android.com/guide/topics/ui/layout-objects.html Page 3 of 4

Common Layout Objects | Android Developers 29.04.09 0:38 Summary of Important View Groups These objects all hold child UI elements. Some provide their own form of a visib le UI, while others are invisible structures that only manage the layout of thei r child views. Class AbsoluteLayout FrameLayout Gallery GridView LinearLayout Li stView RelativeLayout ScrollView Spinner SurfaceView Description Enables you to specify the location of child objects relative to the parent in exact measuremen ts (for example, pixels). Layout that acts as a view frame to display a single o bject. A horizontal scrolling display of images, from a bound list. Displays a s crolling grid of m columns and n rows. A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of th e window exceeds the length of the screen. Displays a scrolling single column li st. Enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the par ent). A vertically scrolling column of elements. Displays a single item at a tim e from a bound list, inside a one-row textbox. Rather like a onerow listbox that can scroll either horizontally or vertically. Provides direct access to a dedic ated drawing surface. It can hold child views layered on top of the surface, but is intended for applications that need to draw pixels, rather than using widget s. Provides a tab selection list that monitors clicks and enables the applicatio n to change the screen whenever a tab is clicked. A tabular layout with an arbit rary number of rows and columns, each cell holding the widget of your choice. Th e rows resize to fit the largest column. The cell borders are not visible. A lis t that displays one item at a time, inside a one-row textbox. It can be set to s wap items at timed intervals, like a slide show. Same as ViewFlipper. ! Go to to p TabHost TableLayout ViewFlipper ViewSwitcher " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines http://developer.android.com/guide/topics/ui/layout-objects.html Page 4 of 4

How Android Draws Views | Android Developers 29.04.09 0:38 User Interface > How Android Draws Views When an Activity receives focus, it will be requested to draw its layout. The An droid framework will handle the procedure for drawing, but the Activity must pro vide the root node of its layout hierarchy. Drawing begins with the root node of the layout. It is requested to measure and draw the layout tree. Drawing is han dled by walking the tree and rendering each View that intersects the invalid reg ion. In turn, each View group is responsible for requesting each of its children to be drawn (with the draw() method) and each View is responsible for drawing i tself. Because the tree is traversed in-order, this means that parents will be d rawn before (i.e., behind) their children, with siblings drawn in the order they appear in the tree. Drawing the layout is a two pass process: a measure pass an d a layout pass. The measuring pass is implemented in measure(int, The framework will not draw Views that are not in the invalid region, and also will take care of int) and is a top-down traversal of the View tree. Each View drawing the Vie ws background for you. pushes dimension specifications down the tree during the recursion. You can force a View to draw, by calling At the end of the measure pa ss, every View has stored its invalidate(). measurements. The second pass happen s in layout(int, int, int, int) and is also top-down. During this pass each pare nt is responsible for positioning all of its children using the sizes computed i n the measure pass. When a View's measure() method returns, its getMeasuredWidth () and getMeasuredHeight() values must be set, along with those for all of that View's descendants. A View's measured width and measured height values must resp ect the constraints imposed by the View's parents. This guarantees that at the e nd of the measure pass, all parents accept all of their children's measurements. A parent View may call measure() more than once on its children. For example, t he parent may measure each child once with unspecified dimensions to find out ho w big they want to be, then call measure() on them again with actual numbers if the sum of all the children's unconstrained sizes is too big or too small (i.e., if the children don't agree among themselves as to how much space they each get , the parent will intervene and set the rules on the second pass). The measure p ass uses two classes to communicate dimensions. The View.MeasureSpec class is us ed by Views to tell their parents how they want to be measured and positioned. T he base LayoutParams class just describes how big the View wants to be for both width and height. For each dimension, it can specify one of: an exact number FIL L_PARENT, which means the View wants to be as big as its parent (minus padding) WRAP_CONTENT, which means that the View wants to be just big enough to enclose i ts content (plus padding). There are subclasses of LayoutParams for different su bclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of Layou tParams which adds an X and Y value. MeasureSpecs are used to push requirements down the tree from parent to child. A MeasureSpec can be in one of three modes: UNSPECIFIED: This is used by a parent to determine the desired dimension of a ch ild View. For example, a LinearLayout may call measure() on its child with the h eight set to UNSPECIFIED and a width of EXACTLY 240 to find out how tall the chi ld View wants to be given a width of 240 pixels. EXACTLY: This is used by the pa rent to impose an exact size on the child. The child must use this size, and gua rantee that all of its descendants will fit within this size. http://developer.android.com/guide/topics/ui/how-android-draws.html Page 1 of 2 To intiate a layout, call requestLayout(). This method is typically called by a View on itself when it believes that is can no longer fit within its current bou nds.

How Android Draws Views | Android Developers 29.04.09 0:38 AT_MOST: This is used by the parent to impose a maximum size on the child. The c hild must gurantee that it and all of its descendants will fit within this size. " Back to User Interface Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/ui/how-android-draws.html Page 2 of 2

Resources and Assets | Android Developers 29.04.09 0:40 Resources and Assets Resources are an integral part of an Android application. In general, these are external elements that you want to include and reference within your application , like images, audio, video, text strings, layouts, themes, etc. Every Android a pplication contains a directory for resources (res/) and a directory for assets (assets/). Assets are used less often, because their applications are far fewer. You only need to save data as an asset when you need to read the raw bites. The directories for resources and assets both reside at the top of your project dir ectory, alongside your source code directory (src/). The difference between "res ources" and "assets" isn't much on the surface, but in general, you'll use resou rces to store your external content much more often than you'll use assets. The real difference is that anything placed in the resources directory will be easil y accessible from your application from the R class, which is compiled by Androi d. Whereas, anything placed in the assets directory will maintain its raw file f ormat and, in order to read it, you must use the AssetManager to read the file a s a stream of bytes. So keeping files and data in resources (res/) makes them ea sily accessible. Within the documents of this topic, you'll find information on the kinds of standard resources that are typically used in an Android applicatio n and how to reference them from you code. Resources and Internationalization is where you should start, to learn more about how Android utilizes project resour ces. Then, the Available Resource Types document offers a summary of various res ource types and a reference to their specifications. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/resources/index.html Page 1 of 1

Resources and Internationalization | Android Developers 29.04.09 0:40 Resources and Assets > Resources and Internationalization Resources are external files (that is, non-code files) that are used by your cod e and compiled into your application at build time. Android supports a number of different kinds of resource files, including XML, PNG, and JPEG files. The XML files have very different formats depending on what they describe. This document describes what kinds of files are supported, and the syntax or format of each. Resources are externalized from source code, and XML files are compiled into a b inary, fast loading format for efficiency reasons. Strings, likewise are compres sed into a more efficient storage form. It is for these reasons that we have the se different resource types in the Android platform. This is a fairly technicall y dense document, and together with the Available Resources document, they cover a lot of information about resources. It is not necessary to know this document by heart to use Android, but rather to know that the information is here when y ou need it. Introduction This topic includes a terminology list associated with resources, and a series o f examples of using resources in code. For a complete guide to the supported And roid resource types, see Available Resources. The Android resource system keeps track of all non-code assets associated with an application. You use the Resourc es class to access your application's resources; the Resources instance associat ed with your application can generally be found through Context.getResources(). An application's resources are compiled into the application binary at build tim e for you by the build system. To use a resource, you must install it correctly in the source tree and build your application. As part of the build process, sym bols for each of the resources are generated that you can use in your source cod e -- this allows the compiler to verify that your application code matches up wi th the resources you defined. The rest of this section is organized as a tutoria l on how to use resources in an application. Creating Resources Android supports string, bitmap, and many other types of resource. The syntax an d format of each, and where they're stored, depends upon the type of object. In general, though, you create resources from three types of files: XML files (ever ything but bitmaps and raw), bitmap files(for images) and Raw files (anything el se, for example sound files, etc.). In fact, there are two different types of XM L file as well, those that get compiled as-is into the package, and those that a re used to generate resources by aapt. Here is a list of each resource type, the format of the file, a description of the file, and details of any XML files. Yo u will create and store your resource files under the appropriate subdirectory u nder the res/ directory in your project. Android has a resource compiler (aapt) that compiles resources according to which subfolder they are in, and the format of the file. Here is a list of the file types for each resource. See the Availa ble Resources for descriptions of each type of object, the syntax, and the forma t or syntax of the containing file. Directory Resource Types http://developer.android.com/guide/topics/resources/resources-i18n.html Page 1 of 9

Resources and Internationalization | Android Developers 29.04.09 0:40 res/anim/ res/drawable/ XML files that are compiled into frame by frame animation or tweened animation o bjects .png, .9.png, .jpg files that are compiled into the following Drawable re source subtypes: To get a resource of this type, use Resource.getDrawable(id) bi tmap files 9-patches (resizable bitmaps) res/layout/ res/values/ XML files that are compiled into screen layouts (or part of a screen). See Decla ring Layout XML files that can be compiled into many kinds of resource. Note: un like the other res/ folders, this one can hold any number of files that hold des criptions of resources to create rather than the resources themselves. The XML e lement types control where these resources are placed under the R class. While t he files can be named anything, these are the typical files in this folder (the convention is to name the file after the type of elements defined within): array s.xml to define arrays colors.xml to define color drawables and color string val ues. Use Resources.getDrawable() and Resources.getColor(), respectively, to get these resources. dimens.xml to define dimension value. Use Resources.getDimensio n() to get these resources. strings.xml to define string values (use either Reso urces.getString or preferably Resources.getText() to get these resources. getTex t() will retain any rich text styling which is usually desirable for UI strings. styles.xml to define style objects. res/xml/ res/raw/ Arbitrary XML files that are compiled and can be read at run time by calling Res ources.getXML(). Arbitrary files to copy directly to the device. They are added uncompiled to the compressed file that your application build produces. To use t hese resources in your application, call Resources.openRawResource() with the re source ID, which is R.raw.somefilename. Resources are compiled into the final APK file. Android creates a wrapper class, called R, that you can use to refer to these resources in your code. R contains subclasses named according to the path and file name of the source file Global Resource Notes Several resources allow you to define colors. Android accepts color values writt en in various web-style formats -a hexadecimal constant in any of the following forms: #RGB, #ARGB, #RRGGBB, #AARRGGBB. All color values support setting an alph a channel value, where the first two hexadecimal numbers specify the transparenc y. Zero in the alpha channel means transparent. The default value is opaque. Using Resources This section describes how to use the resources you've created. It includes the following topics: http://developer.android.com/guide/topics/resources/resources-i18n.html Page 2 of 9

Resources and Internationalization | Android Developers 29.04.09 0:40 Using resources in code - How to call resources in your code to instantiate them . Referring to resources from other resources - You can reference resources from other resources. This lets you reuse common resource values inside resources. S upporting Alternate Resources for Alternate Configurations - You can specify dif ferent resources to load, depending on the language or display configuration of the host hardware. At compile time, Android generates a class named R that conta ins resource identifiers to all the resources in your program. This class contai ns several subclasses, one for each type of resource supported by Android, and f or which you provided a resource file. Each class contains one or more identifie rs for the compiled resources, that you use in your code to load the resource. H ere is a small resource file that contains string, layout (screens or parts of s creens), and image resources. Note: the R class is an auto-generated file and is not designed to be edited by hand. It will be automatically recreated as needed when the resources are updated. package com.android.samples; public final class R { public static final class string { public static final int greeting=0x02040 00e; public static final int start_button_text=0x02040001; public static final i nt submit_button_text=0x02040008; public static final int main_screen_title=0x02 04000a; }; public static final class layout { public static final int start_scre en=0x02070000; public static final int new_user_pane=0x02070001; public static f inal int select_user_list=0x02070002; }; public static final class drawable { pu blic static final int company_logo=0x02020005; public static final int smiling_c at=0x02020006; public static final int yellow_fade_background=0x02020007; public static final int stretch_button_1=0x02020008; }; }; Using Resources in Code Using resources in code is just a matter of knowing the full resource ID and wha t type of object your resource has been compiled into. Here is the syntax for re ferring to a resource: R.resource_type.resource_name or android.R.resource_type. resource_name Where resource_type is the R subclass that holds a specific type o f resource. resource_name is the name attribute for resources defined in XML fil es, or the file name (without the extension) for resources defined by other file types. Each type of resource will be added to a specific R subclass, depending on the type of resource it is; to learn which R subclass hosts your compiled res ource type, consult the Available Resources document. Resources compiled by your own application can be referred to without a package name (simply as R.resource _type.resource_name). Android contains a number of standard resources, such as s creen styles and button backgrounds. To refer to these in code, you must qualify them with android, as in android.R.drawable.button_background. Here are some go od and bad examples of using compiled resources in code: http://developer.android.com/guide/topics/resources/resources-i18n.html Page 3 of 9

Resources and Internationalization | Android Developers 29.04.09 0:40 // Load a background for the current screen from a drawable resource. this.getWi ndow().setBackgroundDrawableResource(R.drawable.my_background_image); // WRONG S ending a string resource reference into a // method that expects a string. this. getWindow().setTitle(R.string.main_title); // RIGHT Need to get the title from t he Resources wrapper. this.getWindow().setTitle(Resources.getText(R.string.main_ title)); // Load a custom layout for the current screen. setContentView(R.layout .main_screen); // Set a slide in animation for a ViewFlipper object. mFlipper.se tInAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_in)); // Set t he text on a TextView object. TextView msgTextView = (TextView)findViewByID(R.id .msg); msgTextView.setText(R.string.hello_message); References to Resources A value supplied in an attribute (or resource) can also be a reference to a reso urce. This is often used in layout files to supply strings (so they can be local ized) and images (which exist in another file), though a reference can be any re source type including colors and integers. For example, if we have color resourc es, we can write a layout file that sets the text color size to be the value con tained in one of those resources: <?xml version="1.0" encoding="utf-8"?> <EditTe xt id="text" xmlns:android="http://schemas.android.com/apk/res/android" android: layout_width="fill_parent" android:layout_height="fill_parent" android:textColor ="@color/opaque_red" android:text="Hello, World!" /> Note here the use of the '@ ' prefix to introduce a resource reference -- the text following that is the nam e of a resource in the form of @[package:]type/name. In this case we didn't need to specify the package because we are referencing a resource in our own package . To reference a system resource, you would need to write: <?xml version="1.0" e ncoding="utf-8"?> <EditText id="text" xmlns:android="http://schemas.android.com/ apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_ parent" android:textColor="@android:color/opaque_red" android:text="Hello, World !" /> As another example, you should always use resource references when supplyi ng strings in a layout file so that they can be localized: <?xml version="1.0" e ncoding="utf-8"?> <EditText id="text" xmlns:android="http://schemas.android.com/ apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_ parent" android:textColor="@android:color/opaque_red" android:text="@string/hell o_world" /> This facility can also be used to create references between resource s. For example, we can create new drawable resources that are aliases for existi ng images: http://developer.android.com/guide/topics/resources/resources-i18n.html Page 4 o f 9

Resources and Internationalization | Android Developers 29.04.09 0:40 <?xml version="1.0" encoding="utf-8"?> <resources> <drawable id="my_background"> @android:drawable/theme2_background</drawable> </resources> References to Theme Attributes Another kind of resource value allows you to reference the value of an attribute in the current theme. This attribute reference can only be used in style resour ces and XML attributes; it allows you to customize the look of UI elements by ch anging them to standard variations supplied by the current theme, instead of sup plying more concrete values. As an example, we can use this in our layout to set the text color to one of the standard colors defined in the base system theme: <?xml version="1.0" encoding="utf-8"?> <EditText id="text" xmlns:android="http:/ /schemas.android.com/apk/res/android" android:layout_width="fill_parent" android :layout_height="fill_parent" android:textColor="?android:textDisabledColor" andr oid:text="@string/hello_world" /> Note that this is very similar to a resource r eference, except we are using an '?' prefix instead of '@'. When you use this ma rkup, you are supplying the name of an attribute resource that will be looked up in the theme -- because the resource tool knows that an attribute resource is e xpected, you do not need to explicitly state the type (which would be ?android:a ttr/android:textDisabledColor). Other than using this resource identifier to fin d the value in the theme instead of raw resources, the name syntax is identical to the '@' format: ?[namespace:]type/name with the type here being optional. Using System Resources Many resources included with the system are available to applications. All such resources are defined under the class "android.R". For example, you can display the standard application icon in a screen with the following code: public class MyActivity extends Activity { public void onStart() { requestScreenFeatures(FEAT URE_BADGE_IMAGE); super.onStart(); } setBadgeResource(android.R.drawable.sym_def _app_icon); } In a similar way, this code will apply to your screen the standard "green backgr ound" visual treatment defined by the system: public class MyActivity extends Ac tivity { public void onStart() { super.onStart(); } setTheme(android.R.style.The me_Black); } http://developer.android.com/guide/topics/resources/resources-i18n.html Page 5 of 9

Resources and Internationalization | Android Developers 29.04.09 0:40 Alternate Resources (for alternate languages and configurations) You can supply different resources for your product according to the UI language or hardware configuration on the device. Note that although you can include dif ferent string, layout, and other resources, the SDK does not expose methods to l et you specify which alternate resource set to load. Android detects the proper set for the hardware and location, and loads them as appropriate. Users can sele ct alternate language settings using the settings panel on the device. To includ e alternate resources, create parallel resource folders with qualifiers appended to the folder names, indicating the configuration it applies to (language, scre en orientation, and so on). For example, here is a project that holds one string resource file for English, and another for French: MyApp/ res/ values-en/ strin gs.xml values-fr/ strings.xml Android supports several types of qualifiers, with various values for each. Append these to the end of the resource folder name, s eparated by dashes. You can add multiple qualifiers to each folder name, but the y must appear in the order they are listed here. For example, a folder containin g drawable resources for a fully specified configuration would look like: MyApp/ res/ drawable-en-rUS-port-160dpi-finger-keysexposed-qwerty-dpad-480x320/ More t ypically, you will only specify a few specific configuration options that a reso urce is defined for. You may drop any of the values from the complete list, as l ong as the remaining values are still in the same order: MyApp/ res/ drawable-en -rUS-finger/ drawable-port/ drawable-port-160dpi/ drawable-qwerty/ Qualifier Lan guage Region Screen orientation Screen pixel density Touchscreen type Whether th e keyboard is available to the user Primary text input method Values The two let ter ISO 639-1 language code in lowercase. For example: en, fr, es The two letter ISO 3166-1-alpha-2 language code in uppercase preceded by a lowercase "r". For example: rUS, rFR, rES port, land, square 92dpi, 108dpi, etc. notouch, stylus, f inger keysexposed, keyshidden nokeys, qwerty, 12key http://developer.android.com/guide/topics/resources/resources-i18n.html Page 6 of 9

Resources and Internationalization | Android Developers 29.04.09 0:40 Primary non-touchscreen navigation method Screen dimensions nonav, dpad, trackball, wheel 320x240, 640x480, etc. The larger dimension must b e specified first. This list does not include device-specific parameters such as carrier, branding, device/hardware, or manufacturer. Everything that an application needs to know about the device that it is running on is encoded via the resource qualifiers in the table above. Here are some general guidelines on qualified resource directo ry names: Values are separated by a dash (as well as a dash after the base direc tory name) Values are case-sensitive (even though they must be unique across all folder names in a case-insensitive way) For example, A portrait-specific drawab le directory must be named drawable-port, not drawable-PORT. You may not have tw o directories named drawable-port and drawable-PORT, even if you had intended "p ort" and "PORT" to refer to different parameter values. Only one value for each qualifier type is supported (that is, you cannot specify drawable-rEN-rFR/) You can specify multiple parameters to define specific configurations, but they must always be in the order listed above. For example, drawable-en-rUS-land will app ly to landscape view, US-English devices. Android will try to find the most spec ific matching directory for the current configuration, as described below The or der of parameters listed in this table is used to break a tie in case of multipl e qualified directories (see the example given below) All directories, both qual ified and unqualified, live under the res/ folder. Qualified directories cannot be nested (you cannot have res/drawable/drawable-en) All resources will be refer enced in code or resource reference syntax by their simple, undecorated name. So if a resource is named this: MyApp/res/drawable-port-92dp/myimage.png It would be referenced as this: R.drawable.myimage (code) @drawable/myimage (XML) How Android finds the best matching directory Android will pick which of the various underlying resource files should be used at runtime, depending on the current configuration. The selection process is as follows: 1. Eliminate any resources whose configuration does not match the curre nt device configuration. For example, if the screen pixel density is 108dpi, thi s would eliminate only MyApp/res/drawable-port-92dpi/. MyApp/res/drawable/myimag e.png MyApp/res/drawable-en/myimage.png MyApp/res/drawable-port/myimage.png MyAp p/res/drawable-port-92dpi/myimage.png 2. Pick the resources with the highest num ber of matching configurations. For example, if our locale is en-GB and orientat ion is port, then we have two candidates with one matching configuration each: M yApp/res/drawableen/ and MyApp/res/drawable-port/. The directory MyApp/res/drawa ble/ is eliminated because it has zero matching configurations, while the others have one matching configuration. MyApp/res/drawable/myimage.png MyApp/res/drawa ble-en/myimage.png MyApp/res/drawable-port/myimage.png http://developer.android.com/guide/topics/resources/resources-i18n.html Page 7 o f 9

Resources and Internationalization | Android Developers 29.04.09 0:40 3. Pick the final matching file based on configuration precedence, which is the order of parameters listed in the table above. That is, it is more important to match the language than the orientation, so we break the tie by picking the lang uage-specific file, MyApp/res/drawable-en/. MyApp/res/drawable-en/myimage.png My App/res/drawable-port/myimage.png Terminology The resource system brings a number of different pieces together to form the fin al complete resource functionality. To help understand the overall system, here are some brief definitions of the core concepts and components you will encounte r in using it: Asset: A single blob of data associated with an application. This includes object files compiled from the Java source code, graphics (such as PNG images), XML files, etc. These files are organized in a directory hierarchy tha t, during final packaging of the application, is bundled together into a single ZIP file. aapt: Android Asset Packaging Tool. The tool that generates the final ZIP file of application assets. In addition to collecting raw assets together, i t also parses resource definitions into binary asset data. Resource Table: A spe cial asset that aapt generates for you, describing all of the resources containe d in an application/package. This file is accessed for you by the Resources clas s; it is not touched directly by applications. Resource: An entry in the Resourc e Table describing a single named value. Broadly, there are two types of resourc es: primitives and bags. Resource Identifier: In the Resource Table all resource s are identified by a unique integer number. In source code (resource descriptio ns, XML files, Java source code) you can use symbolic names that stand as consta nts for the actual resource identifier integer. Primitive Resource: All primitiv e resources can be written as a simple string, using formatting to describe a va riety of primitive types included in the resource system: integers, colors, stri ngs, references to other resources, etc. Complex resources, such as bitmaps and XML describes, are stored as a primitive string resource whose value is the path of the underlying Asset holding its actual data. Bag Resource: A special kind o f resource entry that, instead of a simple string, holds an arbitrary list of na me/value pairs. Each name is itself a resource identifier, and each value can ho ld the same kinds of string formatted data as a normal resource. Bags also suppo rt inheritance: a bag can inherit the values from another bag, selectively repla cing or extending them to generate its own contents. Kind: The resource kind is a way to organize resource identifiers for various purposes. For example, drawab le resources are used to instantiate Drawable objects, so their data is a primit ive resource containing either a color constant or string path to a bitmap or XM L asset. Other common resource kinds are string (localized string primitives), c olor (color primitives), layout (a string path to an XML asset describing a view layout), and style (a bag resource describing user interface attributes). There is also a standard "attr" resource kind, which defines the resource identifiers to be used for naming bag items and XML attributes Style: The name of the resou rce kind containing bags that are used to supply a set of user interface attribu tes. For example, a TextView class may be given a style resource that defines it s text size, color, and alignment. In a layout XML file, you associate a style w ith a bag using the "style" attribute, whose value is the name of the style reso urce. Style Class: Specifies a related set of attribute resources. This data is not placed in the resource table itself, but used to generate constants in the s ource code that make it easier for you to retrieve values out of a style resourc e and/or XML tag's attributes. For example, the Android platform defines a "View " style class that contains all of the standard http://developer.android.com/guide/topics/resources/resources-i18n.html Page 8 o f 9

Resources and Internationalization | Android Developers 29.04.09 0:40 XML tag's attributes. For example, the Android platform defines a "View" style c lass that contains all of the standard view attributes: padding, visibility, bac kground, etc.; when View is inflated it uses this style class to retrieve those values from the XML file (at which point style and theme information is applied as approriate) and load them into its instance. Configuration: For any particula r resource identifier, there may be multiple different available values dependin g on the current configuration. The configuration includes the locale (language and country), screen orientation, screen density, etc. The current configuration is used to select which resource values are in effect when the resource table i s loaded. Theme: A standard style resource that supplies global attribute values for a particular context. For example, when writing an Activity the application developer can select a standard theme to use, such as the Theme.White or Theme. Black styles; this style supplies information such as the screen background imag e/color, default text color, button style, text editor style, text size, etc. Wh en inflating a layout resource, most values for widgets (the text color, selecto r, background) if not explicitly set will come from the current theme; style and attribute values supplied in the layout can also assign their value from explic itly named values in the theme attributes if desired. Overlay: A resource table that does not define a new set of resources, but instead replaces the values of resources that are in another resource table. Like a configuration, this is appl ied at load time to the resource data; it can add new configuration values (for example strings in a new locale), replace existing values (for example change th e standard white background image to a "Hello Kitty" background image), and modi fy resource bags (for example change the font size of the Theme.White style to h ave an 18 pt font size). This is the facility that allows the user to select bet ween different global appearances of their device, or download files with new ap pearances. Resource Reference The Available Resources document provides a detailed list of the various types o f resource and how to use them from within the Java source code, or from other r eferences. Internationalization and Localization Coming Soon: Internationalization and Localization are critical, but are also no t quite ready yet in the current SDK. As the SDK matures, this section will cont ain information on the Internationalization and Localization features of the And roid platform. In the meantime, it is a good idea to start by externalizing all strings, and practicing good structure in creating and using resources. " Back t o Resources and Assets Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/resources/resources-i18n.html Page 9 of 9

Available Resource Types | Android Developers 29.04.09 0:40 Resources and Assets > Available Resource Types This page describes the different types of resources that you can externalize fr om your code and package with your application. For more details on how to use r esources in your application, please see the Resources and Internationalization documentation. Simple Values All simple resource values can be expressed as a string, using various formats t o unambiguously indicate the type of resource being created. For this reason, th ese values can be defined both as standard resources (under res/values/), as wel l as direct values supplied for mappings in styles and themes, and attributes in XML files such as layouts. Color Values A color value specifies an RGB value with an alpha channel, which can be used in various places such as specifying a solid color for a Drawable or the color to use for text. A color value always begins with a pound (#) character and then fo llowed by the Alpha-Red-Green-Blue information in one of the following formats: #RGB #ARGB #RRGGBB #AARRGGBB If you want to retrieve the color represented by a resource ID, you can call the Resources.getColor() method. Source file format: X ML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a ro ot <resources> element containing one or more <color> tags. Resource source file location: res/values/colors.xml (file name is arbitrary) Compiled resource data type: Resource pointer to a Java int. Resource reference name: Java: R.color.som e_name XML: @[package:]color/some_name (where some_name is the name of a specifi c color) Syntax <color name=color_name>#color_value</color> <color> Value is a c olor, using web-style syntax, as describe above. Has only one attribute: name The name used in referring to this color. http://developer.android.com/guide/topics/resources/available-resources.html Pag e 1 of 14

Available Resource Types | Android Developers 29.04.09 0:40 Example XML Declaration The following code declares two colors, the first fully opaque, and the second translucent. <resources> <color name="opaque_red">#f00</c olor> <color name="translucent_red">#80ff0000</color> </resources> Example Code Use Example Java code // Retrieve a color value. int color = getResources.getCol or(R.color.opaque_red); Example XML code <TextView android:layout_width="fill_pa rent" android:layout_height="wrap_content" android:textAlign="center" android:te xtColor="@color/translucent_red" android:text="Some Text"/> Strings and Styled Text Strings, with optional simple formatting, can be stored and retrieved as resourc es. You can add formatting to your string by using three standard HTML tags: <b> , <i>, and <u>. To guarantee getting an unstyled string only (the raw text) call the toString() method of the retrieved CharSequence object. Methods that accept string resources should be able to process these styling tags. If you want to r etrieve the String represented by a resource ID, you can call the Context.getStr ing() method. Note: If you use an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other kind of enclosing quo tes: <string <string <string <string name="good_example">"This'll work"</string> name="good_example_2">This\'ll also work</string> name="bad_example">This won't work!</string> name="bad_example_2">XML encodings won&apos;t work either!</stri ng> Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <string> tags . Resource source file location: res/values/strings.xml (file name is arbitrary) Compiled resource datatype: Resource pointer to a Java CharSequence. Resource r eference name: Java: R.string.some_name XML: @[package:]string/some_name (where some_name is the name of a specific string) Syntax <string name=string_name>stri ng_value</string> http://developer.android.com/guide/topics/resources/available-resources.html Pag e 2 of 14

Available Resource Types | Android Developers 29.04.09 0:40 <string> Value is a string, with optional styling tags. Has only one attribute: name - The name used in referring to this string. Example XML Declaration The fo llowing declares two strings: the first simple text with no formatting (resultin g in a CharSequence that is simply a String object) the second includes formatti ng information in the string (resulting in a CharSequence that is a complex data structure). If you are using the custom editor for string files in Eclipse, the HTML formatting tags will automatically be escaped and you will need to use Con text.getString() and fromHtml(String) to retreive the resource and then convert it to formatted text. <resources> <string name="simple_welcome_message">Welcome! </string> <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources> Example Code Use Example Java code // Assign a st yled string resource to a TextView // on the current screen. CharSequence str = getString(R.string.styled_welcome_message); TextView tv = (TextView)findViewByID (R.id.text); tv.setText(str); Example XML code <TextView android:layout_width="f ill_parent" android:layout_height="wrap_content" android:textAlign="center" andr oid:text="@string/simple_welcome_message"/> Using Styled Text as a Format String Sometimes you may want to create a styled text resource that is also used as a f ormat string. This cannot be done directly because there is no way of passing th e styled text as the format string argument of String.format() without stripping out the style information. The workaround is to store the style tags as escaped HTML tags, and then convert the escaped HTML string into a styled text after fo rmatting has taken place. To use styled text as a format string, do the followin g. 1. Store your styled text resource as an escaped string, so that the HTML tag s in your text resource are not interpreted as if they were XML tags: <resources > <string name="search_results_resultsTextFormat">%1$d results for &lt;b>&amp;qu ot;%2$s&amp;quot;&lt;/b></string> </resources> In this example the format string has two arguments: %1$d is a decimal number, %2$s is a string. 2. Make sure any String arguments are properly escaped if they might contain '<' or '&' characte rs. The htmlEncode(String) method will do this: String escapedTitle = TextUtil.h tmlEncode(title); http://developer.android.com/guide/topics/resources/available-resources.html Pag e 3 of 14

Available Resource Types | Android Developers 29.04.09 0:40 3. Use String.format() to format the HTML text, then use fromHtml(String) to con vert the HTML text into styled text: String resultsTextFormat = getContext().get Resources().getString(R.string.search_results_resultsTextFormat ); String result sText = String.format(resultsTextFormat, count, escapedTitle); CharSequence styl edResults = Html.fromHtml(resultsText); You can create common dimensions to use for various screen elements by defining dimension values in XML. A dimension resource is a number followed by a unit of measurement. For example: 10px, 2in, 5sp. Here are the units of measurement supp orted by Android: px Pixels - corresponds to actual pixels on the screen. in Inc hes - based on the physical size of the screen. mm Millimeters - based on the ph ysical size of the screen. pt Points - 1/72 of an inch based on the physical siz e of the screen. dp Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi scr een, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will c hange with the screen density, but not necessarily in direct proportion. Note: T he compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp ". sp Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when spec ifying font sizes, so they will be adjusted for both the screen density and user 's preference. Dimension values are not normally used as raw resources, but rath er as attribute values in XML files. You can, however, create plain resources co ntaining this data type. Source file format: XML file requiring a <?xml version= "1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <dimen> tags. Resource source file location: res/values/dimens.xml ( File name is arbitrary; standard practice is to put all dimensions in one file d evoted to dimensions.) Compiled resource datatype: Resource pointer to a dimensi on. Resource reference name: Java: R.dimen.some_name XML: @[package:]dimen/some_ name (where some_name is the name of a specific <dimen> element) Syntax <dimen n ame=dimen_name>dimen_value</dimen> <dimen> http://developer.android.com/guide/topics/resources/available-resources.html Pag e 4 of 14

Available Resource Types | Android Developers 29.04.09 0:40 A valid dimension value. name - The name used in referring to this dimension. Ex ample XML Declaration The following code declares several dimension values. <res ources> <dimen name="one_pixel">1px</dimen> <dimen name="double_density">2dp</di men> <dimen name="sixteen_sp">16sp</dimen> </resources> Example Code Use Example Java code: float dimen = Resources.getDimen(R.dimen.one_pixel); Example XML cod e: <TextView android:layout_width="fill_parent" android:layout_height="wrap_cont ent" android:textSize="@dimen/sixteen_sp"/> Drawables A Drawable is a type of resource that you retrieve with Resources.getDrawable() and use to draw to the screen. There are a number of drawable resources that can be created. Bitmap Files Android supports bitmap resource files in a few different formats: png (preferre d), jpg (acceptable), gif (discouraged). The bitmap file itself is compiled and referenced by the file name without the extension (so res/drawable/my_picture.pn g would be referenced as R.drawable.my_picture). Source file formats: png (prefe rred), jpg (acceptable), gif (discouraged). One resource per file. Resource file location: res/drawable/some_file.png or some_file.jpg or some_file.gif. Compile d resource datatype: Resource pointer to a BitmapDrawable. Resource reference na me: Java: R.drawable.some_file XML: @[package:]drawable/some_file For more discu ssion and examples using drawable resources, see the discussion in 2D Graphics. Color Drawables You can create a PaintDrawable object that is a rectangle of color, with optiona lly rounded corners. This element can be defined in any of the files inside res/ values/. http://developer.android.com/guide/topics/resources/available-resources.html Page 5 of 14

Available Resource Types | Android Developers 29.04.09 0:40 Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?> declaration, and a root <resources> element containing one or more <drawable> ta gs. Resource source file location: res/values/colors.xml (File name is arbitrary ; standard practice is to put the PaintDrawable items in the file along with the numeric color values.) Compiled resource datatype: Resource pointer to a PaintD rawable. Resource reference name: Java: R.drawable.some_name XML: @[package:]dra wable/some_name (where some_name is the name of a specific resource) Syntax <dra wable name=color_name>color_value</drawable> <drawable> A valid color value. nam e - The name used in referring to this drawable. Example XML Declaration The fol lowing code declares several color drawables. <resources> <drawable name="solid_ red">#f00</drawable> <drawable name="solid_blue">#0000ff</drawable> <drawable na me="solid_green">#f0f0</drawable> </resources> Example Code Use Example Java cod e // Assign a PaintDrawable as the background to // a TextView on the current sc reen. Drawable redDrawable = Resources.getDrawable(R.drawable.solid_red); TextVi ew tv = (TextView)findViewByID(R.id.text); tv.setBackground(redDrawable); Exampl e XML code <TextView android:layout_width="fill_parent" android:layout_height="w rap_content" android:textAlign="center" android:background="@drawable/solid_red" /> Nine-Patch (stretchable) Images Android supports a stretchable bitmap image, called a NinePatch graphic. This is a PNG image in which you define stretchable sections that Android will resize t o fit the object at display time to accommodate variable sized sections, such as text strings. You typically assign this resource to the View's background. An e xample use of a stretchable image is the button backgrounds that Android uses; b uttons must stretch to accommodate strings of various lengths. Source file forma t: PNG one resource per file http://developer.android.com/guide/topics/resources/available-resources.html Pag e 6 of 14

Available Resource Types | Android Developers 29.04.09 0:40 Resource source file location: res/drawable/some_name.9.png (must end in .9.png) Compiled resource datatype: Resource pointer to a NinePatchDrawable. Resource r eference name: Java: R.drawable.some_file XML: @[package:]drawable.some_file For more information and examples using NinePatch drawables, see the discussion in 2D Graphics. Animation Tweened Animation Android can perform simple animation on a graphic, or a series of graphics. Thes e include rotations, fading, moving, and stretching. Source file format: XML fil e, one resource per file, one root tag with no <?xml> declaration Resource file location: res/anim/some_file.xml Compiled resource datatype: Resource pointer to an Animation. Resource reference name: Java: R.anim.some_file XML: @[package:]a nim/some_file Syntax The file must have a single root element: this will be eith er a single <alpha>, <scale>, <translate>, <rotate>, interpolator element, or <s et> element that holds groups of these elements (which may include another <set> ). By default, all elements are applied simultaneously. To have them occur seque ntially, you must specify the startOffset attribute. <set android:shareInterpola tor=boolean> used. <alpha android:fromAlpha=float android:toAlpha=float > | <sca le android:fromXScale=float android:toXScale=float android:fromYScale=float andr oid:toYScale=float android:pivotX=string android:pivotY=string > | <translate an droid:fromX=string android:toX=string android:fromY=string android:toY=string > | <rotate android:fromDegrees=float android:toDegrees=float android:pivotX=strin g android:pivotY=string > | <interpolator tag> <set> </set> // Only required if multiple tags are http://developer.android.com/guide/topics/resources/available-resources.html Page 7 of 14

Available Resource Types | Android Developers 29.04.09 0:40 Elements and Attributes <set> A container that can recursively hold itself or ot her animations. Represents an AnimationSet. You can include as many child elemen ts of the same or different types as you like. Supports the following attribute: shareInterpolator - Whether to share the same Interpolator among all immediate child elements. <alpha> A fading animation. Represents an AlphaAnimation. Suppor ts the following attributes: fromAlpha - 0.0 to 1.0, where 0.0 is transparent. t oAlpha - 0.0 to 1.0, where 0.0 is transparent. <scale> A resizing animation. Rep resents a ScaleAnimation. You can specify what is the center point of the image (the pinned center), from which it grows outward (or inward), by specifying pivo tX and pivotY. So, for example, if these were 0, 0 (top left corner), all growth would be down and to the right. scale supports the following attributes: fromXS cale - Starting X size, where 1.0 is no change. toXScale - Ending X size, where 1.0 is no change. fromYScale - Starting Y size, where 1.0 is no change. toYScale - Ending Y size, where 1.0 is no change. pivotX - The X coordinate of the pinne d center. pivotY - The Y coordinate of the pinned center. <translate> A vertical /horizontal motion animation. Represents a TranslateAnimation. Supports the foll owing attributes in any of the following three formats: values from -100 to 100, ending with "%", indicating a percentage relative to itself; values from -100 t o 100, ending in "%p", indicating a percentage relative to its parent; a float w ith no suffix, indicating an absolute value. fromXDelta - Starting X location. t oXDelta - Ending X location. fromYDelta - Starting Y location. toYDelta - Ending Y location. <rotate> A rotation animation. Represents a RotateAnimation. Suppor ts the following attributes: fromDegrees - Starting rotation, in degrees. toDegr ees - Ending rotation, in degrees. pivotX - The X coordinate of the center of ro tation, in pixels, where (0,0) is the top left corner. pivotY - The Y coordinate of the center of rotation, in pixels, where (0,0) is the top left corner. <inte rpolator tag> You can also use any of the interpolator subclass elements defined in R.styleable. Examples include <CycleInterpolator>, <EaseInInterpolator>, and <EaseOutInterpolator>. These objects define a velocity curve that describes how quickly a visual action takes place on a timeline (fast at first and slow later , slow at first and gradually faster, and so on). In addition to the attributes defined for each element above, the elements <alpha>, <scale>, <translate>, <rot ate>, and <set> all support the following attributes (inherited from the Animati on class): duration Duration, in milliseconds, for this effect. http://developer.android.com/guide/topics/resources/available-resources.html Page 8 of 14

Available Resource Types | Android Developers 29.04.09 0:40 startOffset Offset start time for this effect, in milliseconds. fillBefore When set true, the animation transformation is applied before the animation begins. f illAfter When set true, the animation transformation is applied after the animat ion ends. repeatCount Defines the number of times the animation should repeat. r epeatMode Defines the animation behavior when it reaches the end and the repeat count is greater than 0. Options are to either restart or reverse the animation. zAdjustment Defines the z-axis ordering mode to use when running the animation (normal, top, or bottom). interpolator You can optionally set an interpolator fo r each element to determine how quickly or slowly it performs its effect over ti me. For example, slow at the beginning and faster at the end for EaseInInterpola tor, and the reverse for EaseOutInterpolator. A list of interpolators is given i n R.anim. To specify these, use the syntax @android:anim/interpolatorName. For m ore discussion and animation code samples, see the discussion in the 2D Graphics document. Menus Application menus (Options Menu, Context Menu, or Sub Menu) can be defined as XM L resources and inflated by your application using MenuInflater. Source file for mat: XML file, one resource per file, one root tag, <?xml> declaration not requi red. Resource file location: res/menu/some_file.xml Compiled resource datatype: Resource pointer to a Menu (or subclass) resource. Resource reference name: Java : R.menu.some_file Syntax The file must have a single root element: a <menu> element. In all, there are th ree valid elements: <menu>, <group> and <item>. The <item> and <group> elements must be the children of a <menu>, but <item> elements can also be the children o f a <group>, and another <menu> element may be the child of an <item> (to create a Sub Menu). <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/example_item android:title="Example Item" android:icon="@ drawable/example_item_icon" /> <group android:id="@+id/example_group"> <item and roid:id="@+id/example_item2 android:title="Example Item 2" android:icon="@drawab le/example_item2_icon" /> http://developer.android.com/guide/topics/resources/available-resources.html Pag e 9 of 14

Available Resource Types | Android Developers 29.04.09 0:40 android:icon="@drawable/example_item2_icon" /> </group> <item android:id="@+id/e xample_submenu android:title="Example Sub Menu" > <menu> <item android:id="@+id/ example_submenu_item android:title="Example Sub Menu Item" /> </menu> </item> </ menu> Elements and Attributes All attributes must be defined with the android namespace (e.g., android:icon="@ drawable/icon"). <menu> The root of a menu. Contains <item> and <group> nodes. N o attributes. <group> A menu group. Contains <item> elements. Valid attributes: id - A unique integer ID for the group. menuCategory - Value corresponding to Me nu CATEGORY_* constants defines the priority of the group. Valid values: contain er, system, secondary, and alternative. orderInCategory - An integer that define s the default order of the items within the category. checkableBehavior - Whethe r the items are checkable. Valid values: none, all (exclusive / radio buttons), single (non-exclusive / checkboxes) visible - Whether the group is visible. true or false. enabled - Whether the group is enabled. true or false. <item> A menu item. May contain a <menu> element (for a Sub Menu). Valid attributes: id - A un ique resource ID for the item. menuCategory - Used to define the menu category. orderInCategory - Used to define the order of the item, within a group. title A string for the menu title. titleCondensed - A condensed string title, for situ ations in which the normal title is too long. icon - A resource identifier for a drawable icon. alphabeticShortcut - A character for the alphabetic shortcut key . numericShortcut - A number for the numeric shortcut key. checkable - Whether t he item is checkable. true or false. checked - Whether the item is checked by de fault. true or false. visible - Whether the item is visible by default. true or false. enabled - Whether the item is enabled by default. true or false. For more discussion on how to create menus in XML and inflate them in your application, read Creating Menus. Layout Android lets you specify screen layouts using XML elements inside an XML file, s imilar to designing screen layout for a webpage in an HTML file. Each file conta ins a whole screen or a part of a screen, and is compiled into a View http://developer.android.com/guide/topics/resources/available-resources.html Pag e 10 of 14

Available Resource Types | Android Developers 29.04.09 0:40 webpage in an HTML file. Each file contains a whole screen or a part of a screen , and is compiled into a View resource that can be passed in to Activity.setCont entView or used as a reference by other layout resource elements. Files are save d in the res/layout/ folder of your project, and compiled by the Android resourc e compiler, aapt. Every layout XML file must evaluate to a single root element. First we'll describe how to use the standard XML tags understood by Android as i t is shipped, and then we'll give a little information on how you can define you r own custom XML elements for custom View objects. The root element must have th e Android namespace "http://schemas.android.com/apk/res/android" defined in the root element. For a complete discussion on creating layouts, see the User Interf ace topic. Source file format: XML file requiring a <?xml version="1.0" encoding ="utf-8"?> declaration, and a root element of one of the supported XML layout el ements. Resource file location: res/layout/some_file.xml. Compiled resource data type: Resource pointer to a View (or subclass) resource. Resource reference name : Java: R.layout.some_file XML: @[package:]layout/some_file Syntax <ViewGroupCla ss xmlns:android="http://schemas.android.com/apk/res/android" id="@+id/string_na me" (attributes)> <widget or other nested ViewGroupClass>+ <requestFocus/>(0 or 1 per layout file, assigned to any element) </ViewGroupClass> <ViewGroupClass> T he file must have a single root element. This can be a ViewGroup class that cont ains other elements, or a widget (or custom item) if it's only one object. By de fault, you can use any (case-sensitive) Android widget or ViewGroup class name a s an element. These elements support attributes that apply to the underlying cla ss, but the naming is not as clear. How to discover what attributes are supporte d for what tags is discussed below. You should not assume that any nesting is va lid (for example you cannot enclose <TextView> elements inside a <ListLayout>). If a class derives from another class, the XML element inherits all the attribut es from the element that it "derives" from. So, for example, <EditText> is the c orresponding XML element for the EditText class. It exposes its own unique attri butes (EditText_numeric), as well as all attributes supported by <TextView> and <View>. For the id attribute of a tag in XML, you should use a special syntax: " @+id/somestringvalue". The "@+" syntax creates a resource number in the R.id cla ss, if one doesn't exist, or uses it, if it does exist. When declaring an ID val ue for an XML tag, use this syntax. Example: <TextView id="@+id/nameTextbox"/>, and refer to it this way in Java: findViewById(R.id.nameTextbox). All elements s upport the following values: id - An ID value used to access this element in Jav a. Typically you will use the syntax @+id/string_name to generate an ID for you in the id.xml file if you haven't created one yourself. xmlns:android="http://sc hemas.android.com/apk/res/android" - Required for the root element only. <reques tFocus> Any element representing a View object can include this empty element, w hich gives it's parent tag initial focus on the screen. You can have only one of these elements per file. http://developer.android.com/guide/topics/resources/available-resources.html Page 11 of 14

Available Resource Types | Android Developers 29.04.09 0:40 What Attributes Are Supported for What Elements? Android uses the LayoutInflater class at run time to load an XML layout resource and translate it into visual e lements. By default, all widget class names are supported directly as tags, but a full list of supported tags and attributes is listed in the R.styleable refere nce page. However, the attribute names are somewhat obscure. If an underscore ap pears in the name, this indicates that it is an attribute typically of the eleme nt before the underscore. So, for example, EditText_autoText means that the <Edi tText> tag supports an attribute autoText. When you actually use the attribute i n that element, use only the portion after the last underscore, and prefix the a ttribute with the prefix "android:". So, for example, if R.styleable lists the f ollowing values: TextView TextView_lines TextView_maxlines You could create an e lement like this: <TextView android:lines="10" android:maxlines="20"/> This woul d create a TextView object and set its lines and maxlines properties. Attributes come from three sources: Attributes exposed directly by the element. For exampl e, TextView supports TextView_text, as discussed above. Attributes exposed by al l the superclasses of that element. For example, the TextView class extends the View class, so the <TextView> element supports all the attributes that the <View > element exposes a long list, including View_paddingBottom and View_scrollbars. These too are used without the class name: <TextView android:paddingBottom="20" android:scrollbars="horizontal" />. Attributes of the object's ViewGroup.Layout Params subclass. All View objects support a LayoutParams member (see Declaring L ayout). To set properties on an element's LayoutParams member, the attribute to use is "android:layout_layoutParamsProperty". For example: android:layout_gravit y for an object wrapped by a <LinearLayout> element. Remember that each LayoutPa rams subclass also supports inherited attributes. Attributes exposed by each sub class are given in the format someLayoutParamsSubclass_Layout_layout_somepropert y. This defines an attribute "android:layout_someproperty". Here is an example o f how Android documentation lists the properties of the LinearLayout.LayoutParam s class: LinearLayout_Layout // The actual object not used. LinearLayout_Layout_ layout_gravity // Exposes a gravity attribute LinearLayout_Layout_layout_height // Exposes a height attribute LinearLayout_Layout_layout_weight // Exposes a wei ght attribute LinearLayout_Layout_layout_width // Exposes a width attribute Here is an example that sets some of these values on a few objects, including direct attributes, inherited attributes, and LayoutParams attributes: <?xml version="1 .0" encoding="utf-8"?> <!-- res/main_screen.xml --> <LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android" android:orientation="vertical" // T he object's own orientation property android:padding="4" // Inherited View prope rty android:gravity="center" // The object's own property android:layout_width=" fill_parent" // Parent object's LinearLayout.LayoutParams.width http://developer.android.com/guide/topics/resources/available-resources.html Pag e 12 of 14

Available Resource Types | Android Developers 29.04.09 0:40 LinearLayout.LayoutParams.width android:layout_height="fill_parent"> // Parent o bject's LinearLayout.LayoutParams.height <TextView android:layout_width="fill_pa rent" // TextView.LayoutParams.width android:layout_height="wrap_content" // Tex tView.LayoutParams.height android:layout_weight="0" // TextView.LayoutParams.wei ght android:paddingBottom="4" // TextView.paddingBottom android:text="@string/re direct_getter"/> // TextView.text <EditText id="@+id/text" android:layout_width= "fill_parent" android:layout_height="wrap_content" android:layout_weight="0" Edi tText.LinearLayoutParams.weight android:paddingBottom="4"> <requestFocus /> </Ed itText> // EditText.LayoutParams.width // EditText.LayoutParams.height // // Edi tText.paddingBottom <Button id="@+id/apply" android:layout_width="wrap_content" // Button.LayoutPara ms.width android:layout_height="wrap_content" // Button.LayoutParams.height andr oid:text="@string/apply" /> // TextView.text </LinearLayout> Example Code Use Th e most common use is to load the XML file (located at res/main_screen.xml) and u se it as the current screen, as shown here with the preceding file: setContentVi ew(R.layout.main_screen); However, layout elements can also represent repeating elements used as templates. Also see User Interface for more information on layo uts. Custom Layout Resources You can define custom elements to use in layout resources. These custom elements can then be used the same as any Android layout elements: that is, you can use them and specify their attributes in other resources. The ApiDemos sample applic ation has an example of creating a custom layout XML tag, LabelView. To create a custom element, you will need the following files: Java implementation file - T he implementation file. The class must extend View or a subclass. See LabelView. java in ApiDemos. res/values/attrs.xml - Defines the XML element, and the attrib utes that it supports, for clients to use to instantiate your object in their la yout XML file. Define your element in a <declare-styleable id=your_java_class_na me>. See res/layout/attrs.xml in ApiDemos. res/layout/your_class.xml [optional] - An optional XML file to describe the layout of your object. This could also be done in Java. See custom_view_1.xml in ApiDemos. Source file format: XML file w ithout an <?xml> declaration, and a <resources> root element containing one or m ore custom element tags. Resource file location: res/values/attrs.xml (file name is arbitrary). Compiled resource datatype: Resource pointer to a View (or subcl ass) resource. Resource reference name: R.styleable.some_file (Java). http://developer.android.com/guide/topics/resources/available-resources.html Page 13 of 14

Available Resource Types | Android Developers 29.04.09 0:40 Styles and Themes A style is one or more attributes applied to a single element (for example, 10 p oint red Arial font, applied to a TextView). A style is applied as an attribute to an element in a layout XML file. A theme is one or more attributes applied to a whole screen for example, you might apply the stock Android Theme.dialog them e to an activity designed to be a floating dialog box. A theme is assigned as an attribute to an Activity in the manifest file. Both styles and themes are defin ed in a <style> block containing one or more string or numerical values (typical ly color values), or references to other resources (drawables and so on). These elements support inheritance, so you could have MyBaseTheme, MyBaseTheme.Fancy, MyBaseTheme.Small, and so on. For a complete discussion on styles and themes, re ad Applying Styles and Themes. Source file format: XML file requiring a <?xml ve rsion="1.0" encoding="utf-8"?> declaration, and a root <resources> element conta ining one or more <style> tags. Resource source file location: res/values/styles .xml (file name is arbitrary). The file name is arbitrary, but standard practice is to put all styles into a file named styles.xml. Compiled resource datatype: Resource pointer to a Java CharSequence. Resource reference name: Java: R.style. styleID for the whole style, R.style.styleID.itemID for an individual setting XM L: @[package:]style/styleID for a whole style, @[package:]style/styleID/itemID f or an individual item. Note: to refer to a value in the currently applied theme, use "?" instead of "@" as described below (XML). Syntax <style name=string [par ent=string] > <item name=string>Hex value | string value | reference</item>+ </s tyle> <style> Holds one or more <item> elements, each describing one value. This style, which is a bundle of values, can be referred to as a theme. name - The n ame used in referring to this theme. parent - An optional parent theme. All valu es from the specified theme will be inherited into this theme. Any values with i dentical names that you specify will override inherited values. The name must be qualified by the package, but you don't need the /style directive (for example, android:Theme for the base Android theme, or MyTheme for a theme defined in you r package). <item> A value to use in this theme. It can be a standard string, a hex color value, or a reference to any other resource type. For examples of how to declare and apply styles and themes, read Applying Styles and Themes. " Back to Resources and Assets Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/resources/available-resources.html Page 14 of 14

Intents and Intent Filters | Android Developers 29.04.09 0:40 Intents and Intent Filters Three of the core components of an application activities, services, and broadca st receivers are activated through messages, called intents. Intent messaging is a facility for late run-time binding between components in the same or differen t applications. The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed or, in the case of broadcasts, a description of something that has happened and is being announ ced. There are separate mechanisms for delivering intents to each type of compon ent: An Intent object is passed to Context.startActivity() or Activity.startActi vityForResult() to launch an activity or get an existing activity to do somethin g new. An Intent object is passed to Context.startService() to initiate a servic e or deliver new instructions to an ongoing service. Similarly, an intent can be passed to Context.bindService() to establish a connection between the calling c omponent and a target service. It can optionally initiate the service if it's no t already running. Intent objects passed to any of the broadcast methods (such a s Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendSticky Broadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code. In each case, the Android system finds the appropriate activity, service, or set of broadcast receivers to respond to the i ntent, instantiating them if necessary. There is no overlap within these messagi ng systems: Broadcast intents are delivered only to broadcast receivers, never t o activities or services. An intent passed to startActivity() is delivered only to an activity, never to a service or broadcast receiver, and so on. This docume nt begins with a description of Intent objects. It then describes the rules Andr oid uses to map intents to components how it resolves which component should rec eive an intent message. For intents that don't explicitly name a target componen t, this process involves testing the Intent object against intent filters associ ated with potential targets. Intent Objects An Intent object is a bundle of information. It contains information of interest to the component that receives the intent (such as the action to be taken and t he data to act on) plus information of interest to the Android system (such as t he category of component that should handle the intent and instructions on how t o launch a target activity). Principally, it can contain the following: Componen t name The name of the component that should handle the intent. This field is a ComponentName object a combination of the fully qualified class name of the targ et component (for example "com.example.project.app.FreneticActivity") and the pa ckage name set in the manifest file of the application where the component resid es (for example, "com.example.project"). The package part of the component name and the package name set in the manifest do not necessarily have to match. The c omponent name is optional. If it is set, the Intent object is delivered to an in stance of the designated class. If it is not set, Android uses other information in the Intent object to locate a suitable target see Intent Resolution, later i n this document. The component name is set by setComponent(), setClass(), or set ClassName() and read by getComponent(). http://developer.android.com/guide/topics/intents/intents-filters.html Page 1 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 Action A string naming the action to be performed or, in the case of broadcast i ntents, the action that took place and is being reported. The Intent class defin es a number of action constants, including these: Constant ACTION_CALL ACTION_ED IT ACTION_MAIN ACTION_SYNC ACTION_BATTERY_LOW ACTION_HEADSET_PLUG ACTION_SCREEN_ ON ACTION_TIMEZONE_CHANGED Target component activity activity activity activity broadcast receiver broadcast receiver broadcast receiver broadcast receiver Acti on Initiate a phone call. Display data for the user to edit. Start up as the ini tial activity of a task, with no data input and no returned output. Synchronize data on a server with data on the mobile device. A warning that the battery is l ow. A headset has been plugged into the device, or unplugged from it. The screen has been turned on. The setting for the time zone has changed. See the Intent class description for a list of pre-defined constants for generic actions. Other actions are defined elsewhere in the Android API. You can also d efine your own action strings for activating the components in your application. Those you invent should include the application package as a prefix for example : "com.example.project.SHOW_COLOR". The action largely determines how the rest o f the intent is structured particularly the data and extras fields much as a met hod name determines a set of arguments and a return value. For this reason, it's a good idea to use action names that are as specific as possible, and to couple them tightly to the other fields of the intent. In other words, instead of defi ning an action in isolation, define an entire protocol for the Intent objects yo ur components can handle. The action in an Intent object is set by the setAction () method and read by getAction(). Data The URI of the data to be acted on and t he MIME type of that data. Different actions are paired with different kinds of data specifications. For example, if the action field is ACTION_EDIT, the data f ield would contain the URI of the document to be displayed for editing. If the a ction is ACTION_CALL, the data field would be a tel: URI with the number to call . Similarly, if the action is ACTION_VIEW and the data field is an http: URI, th e receiving activity would be called upon to download and display whatever data the URI refers to. When matching an intent to a component that is capable of han dling the data, it's often important to know the type of data (its MIME type) in addition to its URI. For example, a component able to display image data should not be called upon to play an audio file. In many cases, the data type can be i nferred from the URI particularly content: URIs, which indicate that the data is located on the device and controlled by a content provider (see the separate di scussion on content providers). But the type can also be explicitly set in the I ntent object. The setData() method specifies data only as a URI, setType() speci fies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType(). http://developer.android.com/guide/topics/intents/intents-filters.html Page 2 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 Category A string containing additional information about the kind of component that should handle the intent. Any number of category descriptions can be placed in an Intent object. As it does for actions, the Intent class defines several c ategory constants, including these: Constant CATEGORY_BROWSABLE CATEGORY_GADGET CATEGORY_HOME CATEGORY_LAUNCHER CATEGORY_PREFERENCE Meaning The target activity can be safely invoked by the browser to display data referenced by a link for ex ample, an image or an e-mail message. The activity can be embedded inside of ano ther activity that hosts gadgets. The activity displays the home screen, the fir st screen the user sees when the device is turned on or when the HOME key is pre ssed. The activity can be the initial activity of a task and is listed in the to p-level application launcher. The target activity is a preference panel. See the Intent class description for the full list of categories. The addCategor y() method places a category in an Intent object, removeCategory() deletes a cat egory previously added, and getCategories() gets the set of all categories curre ntly in the object. Extras Key-value pairs for additional information that shoul d be delivered to the component handling the intent. Just as some actions are pa ired with particular kinds of data URIs, some are paired with particular extras. For example, an ACTION_TIMEZONE_CHANGED intent has a "time-zone" extra that ide ntifies the new time zone, and ACTION_HEADSET_PLUG has a "state" extra indicatin g whether the headset is now plugged in or unplugged, as well as a "name" extra for the type of headset. If you were to invent a SHOW_COLOR action, the color va lue would be set in an extra key-value pair. The Intent object has a series of p ut...() methods for inserting various types of extra data and a similar set of g et...() methods for reading the data. These methods parallel those for Bundle ob jects. In fact, the extras can be installed and read as a Bundle using the putEx tras() and getExtras() methods. Flags Flags of various sorts. Many instruct the Android system how to launch an activity (for example, which task the activity s hould belong to) and how to treat it after it's launched (for example, whether i t belongs in the list of recent activities). All these flags are defined in the Intent class. The Android system and the applications that come with the platfor m employ Intent objects both to send out systemoriginated broadcasts and to acti vate system-defined components. To see how to structure an intent to activate a system component, consult the list of intents in the reference. Intent Resolution Intents can be divided into two groups: Explicit intents designate the target co mponent by its name (the component name field, mentioned earlier, has a value se t). Since component names would generally not be known to developers of other ap plications, explicit intents are typically used for application-internal message s such as an activity starting a subordinate service or launching a sister activ ity. Implicit intents do not name a target (the field for the component name is blank). Implicit intents are often used to activate components in other applicat ions. http://developer.android.com/guide/topics/intents/intents-filters.html Page 3 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 Android delivers an explicit intent to an instance of the designated target clas s. Nothing in the Intent object other than the component name matters for determ ining which component should get the intent. A different strategy is needed for implicit intents. In the absence of a designated target, the Android system must find the best component (or components) to handle the intent a single activity or service to perform the requested action or the set of broadcast receivers to respond to the broadcast announcement. It does so by comparing the contents of t he Intent object to intent filters, structures associated with components that c an potentially receive intents. Filters advertise the capabilities of a componen t and delimit the intents it can handle. They open the component to the possibil ity of receiving implicit intents of the advertised type. If a component does no t have any intent filters, it can receive only explicit intents. A component wit h filters can receive both explicit and implicit intents. Only three aspects of an Intent object are consulted when the object is tested against an intent filte r: action data (both URI and data type) category The extras and flags play no pa rt in resolving which component receives an intent. Intent filters To inform the system which implicit intents they can handle, activities, service s, and broadcast receivers can have one or more intent filters. Each filter desc ribes a capability of the component, a set of intents that the component is will ing to receive. It, in effect, filters in intents of a desired type, while filte ring out unwanted intents but only unwanted implicit intents (those that don't n ame a target class). An explicit intent is always delivered to its target, no ma tter what it contains; the filter is not consulted. But an implicit intent is de livered to a component only if it can pass through one of the component's filter s. A component has separate filters for each job it can do, each face it can pre sent to the user. For example, the principal activity of the sample NotePad appl ication has three filters one for starting up with a blank slate, another for st arting with an assigned directory of notes that the user can view, edit, or sele ct from, and a third for finding a particular note without an initial specificat ion of its directory. An intent filter is an instance of the IntentFilter class. However, since the Android system must know about the capabilities of a compone nt before it can launch that component, intent filters are generally not set up in Java code, but in the application's manifest file (AndroidManifest.xml) as <i ntent-filter> elements. (The one exception would be filters for broadcast receiv ers that are registered dynamically by calling Context.registerReceiver(); they are directly created as IntentFilter objects.) A filter has fields that parallel the action, data, and category fields of an Intent object. An implicit intent i s tested against the filter in all three areas. To be delivered to the component that owns the filter, it must pass all three tests. If it fails even one of the m, the Android system won't deliver it to the component at least not on the basi s of that filter. However, since a component can have multiple intent filters, a n intent that does not pass through one of a component's filters might make it t hrough on another. Each of the three tests is described in detail below: Action test An <intent-filter> element in the manifest file lists actions as <action> s ubelements. For example: Filters and security An intent filter cannot be relied on for security. While it opens a component to receiving only certain kinds of implicit intents, it does nothing to prevent explicit intents from targeting the component. Even though a filter restricts the intents a component will be asked to handle to certain acti ons and data sources, someone could always put together an explicit intent with a different action and data source, and name the component as the target. <intent-filter . . . > <action android:name="com.example.project.SHOW_CURRENT" /

> <action android:name="com.example.project.SHOW_RECENT" /> <action android:name ="com.example.project.SHOW_PENDING" /> http://developer.android.com/guide/topics/intents/intents-filters.html Page 4 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 <action android:name="com.example.project.SHOW_PENDING" /> . . . </intent-filter > As the example shows, while an Intent object names just a single action, a fil ter may list more than one. The list cannot be empty; a filter must contain at l east one <action> element, or it will block all intents. To pass this test, the action specified in the Intent object must match one of the actions listed in th e filter. If the object or the filter does not specify an action, the results ar e as follows: If the filter fails to list any actions, there is nothing for an i ntent to match, so all intents fail the test. No intents can get through the fil ter. On the other hand, an Intent object that doesn't specify an action automati cally passes the test as long as the filter contains at least one action. Catego ry test An <intent-filter> element also lists categories as subelements. For exa mple: <intent-filter . . . > <category android:name="android.intent.category.DEF AULT" /> <category android:name="android.intent.category.BROWSABLE" /> . . . </i ntent-filter> Note that the constants described earlier for actions and categori es are not used in the manifest file. The full string values are used instead. F or instance, the "android.intent.category.BROWSABLE" string in the example above corresponds to the CATEGORY_BROWSABLE constant mentioned earlier in this docume nt. Similarly, the string "android.intent.action.EDIT" corresponds to the ACTION _EDIT constant. For an intent to pass the category test, every category in the I ntent object must match a category in the filter. The filter can list additional categories, but it cannot omit any that are in the intent. In principle, theref ore, an Intent object with no categories should always pass this test, regardles s of what's in the filter. That's mostly true. However, with one exception, Andr oid treats all implicit intents passed to startActivity() as if they contained a t least one category: "android.intent.category.DEFAULT" (the CATEGORY_DEFAULT co nstant). Therefore, activities that are willing to receive implicit intents must include "android.intent.category.DEFAULT" in their intent filters. (Filters wit h "android.intent.action.MAIN" and "android.intent.category.LAUNCHER" settings a re the exception. They mark activities that begin new tasks and that are represe nted on the launcher screen. They can include "android.intent.category.DEFAULT" in the list of categories, but don't need to.) See Using intent matching, later, for more on these filters.) Data test Like the action and categories, the data specification for an intent filter is contained in a subelement. And, as in thos e cases, the subelement can appear multiple times, or not at all. For example: < intent-filter . . . > <data android:type="video/mpeg" android:scheme="http" . . . /> <data android:type="audio/mpeg" android:scheme="http" . . . /> . . . </inte nt-filter> Each <data> element can specify a URI and a data type (MIME media typ e). There are separate attributes scheme, host, port, and path for each part of the URI: scheme://host:port/path For example, in the following URI, http://developer.android.com/guide/topics/intents/intents-filters.html Page 5 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 content://com.example.project:200/folder/subfolder/etc the scheme is "content", the host is "com.example.project", the port is "200", and the path is "folder/su bfolder/etc". The host and port together constitute the URI authority; if a host is not specified, the port is ignored. Each of these attributes is optional, bu t they are not independent of each other: For an authority to be meaningful, a s cheme must also be specified. For a path to be meaningful, both a scheme and an authority must be specified. When the URI in an Intent object is compared to a U RI specification in a filter, it's compared only to the parts of the URI actuall y mentioned in the filter. For example, if a filter specifies only a scheme, all URIs with that scheme match the filter. If a filter specifies a scheme and an a uthority but no path, all URIs with the same scheme and authority match, regardl ess of their paths. If a filter specifies a scheme, an authority, and a path, on ly URIs with the same scheme, authority, and path match. However, a path specifi cation in the filter can contain wildcards to require only a partial match of th e path. The type attribute of a <data> element specifies the MIME type of the da ta. It's more common in filters than a URI. Both the Intent object and the filte r can use a "*" wildcard for the subtype field for example, "text/*" or "audio/* " indicating any subtype matches. The data test compares both the URI and the da ta type in the Intent object to a URI and data type specified in the filter. The rules are as follows: a. An Intent object that contains neither a URI nor a dat a type passes the test only if the filter likewise does not specify any URIs or data types. b. An Intent object that contains a URI but no data type (and a type cannot be inferred from the URI) passes the test only if its URI matches a URI in the filter and the filter likewise does not specify a type. This will be the case only for URIs like mailto: and tel: that do not refer to actual data. c. An Intent object that contains a data type but not a URI passes the test only if t he filter lists the same data type and similarly does not specify a URI. d. An I ntent object that contains both a URI and a data type (or a data type can be inf erred from the URI) passes the data type part of the test only if its type match es a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a content: or file: URI and the fi lter does not specify a URI. In other words, a component is presumed to support content: and file: data if its filter lists only a data type. If an intent can p ass through the filters of more than one activity or service, the user may be as ked which component to activate. An exception is raised if no target can be foun d. Common cases The last rule shown above for the data test, rule (d), reflects the expectation that components are able to get local data from a file or content provider. Ther efore, their filters can list just a data type and do not need to explicitly nam e the content: and file: schemes. This is a typical case. A <data> element like the following, for example, tells Android that the component can get image data from a content provider and display it: <data android:type="image/*" /> Since mo st available data is dispensed by content providers, filters that specify a data type but not a URI are perhaps the most common. Another common configuration is filters with a scheme and a data type. For example, a <data> element like the f ollowing tells Android that the component can get video data from the network an d display it: http://developer.android.com/guide/topics/intents/intents-filters.html Page 6 of 7

Intents and Intent Filters | Android Developers 29.04.09 0:40 <data android:scheme="http" android:type="video/*" /> Consider, for example, wha t the browser application does when the user follows a link on a web page. It fi rst tries to display the data (as it could if the link was to an HTML page). If it can't display the data, it puts together an implicit intent with the scheme a nd data type and tries to start an activity that can do the job. If there are no takers, it asks the download manager to download the data. That puts it under t he control of a content provider, so a potentially larger pool of activities (th ose with filters that just name a data type) can respond. Most applications also have a way to start fresh, without a reference to any particular data. Activiti es that can initiate applications have filters with "android.intent.action.MAIN" specified as the action. If they are to be represented in the application launc her, they also specify the "android.intent.category.LAUNCHER" category: <intentfilter . . . > <action android:name="code android.intent.action.MAIN" /> <catego ry android:name="code android.intent.category.LAUNCHER" /> </intent-filter> Using intent matching Intents are matched against intent filters not only to discover a target compone nt to activate, but also to discover something about the set of components on th e device. For example, the Android system populates the application launcher, th e top-level screen that shows the applications that are available for the user t o launch, by finding all the activities with intent filters that specify the "an droid.intent.action.MAIN" action and "android.intent.category.LAUNCHER" category (as illustrated in the previous section). It then displays the icons and labels of those activities in the launcher. Similarly, it discovers the home screen by looking for the activity with "android.intent.category.HOME" in its filter. You r application can use intent matching is a similar way. The PackageManager has a set of query...() methods that return all components that can accept a particul ar intent, and a similar series of resolve...() methods that determine the best component to respond to an intent. For example, queryIntentActivities() returns a list of all activities that can perform the intent passed as an argument, and queryIntentServices() returns a similar list of services. Neither method activat es the components; they just list the ones that can respond. There's a similar m ethod, queryBroadcastReceivers(), for broadcast receivers. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/intents/intents-filters.html Page 7 of 7

Data Storage | Android Developers 29.04.09 0:41 Data Storage A typical desktop operating system provides a common file system that any applic ation can use to store files that can be read by other applications (perhaps wit h some access control settings). Android uses a different system: On Android, al l application data (including files) are private to that application. However, A ndroid also provides a standard way for an application to expose its private dat a to other applications through content providers. A content provider is an opti onal component of an application that exposes read/write access to the applicati on's data, subject to whatever restrictions it might impose. Content providers i mplement a standard syntax for requesting and modifying data, and a standard mec hanism for reading the returned data. Android supplies a number of content provi ders for standard data types, such as image, audio, and video files and personal contact information. For more information on using content providers, see a sep arate document, Content Providers. Whether or not you want to export your applic ation's data to others, you need a way to store it. Android provides the followi ng four mechanisms for storing and retrieving data: Preferences, Files, Database s, and Network. Preferences Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types. It is typically used to store application preferences, suc h as a default greeting or a text font to be loaded whenever the application is started. Call Context.getSharedPreferences() to read and write values. Assign a name to your set of preferences if you want to share them with other components in the same application, or use Activity.getPreferences() with no name to keep t hem private to the calling activity. You cannot share preferences across applica tions (except by using a content provider). Here is an example of setting user p references for silent keypress mode for a calculator: import android.app.Activit y; import android.content.SharedPreferences; public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; . . . @Override protect ed void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferen ces SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean si lent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); // Save user preferences. We need an Editor object to // make changes. All objects are from android.context.C ontext SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); http://developer.android.com/guide/topics/data/data-storage.html Page 1 of 3

Data Storage | Android Developers 29.04.09 0:41 SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferen ces.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode ); // Don't forget to commit your edits!!! editor.commit(); } } Files You can store files directly on the mobile device or on a removable storage medi um. By default, other applications cannot access these files. To read data from a file, call Context.openFileInput() and pass it the local name and path of the file. It returns a standard Java FileInputStream object. To write to a file, cal l Context.openFileOutput() with the name and path. It returns a FileOutputStream object. Calling these methods with name and path strings from another applicati on will not work; you can only access local files. If you have a static file to package with your application at compile time, you can save the file in your pro ject in res/raw/myDataFile, and then open it with Resources.openRawResource (R.r aw.myDataFile). It returns an InputStream object that you can use to read from t he file. Databases The Android API contains support for creating and using SQLite databases. Each d atabase is private to the application that creates it. The SQLiteDatabase object represents a database and has methods for interacting with it making queries an d managing the data. To create the database, call SQLiteDatabase.create() and al so subclass SQLiteOpenHelper. As part of its support for the SQLite database sys tem, Android exposes database management functions that let you store complex co llections of data wrapped into useful objects. For example, Android defines a da ta type for contact information; it consists of many fields including a first an d last name (strings), an address and phone numbers (also strings), a photo (bit map image), and much other information describing a person. Android ships with t he sqlite3 database tool, which enables you to browse table contents, run SQL co mmands, and perform other useful functions on SQLite databases. See Examine data bases (sqlite3) to learn how to run this program. All databases, SQLite and othe rs, are stored on the device in /data/data/package_name/databases. Discussion of how many tables to create, what fields they contain, and how they are linked, i s beyond the scope of this note, but Android does not impose any limitations bey ond the standard SQLite concepts. We do recommend including an autoincrement val ue key field that can be used as a unique ID to quickly find a record. This is n ot required for private data, but if you implement a content provider, you must include such a unique ID field. See the Content Providers document for more info rmation on this field and the NotePadProvider class in the NotePad sample code f or an example of creating and populating a new database. Any databases you creat e will be accessible by name to any other class in the application, but not outs ide the application. Network You can also use the network to store and retrieve data (when it's available). T o do network operations, use the classes in the following packages: http://developer.android.com/guide/topics/data/data-storage.html Page 2 of 3

Data Storage | Android Developers 29.04.09 0:41 java.net.* android.net.* Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/data/data-storage.html Page 3 of 3

Content Providers | Android Developers 29.04.09 0:41 Content Providers Content providers store and retrieve data and make it accessible to all applicat ions. They're the only way to share data across applications; there's no common storage area that all Android packages can access. Android ships with a number o f content providers for common data types (audio, video, images, personal contac t information, and so on). You can see some of them listed in the android.provid er package. You can query these providers for the data they contain (although, f or some, you must acquire the proper permission to read the data). If you want t o make your own data public, you have two options: You can create your own conte nt provider (a ContentProvider subclass) or you can add the data to an existing provider if there's one that controls the same type of data and you have permiss ion to write to it. This document is an introduction to using content providers. After a brief discussion of the fundamentals, it explores how to query a conten t provider, how to modify data controlled by a provider, and how to create a con tent provider of your own. Content Provider Basics How a content provider actually stores its data under the covers is up to its de signer. But all content providers implement a common interface for querying the provider and returning results as well as for adding, altering, and deleting dat a. It's an interface that clients use indirectly, most generally through Content Resolver objects. You get a ContentResolver by calling getContentResolver() from within the implementation of an Activity or other application component: Conten tResolver cr = getContentResolver(); You can then use the ContentResolver's meth ods to interact with whatever content providers you're interested in. When a que ry is initiated, the Android system identifies the content provider that's the t arget of the query and makes sure that it is up and running. The system instanti ates all ContentProvider objects; you never need to do it on your own. In fact, you never deal directly with ContentProvider objects at all. Typically, there's just a single instance of each type of ContentProvider. But it can communicate w ith multiple ContentResolver objects in different applications and processes. Th e interaction between processes is handled by the ContentResolver and ContentPro vider classes. The data model Content providers expose their data as a simple table on a database model, where each row is a record and each column is data of a particular type and meaning. For example, information about people and their phone numbers might be exposed a s follows: _ID 13 44 NUMBER (425) 555 6677 (212) 555-1234 NUMBER_KEY 425 555 667 7 212 555 1234 LABEL Kirkland office NY apartment NAME Bully Pulpit Alan Vain TY PE TYPE_WORK TYPE_HOME http://developer.android.com/guide/topics/providers/content-providers.html Page 1 of 10

Content Providers | Android Developers 29.04.09 0:41 45 53 (212) 555-6657 201.555.4433 212 555 6657 201 555 4433 Downtown office Love Nest Alan Vain Rex Cars TYPE_MOBILE TYPE_HOME Every record includes a numeric _ID field that uniquely identifies the record wi thin the table. IDs can be used to match records in related tables for example, to find a person's phone number in one table and pictures of that person in anot her. A query returns a Cursor object that can move from record to record and col umn to column to read the contents of each field. It has specialized methods for reading each type of data. So, to read a field, you must know what type of data the field contains. (There's more on query results and Cursor objects later.) URIs Each content provider exposes a public URI (wrapped as a Uri object) that unique ly identifies its data set. A content provider that controls multiple data sets (multiple tables) exposes a separate URI for each one. All URIs for providers be gin with the string "content://". The content: scheme identifies the data as bei ng controlled by a content provider. If you're defining a content provider, it's a good idea to also define a constant for its URI, to simplify client code and make future updates cleaner. Android defines CONTENT_URI constants for all the p roviders that come with the platform. For example, the URI for the table that ma tches phone numbers to people and the URI for the table that holds pictures of p eople (both controlled by the Contacts content provider) are: android.provider.C ontacts.Phones.CONTENT_URI android.provider.Contacts.Photos.CONTENT_URI Similarl y, the URIs for the table of recent phone calls and the table of calendar entrie s are: android.provider.CallLog.Calls.CONTENT_URI android.provider.Calendar.CONT ENT_URI The URI constant is used in all interactions with the content provider. Every ContentResolver method takes the URI as its first argument. It's what iden tifies which provider the ContentResolver should talk to and which table of the provider is being targeted. Querying a Content Provider You need three pieces of information to query a content provider: The URI that i dentifies the provider The names of the data fields you want to receive The data types for those fields If you're querying a particular record, you also need th e ID for that record. Making the query To query a content provider, you can use either the ContentResolver.query() meth od or the Activity.managedQuery() method. Both methods take the same set of argu ments, and both return a Cursor object. However, managedQuery() causes the activ ity to manage the life cycle of the Cursor. A managed Cursor handles all of the niceties, such as unloading itself when the activity pauses, and requerying itse lf when the activity restarts. You can ask an Activity to begin managing an unma naged Cursor object for you by calling Activity.startManagingCursor(). http://developer.android.com/guide/topics/providers/content-providers.html

Page 2 of 10

Content Providers | Android Developers 29.04.09 0:41 The first argument to either query() or managedQuery() is the provider URI the C ONTENT_URI constant that identifies a particular ContentProvider and data set (s ee URIs earlier). To restrict a query to just one record, you can append the _ID value for that record to the URI that is, place a string matching the ID as the last segment of the path part of the URI. For example, if the ID is 23, the URI would be: content://. . . ./23 There are some helper methods, particularly Cont entUris.withAppendedId() and Uri.withAppendedPath(), that make it easy to append an ID to a URI. Both are static methods that return a Uri object with the ID ad ded. So, for example, if you were looking for record 23 in the database of peopl e contacts, you might construct a query as follows: import import import import android.provider.Contacts.People; android.content.ContentUris; android.net.Uri; android.database.Cursor; // Use the ContentUris method to produce the base URI for the contact with _ID = = 23. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23); // Alte rnatively, use the Uri method to produce the base URI. // It takes a string rath er than an integer. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23" ); // Then query for this specific record: Cursor cur = managedQuery(myPerson, n ull, null, null, null); The other arguments to the query() and managedQuery() me thods delimit the query in more detail. They are: The names of the data columns that should be returned. A null value returns all columns. Otherwise, only colum ns that are listed by name are returned. All the content providers that come wit h the platform define constants for their columns. For example, the android.prov ider.Contacts.Phones class defines constants for the names of the columns in the phone table illustrated earlier _ID, NUMBER, NUMBER_KEY, NAME, and so on. A fil ter detailing which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). A null value returns all rows (unless the URI limits the quer y to a single record). Selection arguments. A sorting order for the rows that ar e returned, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns the records in the default order for the table, which may be unordered. Let's look at an example query to retrieve a list of contact names and their primary phone numbers: import android.provider.Contacts.People; impor t android.database.Cursor; // Form an array specifying which columns to return. String[] projection = new String[] { People._ID, People._COUNT, People.NAME, Peo ple.NUMBER }; // Get the base URI for the People table in the Contacts content p rovider. Uri contacts = People.CONTENT_URI; // Make the query. Cursor managedCur sor = managedQuery(contacts, projection, // Which columns to return null, // Whi ch rows to return (all rows) http://developer.android.com/guide/topics/providers/content-providers.html Page 3 of 10

Content Providers | Android Developers 29.04.09 0:41 null, // Which rows to return (all rows) null, // Selection arguments (none) // Put the results in ascending order by name People.NAME + " ASC"); This query ret rieves data from the People table of the Contacts content provider. It gets the name, primary phone number, and unique record ID for each contact. It also repor ts the number of records that are returned as the _COUNT field of each record. T he constants for the names of the columns are defined in various interfaces _ID and _COUNT in BaseColumns, NAME in PeopleColumns, and NUMBER in PhoneColumns. Th e Contacts.People class implements each of these interfaces, which is why the co de example above could refer to them using just the class name. What a query returns A query returns a set of zero or more database records. The names of the columns , their default order, and their data types are specific to each content provide r. But every provider has an _ID column, which holds a unique numeric ID for eac h record. Every provider can also report the number of records returned as the _ COUNT column; its value is the same for all rows. Here is an example result set for the query in the previous section: _ID 44 13 53 _COUNT 3 3 3 NAME Alan Vain Bully Pulpit Rex Cars NUMBER 212 555 1234 425 555 6677 201 555 4433 The retrieved data is exposed by a Cursor object that can be used to iterate bac kward or forward through the result set. You can use this object only to read th e data. To add, modify, or delete data, you must use a ContentResolver object. Reading retrieved data The Cursor object returned by a query provides access to a recordset of results. If you have queried for a specific record by ID, this set will contain only one value. Otherwise, it can contain multiple values. (If there are no matches, it can also be empty.) You can read data from specific fields in the record, but yo u must know the data type of the field, because the Cursor object has a separate method for reading each type of data such as getString(), getInt(), and getFloa t(). (However, for most types, if you call the method for reading strings, the C ursor object will give you the String representation of the data.) The Cursor le ts you request the column name from the index of the column, or the index number from the column name. The following snippet demonstrates reading names and phon e numbers from the query illustrated earlier: import android.provider.Contacts.P eople; private void getColumnData(Cursor cur){ if (cur.moveToFirst()) { String n ame; String phoneNumber; int nameColumn = cur.getColumnIndex(People.NAME); int p honeColumn = cur.getColumnIndex(People.NUMBER); String imagePath; do { // Get th e field values name = cur.getString(nameColumn); phoneNumber = cur.getString(pho neColumn); http://developer.android.com/guide/topics/providers/content-providers.html Page 4 of 10

Content Providers | Android Developers 29.04.09 0:41 phoneNumber = cur.getString(phoneColumn); // Do something with the values. ... } while (cur.moveToNext()); } } If a query can return binary data, such as an ima ge or sound, the data may be directly entered in the table or the table entry fo r that data may be a string specifying a content: URI that you can use to get th e data. In general, smaller amounts of data (say, from 20 to 50K or less) are mo st often directly entered in the table and can be read by calling Cursor.getBlob (). It returns a byte array. If the table entry is a content: URI, you should ne ver try to open and read the file directly (for one thing, permissions problems can make this fail). Instead, you should call ContentResolver.openInputStream() to get an InputStream object that you can use to read the data. Modifying Data Data kept by a content provider can be modified by: Adding new records Adding ne w values to existing records Batch updating existing records Deleting records Al l data modification is accomplished using ContentResolver methods. Some content providers require a more restrictive permission for writing data than they do fo r reading it. If you don't have permission to write to a content provider, the C ontentResolver methods will fail. Adding records To add a new record to a content provider, first set up a map of key-value pairs in a ContentValues object, where each key matches the name of a column in the c ontent provider and the value is the desired value for the new record in that co lumn. Then call ContentResolver.insert() and pass it the URI of the provider and the ContentValues map. This method returns the full URI of the new record that is, the provider's URI with the appended ID for the new record. You can then use this URI to query and get a Cursor over the new record, and to further modify t he record. Here's an example: import android.provider.Contacts.People; import an droid.content.ContentResolver; import android.content.ContentValues; ContentValu es values = new ContentValues(); // Add Abraham Lincoln to contacts and make him a favorite. values.put(People.NAME, "Abraham Lincoln"); // 1 = the new contact is added to favorites // 0 = the new contact is not added to favorites values.pu t(People.STARRED, 1); Uri uri = getContentResolver().insert(People.CONTENT_URI, values); Adding new values http://developer.android.com/guide/topics/providers/content-providers.html Page 5 of 10

Content Providers | Android Developers 29.04.09 0:41 Once a record exists, you can add new information to it or modify existing infor mation. For example, the next step in the example above would be to add contact information like a phone number or an IM or e-mail address to the new entry. The best way to add to a record in the Contacts database is to append the name of t he table where the new data goes to the URI for the record, then use the amended URI to add the new data values. Each Contacts table exposes a name for this pur pose as a CONTENT_DIRECTORY constant. The following code continues the previous example by adding a phone number and e-mail address for the record just created: Uri phoneUri = null; Uri emailUri = null; // Add a phone number for Abraham Lin coln. Begin with the URI for // the new record just returned by insert(); it end s with the _ID // of the new record, so we don't have to add the ID ourselves. / / Then append the designation for the phone table to this URI, // and use the re sulting URI to insert the phone number. phoneUri = Uri.withAppendedPath(uri, Peo ple.Phones.CONTENT_DIRECTORY); values.clear(); values.put(People.Phones.TYPE, Pe ople.Phones.TYPE_MOBILE); values.put(People.Phones.NUMBER, "1233214567"); getCon tentResolver().insert(phoneUri, values); // Now add an email address in the same way. emailUri = Uri.withAppendedPath(uri, People.ContactMethods.CONTENT_DIRECTO RY); values.clear(); // ContactMethods.KIND is used to distinguish different kin ds of // contact methods, such as email, IM, etc. values.put(People.ContactMetho ds.KIND, Contacts.KIND_EMAIL); values.put(People.ContactMethods.DATA, "test@exam ple.com"); values.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_HOM E); getContentResolver().insert(emailUri, values); You can place small amounts o f binary data into a table by calling the version of ContentValues.put() that ta kes a byte array. That would work for a small icon-like image or a short audio c lip, for example. However, if you have a large amount of binary data to add, suc h as a photograph or a complete song, put a content: URI for the data in the tab le and call ContentResolver.openOutputStream() with the file's URI. (That causes the content provider to store the data in a file and record the file path in a hidden field of the record.) In this regard, the MediaStore content provider, th e main provider that dispenses image, audio, and video data, employs a special c onvention: The same URI that is used with query() or managedQuery() to get metai nformation about the binary data (such as, the caption of a photograph or the da te it was taken) is used with openInputStream() to get the data itself. Similarl y, the same URI that is used with insert() to put metainformation into a MediaSt ore record is used with openOutputStream() to place the binary data there. The f ollowing code snippet illustrates this convention: import android.provider.Media Store.Images.Media; import android.content.ContentValues; import java.io.OutputS tream; // Save the name and description of an image in a ContentValues map. Cont entValues values = new ContentValues(3); values.put(Media.DISPLAY_NAME, "road_tr ip_1"); values.put(Media.DESCRIPTION, "Day 1, trip to Los Angeles"); values.put( Media.MIME_TYPE, "image/jpeg"); // Add a new record without the bitmap, but with the values just set. // insert() returns the URI of the new record. Uri uri = g etContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); // Now get a han dle to the file for that record, and save the data into it. http://developer.android.com/guide/topics/providers/content-providers.html Page 6 of 10

Content Providers | Android Developers 29.04.09 0:41 // Now get a handle to the file for that record, and save the data into it. // H ere, sourceBitmap is a Bitmap object representing the file to save to the databa se. try { OutputStream outStream = getContentResolver().openOutputStream(uri); s ourceBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream); outStream.close (); } catch (Exception e) { Log.e(TAG, "exception while writing image", e); } Batch updating records To batch update a group of records (for example, to change "NY" to "New York" in all fields), call the ContentResolver.update() method with the columns and valu es to change. Deleting a record To delete a single record, call {ContentResolver.delete() with the URI of a spec ific row. To delete multiple rows, call ContentResolver.delete() with the URI of the type of record to delete (for example, android.provider.Contacts.People.CON TENT_URI) and an SQL WHERE clause defining which rows to delete. (Caution: Be su re to include a valid WHERE clause if you're deleting a general type, or you ris k deleting more records than you intended!). Creating a Content Provider To create a content provider, you must: Set up a system for storing the data. Mo st content providers store their data using Android's file storage methods or SQ Lite databases, but you can store your data any way you want. Android provides t he SQLiteOpenHelper class to help you create a database and SQLiteDatabase to ma nage it. Extend the ContentProvider class to provide access to the data. Declare the content provider in the manifest file for your application (AndroidManifest .xml). The following sections have notes on the last two of these tasks. Extending the ContentProvider class You define a ContentProvider subclass to expose your data to others using the co nventions expected by ContentResolver and Cursor objects. Principally, this mean s implementing six abstract methods declared in the ContentProvider class: query () insert() update() delete() getType() onCreate() The query() method must retur n a Cursor object that can iterate over the requested data. Cursor itself is an interface, but Android provides some ready-made Cursor objects that you can use. For example, SQLiteCursor can iterate over data stored in an SQLite database. Y ou get the Cursor object by calling any of the SQLiteDatabase class's query() me thods. There are other Cursor implementations such as MatrixCursor for data not stored in a database. http://developer.android.com/guide/topics/providers/content-providers.html Page 7 of 10

Content Providers | Android Developers 29.04.09 0:41 Because these ContentProvider methods can be called from various ContentResolver objects in different processes and threads, they must be implemented in a threa d-safe manner. As a courtesy, you might also want to call ContentResolver.notify Change() to notify listeners when there are modifications to the data. Beyond de fining the subclass itself, there are other steps you should take to simplify th e work of clients and make the class more accessible: Define a public static fin al Uri named CONTENT_URI. This is the string that represents the full content: U RI that your content provider handles. You must define a unique string for this value. The best solution is to use the fully-qualified class name of the content provider (made lowercase). So, for example, the URI for a TransportationProvide r class could be defined as follows: public static final Uri CONTENT_URI = Uri.p arse("content://com.example.codelab.transporationprovider"); If the provider has subtables, also define CONTENT_URI constants for each of the subtables. These U RIs should all have the same authority (since that identifies the content provid er), and be distinguished only by their paths. For example: content://com.exampl e.codelab.transporationprovider/train content://com.example.codelab.transporatio nprovider/air/domestic content://com.example.codelab.transporationprovider/air/i nternational For an overview of content: URIs, see the Content URI Summary at th e end of this document. Define the column names that the content provider will r eturn to clients. If you are using an underlying database, these column names ar e typically identical to the SQL database column names they represent. Also defi ne public static String constants that clients can use to specify the columns in queries and other instructions. Be sure to include an integer column named "_id " (with the constant _ID) for the IDs of the records. You should have this field whether or not you have another field (such as a URL) that is also unique among all records. If you're using the SQLite database, the _ID field should be the f ollowing type: INTEGER PRIMARY KEY AUTOINCREMENT The AUTOINCREMENT descriptor is optional. But without it, SQLite increments an ID counter field to the next num ber above the largest existing number in the column. If you delete the last row, the next row added will have the same ID as the deleted row. AUTOINCREMENT avoi ds this by having SQLite increment to the next largest value whether deleted or not. Carefully document the data type of each column. Clients need this informat ion to read the data. If you are handling a new data type, you must define a new MIME type to return in your implementation of ContentProvider.getType(). The ty pe depends in part on whether or not the content: URI submitted to getType() lim its the request to a specific record. There's one form of the MIME type for a si ngle record and another for multiple records. Use the Uri methods to help determ ine what is being requested. Here is the general format for each type: For a sin gle record: vnd.android.cursor.item/vnd.yourcompanyname.contenttype For example, a request for train record 122, like this URI, content://com.exampl e.transportationprovider/trains/122 might return this MIME type: vnd.android.cur sor.item/vnd.example.rail For multiple records: vnd.android.cursor.dir/vnd.yourc ompanyname.contenttype For example, a request for all train records, like the following URI, content:// com.example.transportationprovider/trains http://developer.android.com/guide/topics/providers/content-providers.html Page 8 of 10

Content Providers | Android Developers 29.04.09 0:41 might return this MIME type: vnd.android.cursor.dir/vnd.example.rail If you are exposing byte data that's too big to put in the table itself such as a large bit map file the field that exposes the data to clients should actually contain a co ntent: URI string. This is the field that gives clients access to the data file. The record should also have another field, named "_data" that lists the exact f ile path on the device for that file. This field is not intended to be read by t he client, but by the ContentResolver. The client will call ContentResolver.open InputStream() on the user-facing field holding the URI for the item. The Content Resolver will request the "_data" field for that record, and because it has high er permissions than a client, it should be able to access that file directly and return a read wrapper for the file to the client. For an example of a private c ontent provider implementation, see the NodePadProvider class in the Notepad sam ple application that ships with the SDK. Declaring the content provider To let the Android system know about the content provider you've developed, decl are it with a <provider> element in the application's AndroidManifest.xml file. Content providers that are not declared in the manifest are not visible to the A ndroid system The name attribute is the fully qualified name of the ContentProvi der subclass. The authorities attribute is the authority part of the content: UR I that identifies the provider. For example if the ContentProvider subclass is A utoInfoProvider, the <provider> element might look like this: <provider name="co m.example.autos.AutoInfoProvider" authorities="com.example.autos.autoinfoprovide r" . . . /> </provider> Note that the authorities attribute omits the path part of a content: URI. For example, if AutoInfoProvider controlled subtables for dif ferent types of autos or different manufacturers, content://com.example.autos.au toinfoprovider/honda content://com.example.autos.autoinfoprovider/gm/compact con tent://com.example.autos.autoinfoprovider/gm/suv those paths would not be declar ed in the manifest. The authority is what identifies the provider, not the path; your provider can interpret the path part of the URI in any way you choose. Oth er <provider> attributes can set permissions to read and write data, provide for an icon and text that can be displayed to users, enable and disable the provide r, and so on. Set the multiprocess attribute to "true" if data does not need to be synchronized between multiple running versions of the content provider. This permits an instance of the provider to be created in each client process, elimin ating the need to perform IPC. Content URI Summary Here is a recap of the important parts of a content URI: http://developer.android.com/guide/topics/providers/content-providers.html Page 9 of 10

Content Providers | Android Developers 29.04.09 0:41 A. Standard prefix indicating that the data is controlled by a content provider. It's never modified. B. The authority part of the URI; it identifies the conten t provider. For third-party applications, this should be a fullyqualified class name (reduced to lowercase) to ensure uniqueness. The authority is declared in t he <provider> element's authorities attribute: <provider name=".TransportationPr ovider" authorities="com.example.transportationprovider" . . . > C. The path tha t the content provider uses to determine what kind of data is being requested. T his can be zero or more segments long. If the content provider exposes only one type of data (only trains, for example), it can be absent. If the provider expos es several types, including subtypes, it can be several segments long for exampl e, "land/bus", "land/train", "sea/ship", and "sea/submarine" to give four possib ilities. D. The ID of the specific record being requested, if any. This is the _ ID value of the requested record. If the request is not limited to a single reco rd, this segment and the trailing slash are omitted: content://com.example.trans portationprovider/trains Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/providers/content-providers.html Page 10 of 10

Security and Permissions | Android Developers 29.04.09 0:41 Security and Permissions Android is a multi-process system, in which each application (and parts of the s ystem) runs in its own process. Most security between applications and the syste m is enforced at the process level through standard Linux facilities, such as us er and group IDs that are assigned to applications. Additional finer-grained sec urity features are provided through a "permission" mechanism that enforces restr ictions on the specific operations that a particular process can perform, and pe r-URI permissions for granting ad-hoc access to specific pieces of data. Security Architecture A central design point of the Android security architecture is that no applicati on, by default, has permission to perform any operations that would adversely im pact other applications, the operating system, or the user. This includes readin g or writing the user's private data (such as contacts or e-mails), reading or w riting another application's files, performing network access, keeping the devic e awake, etc. An application's process is a secure sandbox. It can't disrupt oth er applications, except by explicitly declaring the permissions it needs for add itional capabilities not provided by the basic sandbox. These permissions it req uests can be handled by the operating in various ways, typically by automaticall y allowing or disallowing based on certificates or by prompting the user. The pe rmissions required by an application are declared statically in that application , so they can be known up-front at install time and will not change after that. Application Signing All Android applications (.apk files) must be signed with a certificate whose pr ivate key is held by their developer. This certificate identifies the author of the application. The certificate does not need to be signed by a certificate aut hority: it is perfectly allowable, and typical, for Android applications to use self-signed certificates. The certificate is used only to establish trust relati onships between applications, not for wholesale control over whether an applicat ion can be installed. The most significant ways that signatures impact security is by determining who can access signature-based permissions and who can share u ser IDs. User IDs and File Access Each Android package (.apk) file installed on the device is given its own unique Linux user ID, creating a sandbox for it and preventing it from touching other applications (or other applications from touching it). This user ID is assigned to it when the application is installed on the device, and remains constant for the duration of its life on that device. Because security enforcement happens at the process level, the code of any two packages can not normally run in the sam e process, since they need to run as different Linux users. You can use the shar edUserId attribute in the AndroidManifest.xml's manifest tag of each package to have them assigned the same user ID. By doing this, for purposes of security the two packages are then treated as being the same application, with the same user ID and file permissions. Note that in order to retain security, only two applic ations signed with the same signature (and requesting the same sharedUserId) wil l be given the same user ID. Any data stored by an application will be assigned that application's user ID, and not normally accessible to other packages. When creating a new file with getSharedPreferences(String, int), openFileOutput(Strin g, int), or http://developer.android.com/guide/topics/security/security.html Page 1 of 5

Security and Permissions | Android Developers 29.04.09 0:41 openOrCreateDatabase(String, int, SQLiteDatabase.CursorFactory), you can use the MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE flags to allow any other packag e to read/write the file. When setting these flags, the file is still owned by y our application, but its global read and/or write permissions have been set appr opriately so any other application can see it. Using Permissions A basic Android application has no permissions associated with it, meaning it ca n not do anything that would adversely impact the user experience or any data on the device. To make use of protected features of the device, you must include i n your AndroidManifest.xml one or more <uses-permission> tags declaring the perm issions that your application needs. For example, an application that needs to m onitor incoming SMS messages would specify: <manifest xmlns:android="http://sche mas.android.com/apk/res/android" package="com.android.app.myapp" > <uses-permiss ion android:name="android.permission.RECEIVE_SMS" /> </manifest> At application install time, permissions requested by the application are granted to it by the package installer, based on checks against the signatures of the applications de claring those permissions and/or interaction with the user. No checks with the u ser are done while an application is running: it either was granted a particular permission when installed, and can use that feature as desired, or the permissi on was not granted and any attempt to use the feature will fail without promptin g the user. Often times a permission failure will result in a SecurityException being thrown back to the application. However, this is not guaranteed to occur e verywhere. For example, the sendBroadcast(Intent) method checks permissions as d ata is being delivered to each receiver, after the method call has returned, so you will not receive an exception if there are permission failures. In almost al l cases, however, a permission failure will be printed to the system log. The pe rmissions provided by the Android system can be found at Manifest.permission. An y application may also define and enforce its own permissions, so this is not a comprehensive list of all possible permissions. A particular permission may be e nforced at a number of places during your program's operation: At the time of a call into the system, to prevent an application from executing certain functions . When starting an activity, to prevent applications from launching activities o f other applications. Both sending and receiving broadcasts, to control who can receive your broadcast or who can send a broadcast to you. When accessing and op erating on a content provider. Binding or starting a service. Declaring and Enforcing Permissions To enforce your own permissions, you must first declare them in your AndroidMani fest.xml using one or more <permission> tags. For example, an application that w ants to control who can start one of its activities could declare a permission f or this operation as follows: http://developer.android.com/guide/topics/security/security.html Page 2 of 5

Security and Permissions | Android Developers 29.04.09 0:41 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="co m.me.app.myapp" > <permission android:name="com.me.app.myapp.permission.DEADLY_A CTIVITY" android:label="@string/permlab_deadlyActivity" android:description="@st ring/permdesc_deadlyActivity" android:permissionGroup="android.permission-group. COST_MONEY" android:protectionLevel="dangerous" /> </manifest> The <protectionLe vel> attribute is required, telling the system how the user is to be informed of applications requiring the permission, or who is allowed to hold that permissio n, as described in the linked documentation. The <permissionGroup> attribute is optional, and only used to help the system display permissions to the user. You will usually want to set this to either a standard system group (listed in andro id.Manifest.permission_group) or in more rare cases to one defined by yourself. It is preferred to use an existing group, as this simplifies the permission UI s hown to the user. Note that both a label and description should be supplied for the permission. These are string resources that can be displayed to the user whe n they are viewing a list of permissions (android:label) or details on a single permission ( android:description). The label should be short, a few words descri bing the key piece of functionality the permission is protecting. The descriptio n should be a couple sentences describing what the permission allows a holder to do. Our convention for the description is two sentences, the first describing t he permission, the second warning the user of what bad things can happen if an a pplication is granted the permission. Here is an example of a label and descript ion for the CALL_PHONE permission: <string name="permlab_callPhone">directly cal l phone numbers</string> <string name="permdesc_callPhone">Allows the applicatio n to call phone numbers without your intervention. Malicious applications may ca use unexpected calls on your phone bill. Note that this does not allow the appli cation to call emergency numbers.</string> You can look at the permissions curre ntly defined in the system with the shell command adb shell pm list permissions. In particular, the '-s' option displays the permissions in a form roughly simil ar to how the user will see them: $ adb shell pm list permissions -s All Permiss ions: Network communication: view Wi-Fi state, create Bluetooth connections, ful l Internet access, view network state Your location: access extra location provi der commands, fine (GPS) location, mock location sources for testing, coarse (ne twork-based) location Services that cost you money: send SMS messages, directly call phone numbers ... Enforcing Permissions in AndroidManifest.xml High-level permissions restricting access to entire components of the system or application can be applied through your AndroidManifest.xml. All that this requi res is including an android:permission attribute on the desired component, namin g the permission that will be used to control access to it. Activity permissions (applied to the <activity> tag) restrict who can start the associated activity. The permission is checked during Context.startActivity() and Activity.startActi vityForResult(); if the caller does not have the required permission then Securi tyException is thrown from the call. http://developer.android.com/guide/topics/security/security.html Page 3 of 5

Security and Permissions | Android Developers 29.04.09 0:41 Service permissions (applied to the <service> tag) restrict who can start or bin d to the associated service. The permission is checked during Context.startServi ce(), Context.stopService() and Context.bindService(); if the caller does not ha ve the required permission then SecurityException is thrown from the call. Broad castReceiver permissions (applied to the <receiver> tag) restrict who can send b roadcasts to the associated receiver. The permission is checked after Context.se ndBroadcast() returns, as the system tries to deliver the submitted broadcast to the given receiver. As a result, a permission failure will not result in an exc eption being thrown back to the caller; it will just not deliver the intent. In the same way, a permission can be supplied to Context.registerReceiver() to cont rol who can broadcast to a programmatically registered receiver. Going the other way, a permission can be supplied when calling Context.sendBroadcast() to restr ict which BroadcastReceiver objects are allowed to receive the broadcast (see be low). ContentProvider permissions (applied to the <provider> tag) restrict who c an access the data in a ContentProvider. (Content providers have an important ad ditional security facility available to them called URI permissions which is des cribed later.) Unlike the other components, there are two separate permission at tributes you can set: android:readPermission restricts who can read from the pro vider, and android:writePermission restricts who can write to it. Note that if a provider is protected with both a read and write permission, holding only the w rite permission does not mean you can read from a provider. The permissions are checked when you first retrieve a provider (if you don't have either permission, a SecurityException will be thrown), and as you perform operations on the provi der. Using ContentResolver.query() requires holding the read permission; using C ontentResolver.insert(), ContentResolver.update(), ContentResolver.delete() requ ires the write permission. In all of these cases, not holding the required permi ssion results in a SecurityException being thrown from the call. Enforcing Permissions when Sending Broadcasts In addition to the permission enforcing who can send Intents to a registered Bro adcastReceiver (as described above), you can also specify a required permission when sending a broadcast. By calling Context.sendBroadcast() with a permission s tring, you require that a receiver's application must hold that permission in or der to receive your broadcast. Note that both a receiver and a broadcaster can r equire a permission. When this happens, both permission checks must pass for the Intent to be delivered to the associated target. Other Permission Enforcement Arbitrarily fine-grained permissions can be enforced at any call into a service. This is accomplished with the Context.checkCallingPermission() method. Call wit h a desired permission string and it will return an integer indicating whether t hat permission has been granted to the current calling process. Note that this c an only be used when you are executing a call coming in from another process, us ually through an IDL interface published from a service or in some other way giv en to another process. There are a number of other useful ways to check permissi ons. If you have the pid of another process, you can use the Context method Cont ext.checkPermission(String, int, int) to check a permission against that pid. If you have the package name of another application, you can use the direct Packag eManager method PackageManager.checkPermission(String, String) to find out wheth er that particular package has been granted a specific permission. URI Permissions The standard permission system described so far is often not sufficient when use d with content providers. A content provider may want to protect itself with rea d and write permissions, while its direct clients also need to hand specific URI s to other applications for them to operate on. A typical example is attachments

in a mail application. Access to the mail should be protected by permissions, s ince this is sensitive user data. However, if a URI to an image attachment is gi ven to an image viewer, that image viewer will not have permission to open the a ttachment since it has no reason to hold a permission to access all e-mail. http://developer.android.com/guide/topics/security/security.html Page 4 of 5

Security and Permissions | Android Developers 29.04.09 0:41 The solution to this problem is per-URI permissions: when starting an activity o r returning a result to an activity, the caller can set Intent.FLAG_GRANT_READ_U RI_PERMISSION and/or Intent.FLAG_GRANT_WRITE_URI_PERMISSION. This grants the rec eiving activity permission access the specific data URI in the Intent, regardles s of whether it has any permission to access data in the content provider corres ponding to the Intent. This mechanism allows a common capability-style model whe re user interaction (opening an attachment, selecting a contact from a list, etc ) drives ad-hoc granting of fine-grained permission. This can be a key facility for reducing the permissions needed by applications to only those directly relat ed to their behavior. The granting of fine-grained URI permissions does, however , require some cooperation with the content provider holding those URIs. It is s trongly recommended that content providers implement this facility, and declare that they support it through the android:grantUriPermissions attribute or <grant -uri-permissions> tag. More information can be found in the Context.grantUriPerm ission(), Context.revokeUriPermission(), and Context.checkUriPermission() method s. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/security/security.html Page 5 of 5

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 The AndroidManifest.xml File Every application must have an AndroidManifest.xml file (with precisely that nam e) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it ca n run any of the application's code. Among other things, the manifest does the f ollowing: It names the Java package for the application. The package name serves as a unique identifier for the application. It describes the components of the application the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each o f the components and publishes their capabilities (for example, which Intent mes sages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched. It determines whi ch processes will host application components. It declares which permissions the application must have in order to access protected parts of the API and interac t with other applications. It also declares the permissions that others are requ ired to have in order to interact with the application's components. It lists th e Instrumentation classes that provide profiling and other information as the ap plication is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the applic ation is published. It declares the minimum level of the Android API that the ap plication requires. It lists the libraries that the application must be linked a gainst. Structure of the Manifest File The diagram below shows the general structure of the manifest file and every ele ment that it can contain. Each element, along with all of its attributes, is doc umented in full in a separate file. To view detailed information about any eleme nt, click on the element name in the diagram, in the alphabetical list of elemen ts that follows the diagram, or on any other mention of the element name. <?xml version="1.0" encoding="utf-8"?> <manifest> <uses-permission /> <permission /> < permission-tree /> <permission-group /> <instrumentation /> <uses-sdk /> <applic ation> <activity> <intent-filter> <action /> http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 1 of 6

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 <action /> <category /> <data /> </intent-filter> <meta-data /> </activity> <act ivity-alias> <intent-filter> . . . </intent-filter> <meta-data /> </activity-ali as> <service> <intent-filter> . . . </intent-filter> <meta-data/> </service> <re ceiver> <intent-filter> . . . </intent-filter> <meta-data /> </receiver> <provid er> <grant-uri-permission /> <meta-data /> </provider> <uses-library /> <uses-co nfiguration /> </application> </manifest> All the elements that can appear in th e manifest file are listed below in alphabetical order. These are the only legal elements; you cannot add your own elements or attributes. <action> <activity> < activity-alias> <application> <category> <data> <grant-uri-permission> <instrume ntation> <intent-filter> <manifest> <meta-data> <permission> <permission-group> <permission-tree> <provider> <receiver> <service> <uses-configuration> <uses-lib rary> <uses-permission> <uses-sdk> File Conventions Some conventions and rules apply generally to all elements and attributes in the manifest: http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 2 of 6

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 Elements Only the <manifest> and <application> elements are required, they each must be present and can occur only once. Most of the others can occur many times or not at all although at least some of them must be present for the manifest t o accomplish anything meaningful. If an element contains anything at all, it con tains other elements. All values are set through attributes, not as character da ta within an element. Elements at the same level are generally not ordered. For example, <activity>, <provider>, and <service> elements can be intermixed in any sequence. (An <activity-alias> element is the exception to this rule: It must f ollow the <activity> it is an alias for.) Attributes In a formal sense, all attr ibutes are optional. However, there are some that must be specified for an eleme nt to accomplish its purpose. Use the documentation as a guide. For truly option al attributes, it mentions a default value or states what happens in the absence of a specification. Except for some attributes of the root <manifest> element, all attribute names begin with an android: prefix for example, android:alwaysRet ainTaskState. Because the prefix is universal, the documentation generally omits it when referring to attributes by name. Declaring class names Many elements co rrespond to Java objects, including elements for the application itself (the <ap plication> element) and its principal components activities (<activity>), servic es (<service>), broadcast receivers (<receiver>), and content providers (<provid er>). If you define a subclass, as you almost always would for the component cla sses (Activity, Service, BroadcastReceiver, and ContentProvider), the subclass i s declared through a name attribute. The name must include the full package desi gnation. For example, an Service subclass might be declared as follows: <manifes t . . . > <application . . . > <service android:name="com.example.project.Secret Service" . . . > . . . </service> . . . </application> </manifest> However, as a shorthand, if the first character of the string is a period, the string is appe nded to the application's package name (as specified by the <manifest> element's package attribute). The following assignment is the same as the one above: <man ifest package="com.example.project" . . . > <application . . . > <service androi d:name=".SecretService" . . . > . . . </service> . . . </application> </manifest > When starting a component, Android creates an instance of the named subclass. If a subclass isn't specified, it creates an instance of the base class. Multipl e values If more than one value can be specified, the element is almost always r epeated, rather than listing multiple values within a single element. For exampl e, an intent filter can list several actions: http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 3 of 6

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 <intent-filter . . . > <action android:name="android.intent.action.EDIT" /> <act ion android:name="android.intent.action.INSERT" /> <action android:name="android .intent.action.DELETE" /> . . . </intent-filter> Resource values Some attributes have values that can be displayed to users for example, a label and an icon for an activity. The values of these attributes should be localized and therefore s et from a resource or theme. Resource values are expressed in the following form at, @[package:]type:name where the package name can be omitted if the resource i s in the same package as the application, type is a type of resource such as "st ring" or "drawable" and name is the name that identifies the specific resource. For example: <activity android:icon="@drawable/smallPic" . . . > Values from a t heme are expressed in a similar manner, but with an initial '?' rather than '@': ?[package:]type:name String values Where an attribute value is a string, double backslashes ('\\') must be used to escape characters for example, '\\n' for a n ewline or '\\uxxxx' for a Unicode character. File Features The following sections describe how some Android features are reflected in the m anifest file. Intent Filters The core components of an application (its activities, services, and broadcast r eceivers) are activated by intents. An intent is a bundle of information (an Int ent object) describing a desired action including the data to be acted upon, the category of component that should perform the action, and other pertinent instr uctions. Android locates an appropriate component to respond to the intent, laun ches a new instance of the component if one is needed, and passes it the Intent object. Components advertise their capabilities the kinds of intents they can re spond to through intent filters. Since the Android system must learn which inten ts a component can handle before it launches the component, intent filters are s pecified in the manifest as <intent-filter> elements. A component may have any n umber of filters, each one describing a different capability. An intent that exp licitly names a target component will activate that component; the filter doesn' t play a role. But an intent that doesn't specify a target by name can activate a component only if it can pass through one of the component's filters. For info rmation on how Intent objects are tested against intent filters, see a separate document, Intents and Intent Filters. Icons and Labels A number of elements have icon and label attributes for a small icon and a text label that can be displayed to users. Some also have a description attribute for longer explanatory text that can also be shown on-screen. For http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 4 of 6

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 users. Some also have a description attribute for longer explanatory text that c an also be shown on-screen. For example, the <permission> element has all three of these attributes, so that when the user is asked whether to grant the permiss ion to an application that has requested it, an icon representing the permission , the name of the permission, and a description of what it entails can all be pr esented to the user. In every case, the icon and label set in a containing eleme nt become the default icon and label settings for all of the container's subelem ents. Thus, the icon and label set in the <application> element are the default icon and label for each of the application's components. Similarly, the icon and label set for a component for example, an <activity> element are the default se ttings for each of the component's <intent-filter> elements. If an <application> element sets a label, but an activity and its intent filter do not, the applica tion label is treated as the label for both the activity and the intent filter. The icon and label set for an intent filter are used to represent a component wh enever the component is presented to the user as fulfilling the function adverti sed by the filter. For example, a filter with "android.intent.action.MAIN" and " android.intent.category.LAUNCHER" settings advertises an activity as one that in itiates an application that is, as one that should be displayed in the applicati on launcher. The icon and label set in the filter are therefore the ones display ed in the launcher. Permissions A permission is a restriction limiting access to a part of the code or to data o n the device. The limitation is imposed to protect critical data and code that c ould be misused to distort or damage the user experience. Each permission is ide ntified by a unique label. Often the label indicates the action that's restricte d. For example, here are some permissions defined by Android: android.permission .CALL_EMERGENCY_NUMBERS android.permission.READ_OWNER_DATA android.permission.SE T_WALLPAPER android.permission.DEVICE_POWER A feature can be protected by at mos t one permission. If an application needs access to a feature protected by a per mission, it must declare that it requires that permission with a <uses-permissio n> element in the manifest. Then, when the application is installed on the devic e, the installer determines whether or not to grant the requested permission by checking the authorities that signed the application's certificates and, in some cases, asking the user. If the permission is granted, the application is able t o use the protected features. If not, its attempts to access those features will simply fail without any notification to the user. An application can also prote ct its own components (activities, services, broadcast receivers, and content pr oviders) with permissions. It can employ any of the permissions defined by Andro id (listed in android.Manifest.permission) or declared by other applications. Or it can define its own. A new permission is declared with the <permission> eleme nt. For example, an activity could be protected as follows: <manifest . . . > <p ermission android:name="com.example.project.DEBIT_ACCT" . . . /> . . . <applicat ion . . .> <activity android:name="com.example.project.FreneticActivity" . . . > android:permission="com.example.project.DEBIT_ACCT" . . . > . . . </activity> < /application> . . . <uses-permission android:name="com.example.project.DEBIT_ACC T" /> . . . </manifest> http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 5 of 6

The AndroidManifest.xml File | Android Developers 29.04.09 0:43 Note that, in this example, the DEBIT_ACCT permission is not only declared with the <permission> element, its use is also requested with the <uses-permission> e lement. Its use must be requested in order for other components of the applicati on to launch the protected activity, even though the protection is imposed by th e application itself. If, in the same example, the permission attribute was set to a permission declared elsewhere (such as android.permission.CALL_EMERGENCY_NU MBERS, it would not have been necessary to declare it again with a <permission> element. However, it would still have been necessary to request its use with <us es-permission>. The <permission-tree> element declares a namespace for a group o f permissions that will be defined in code. And <permission-group> defines a lab el for a set of permissions (both those declared in the manifest with <permissio n> elements and those declared elsewhere). It affects only how the permissions a re grouped when presented to the user. The <permission-group> element does not s pecify which permissions belong to the group; it just gives the group a name. A permission is placed in the group by assigning the group name to the <permission > element's permissionGroup attribute. Libraries Every application is linked against the default Android library, which includes the basic packages for building applications (with common classes such as Activi ty, Service, Intent, View, Button, Application, ContentProvider, and so on). How ever, some packages reside in their own libraries. If your application uses code from any of these packages, it must explicitly asked to be linked against them. The manifest must contain a separate <uses-library> element to name each of the libraries. (The library name can be found in the documentation for the package. ) Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/manifest-intro.html Page 6 of 6

<action> | Android Developers 29.04.09 0:43 <action> SYNTAX: <action android:name="string" /> CONTAINED IN: <intent-filter> DESCRIPTION: Adds an action to an intent filter. An <intent-filter> element must contain one or more <action> elements. If it doesn't contain any, no Intent objects will get through the filter. See Intents and Intent Filters for details on intent filter s and the role of action specifications within a filter. ATTRIBUTES: android:name The name of the action. Some standard actions are defined in the In tent class as ACTION_string constants. To assign one of these actions to this at tribute, prepend "android.intent.action." to the string that follows ACTION_. Fo r example, for ACTION_MAIN, use "android.intent.action.MAIN" and for ACTION_WEB_ SEARCH, use "android.intent.action.WEB_SEARCH". For actions you define, it's bes t to use the package name as a prefix to ensure uniqueness. For example, a TRANS MOGRIFY action might be specified as follows: <action android:name="com.example. project.TRANSMOGRIFY" /> INTRODUCED IN: API Level 1 SEE ALSO: <intent-filter> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/action-element.html Page 1 of 1

<activity> | Android Developers 29.04.09 0:43 <activity> SYNTAX: <activity android:allowTaskReparenting=["true" | "false"] android:alwaysRetainTa skState=["true" | "false"] android:clearTaskOnLaunch=["true"" | "false"] android :configChanges=[one or more of: "mcc" "mnc" "locale" "touchscreen" "keyboard" "k eyboardHidden" "navigation" "orientation" "fontScale"] android:enabled=["true" | "false"] android:excludeFromRecents=["true" | "false"] android:exported=["true" | "false"] android:finishOnTaskLaunch=["true" | "false"] android:icon="drawable resource" android:label="string resource" android:launchMode=["multiple" | "sin gleTop" | "singleTask" | "singleInstance"] android:multiprocess=["true" | "false "] android:name="string" android:noHistory=["true" | "false"] android:permission ="string" android:process="string" android:screenOrientation=["unspecified" | "u ser" | "behind" | "landscape" | "portrait" | "sensor" | "nonsensor"] android:sta teNotNeeded=["true" | "false"] android:taskAffinity="string" android:theme="reso urce or theme" android:windowSoftInputMode=[one or more of: "stateUnspecified" " stateUnchanged" "stateHidden" "stateAlwaysHidden" "stateVisible" "stateAlwaysVis ible" "adjustUnspecified" "adjustResize" "adjustPan"] > . . . </activity> CONTAINED IN: <application> CAN CONTAIN: <intent-filter> <meta-data> DESCRIPTION: Declares an activity (an Activity subclass) that implements part of the applicat ion's visual user interface. All activities must be represented by <activity> el ements in the manifest file. Any that are not declared there will not be seen by the system and will never be run. ATTRIBUTES: android:allowTaskReparenting Whether or not the activity can move from the task that started it to the task it has an affinity for when that task is next brough t to the front "true" if it can move, and "false" if it must remain with the tas k where it started. http://developer.android.com/guide/topics/manifest/activity-element.html Page 1 of 8

<activity> | Android Developers 29.04.09 0:43 If this attribute is not set, the value set by the corresponding allowTaskRepare nting attribute of the <application> element applies to the activity. The defaul t value is "false". Normally when an activity is started, it's associated with t he task of the activity that started it and it stays there for its entire lifeti me. You can use this attribute to force it to be re-parented to the task it has an affinity for when its current task is no longer displayed. Typically, it's us ed to cause the activities of an application to move to the main task associated with that application. For example, if an e-mail message contains a link to a w eb page, clicking the link brings up an activity that can display the page. That activity is defined by the browser application, but is launched as part of the e-mail task. If it's reparented to the browser task, it will be shown when the b rowser next comes to the front, and will be absent when the e-mail task again co mes forward. The affinity of an activity is defined by the taskAffinity attribut e. The affinity of a task is determined by reading the affinity of its root acti vity. Therefore, by definition, a root activity is always in a task with the sam e affinity. Since activities with "singleTask" or "singleInstance" launch modes can only be at the root of a task, re-parenting is limited to the "standard" and "singleTop" modes. (See also the launchMode attribute.) android:alwaysRetainTas kState Whether or not the state of the task that the activity is in will always be maintained by the system "true" if it will be, and "false" if the system is a llowed to reset the task to its initial state in certain situations. The default value is "false". This attribute is meaningful only for the root activity of a task; it's ignored for all other activities. Normally, the system clears a task (removes all activities from the stack above the root activity) in certain situa tions when the user re-selects that task from the home screen. Typically, this i s done if the user hasn't visited the task for a certain amount of time, such as 30 minutes. However, when this attribute is "true", users will always return to the task in its last state, regardless of how they get there. This is useful, f or example, in an application like the web browser where there is a lot of state (such as multiple open tabs) that users would not like to lose. android:clearTa skOnLaunch Whether or not all activities will be removed from the task, except f or the root activity, whenever it is relaunched from the home screen "true" if t he task is always stripped down to its root activity, and "false" if not. The de fault value is "false". This attribute is meaningful only for activities that st art a new task (the root activity); it's ignored for all other activities in the task. When the value is "true", every time users start the task again, they are brought to its root activity, regardless of what they were last doing in the ta sk and regardless of whether they used BACK or HOME to last leave it. When the v alue is "false", the task may be cleared of activities in some situations (see t he alwaysRetainTaskState attribute), but not always. Suppose, for example, that someone launches activity P from the home screen, and from there goes to activit y Q. The user next presses HOME, and then returns to activity P. Normally, the u ser would see activity Q, since that is what they were last doing in P's task. H owever, if P set this flag to "true", all of the activities on top of it (Q in t his case) were removed when the user pressed HOME and the task went to the backg round. So the user sees only P when returning to the task. If this attribute and allowTaskReparenting are both "true", any activities that can be re-parented ar e moved to the task they share an affinity with; the remaining activities are th en dropped, as described above. android:configChanges Lists configuration change s that the activity will handle itself. When changes that are not listed occur, the activity is shut down and restarted. When a listed change occurs, the activi ty remains running and its onConfigurationChanged() method is called. Any or all of the following strings can be used to set this attribute. Values are separate d by '|' for example, "locale|navigation|orientation". http://developer.android.com/guide/topics/manifest/activity-element.html Page 2 of 8

<activity> | Android Developers 29.04.09 0:43 "locale|navigation|orientation". Value "mcc" "mnc" "locale" "touchscreen" "keybo ard" "keyboardHidden" "navigation" "orientation" "fontScale" Description The IMS I mobile country code (MCC) has changed that is, a SIM has been detected and upd ated the MCC. The IMSI mobile network code (MNC) has changed that is, a SIM has been detected and updated the MNC. The locale has changed for example, the user has selected a new language that text should be displayed in. The touchscreen ha s changed. (This should never normally happen.) The keyboard type has changed fo r example, the user has plugged in an external keyboard. The keyboard accessibil ity has changed for example, the user has slid the keyboard out to expose it. Th e navigation type has changed. (This should never normally happen.) The screen o rientation has changed that is, the user has rotated the device. The font scalin g factor has changed that is, the user has selected a new global font size. All of these configuration changes can impact the resource values seen by the ap plication. Therefore, when onConfigurationChanged() is called, it will generally be necessary to again retrieve all resources (including view layouts, drawables , and so on) to correctly handle the change. android:enabled Whether or not the activity can be instantiated by the system "true" if it can be, and "false" if n ot. The default value is "true". The <application> element has its own enabled a ttribute that applies to all application components, including activities. The < application> and <activity> attributes must both be "true" (as they both are by default) for the system to be able to instantiate the activity. If either is "fa lse", it cannot be instantiated. android:excludeFromRecents Whether or not the a ctivity should be excluded from the list of recently launched activities that ca n be displayed to users "true" if it should be excluded, and "false" if it shoul d be included. The default value is "false". android:exported Whether or not the activity can be launched by components of other applications "true" if it can b e, and "false" if not. If "false", the activity can be launched only by componen ts of the same application or applications with the same user ID. The default va lue depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact clas s name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true". This attribute is not the only way to limit an activity's exposure to other app lications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute). http://developer.android.com/guide/topics/manifest/activity-element.html Page 3 of 8

<activity> | Android Developers 29.04.09 0:43 android:finishOnTaskLaunch Whether or not an existing instance of the activity s hould be shut down (finished) whenever the user again launches its task (chooses the task on the home screen) "true" if it should be shut down, and "false" if n ot. The default value is "false". If this attribute and allowTaskReparenting are both "true", this attribute trumps the other. The affinity of the activity is i gnored. The activity is not re-parented, but destroyed. android:icon An icon rep resenting the activity. The icon is displayed to users when a representation of the activity is required on-screen. For example, icons for activities that initi ate tasks are displayed in the launcher window. The icon is often accompanied by a label (see the label attribute). This attribute must be set as a reference to a drawable resource containing the image definition. If it is not set, the icon specified for the application as a whole is used instead (see the <application> element's icon attribute). The activity's icon whether set here or by the <appl ication> element is also the default icon for all the activity's intent filters (see the <intent-filter> element's icon attribute). android:label A user-readabl e label for the activity. The label is displayed on-screen when the activity mus t be represented to the user. It's often displayed along with the activity icon. If this attribute is not set, the label set for the application as a whole is u sed instead (see the <application> element's label attribute). The activity's la bel whether set here or by the <application> element is also the default label f or all the activity's intent filters (see the <intent-filter> element's label at tribute). The label should be set as a reference to a string resource, so that i t can be localized like other strings in the user interface. However, as a conve nience while you're developing the application, it can also be set as a raw stri ng. android:launchMode An instruction on how the activity should be launched. Th ere are four modes that work in conjunction with activity flags (FLAG_ACTIVITY_* constants) in Intent objects to determine what should happen when the activity is called upon to handle an intent. They are: "standard" "singleTop" "singleTask " "singleInstance" The default mode is "standard". The modes fall into two main groups, with "standard" and "singleTop" activities on one side, and "singleTask" and "singleInstance" activities on the other. An activity with the "standard" o r "singleTop" launch mode can be instantiated multiple times. The instances can belong to any task and can be located anywhere in the activity stack. Typically, they're launched into the task that called startActivity() (unless the Intent o bject contains a FLAG_ACTIVITY_NEW_TASK instruction, in which case a different t ask is chosen see the taskAffinity attribute). In contrast, "singleTask" and "si ngleInstance" activities can only begin a task. They are always at the root of t he activity stack. Moreover, the device can hold only one instance of the activi ty at a time only one such task. The "standard" and "singleTop" modes differ fro m each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Eac h instance handles a single intent. Similarly, a new instance of a "singleTop" a ctivity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its http://developer.android.com/guide/topics/manifest/activity-element.html Page 4 of 8

<activity> | Android Developers 29.04.09 0:43 handle a new intent. However, if the target task already has an existing instanc e of the activity at the top of its stack, that instance will receive the new in tent (in an onNewIntent() call); a new instance is not created. In other circums tances for example, if an existing instance of the "singleTop" activity is in th e target task, but not at the top of the stack, or if it's at the top of a stack , but not in the target task a new instance would be created and pushed on the s tack. The "singleTask" and "singleInstance" modes also differ from each other in only one respect: A "singleTask" activity allows other activities to be part of its task. It's at the root of the activity stack, but other activities (necessa rily "standard" and "singleTop" activities) can be launched into the same task. A "singleInstance" activity, on the other hand, permits no other activities to b e part of its task. It's the only activity in the task. If it starts another act ivity, that activity is assigned to a different task as if FLAG_ACTIVITY_NEW_TAS K was in the intent. For more information on launch modes and their interaction with Intent flags, see the Activities and Tasks section of the Application Funda mentals document. android:multiprocess Whether an instance of the activity can b e launched into the process of the component that started it "true" if it can be , and "false" if not. The default value is "false". Normally, a new instance of an activity is launched into the process of the application that defined it, so all instances of the activity run in the same process. However, if this flag is set to "true", instances of the activity can run in multiple processes, allowing the system to create instances wherever they are used (provided permissions all ow it), something that is almost never necessary or desirable. android:name The name of the class that implements the activity, a subclass of Activity. The attr ibute value should be a fully qualified class name (such as, "com.example.projec t.ExtracurricularActivity"). However, as a shorthand, if the first character of the name is a period (for example, ".ExtracurricularActivity"), it is appended t o the package name specified in the <manifest> element. There is no default. The name must be specified. android:noHistory Whether or not the activity should be removed from the activity stack and finished (its finish() method called) when the user navigates away from it and it's no longer visible on screen "true" if i t should be finished, and "false" if not. The default value is "false". A value of "true" means that the activity will not leave a historical trace. It will not remain in the activity stack for the task, so the user will not be able to retu rn to it. This attribute was introduced in API Level 3. android:permission The n ame of a permission that clients must have to launch the activity or otherwise g et it to respond to an intent. If a caller of startActivity() or startActivityFo rResult() has not been granted the specified permission, its intent will not be delivered to the activity. If this attribute is not set, the permission set by t he <application> element's permission attribute applies to the activity. If neit her attribute is set, the activity is not protected by a permission. For more in formation on permissions, see the Permissions section in the introduction and an other document, Security and Permissions. android:process The name of the proces s in which the activity should run. Normally, all components of an application r un in the default process created for the application. It has the same name as t he application package. The <application> element's process attribute can set a different default for all components. But each component can override the defaul t, allowing you to spread your application across multiple processes. http://developer.android.com/guide/topics/manifest/activity-element.html Page 5 of 8

<activity> | Android Developers 29.04.09 0:43 If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the activity runs i n that process. If the process name begins with a lowercase character, the activ ity will run in a global process of that name, provided that it has permission t o do so. This allows components in different applications to share a process, re ducing resource usage. android:screenOrientation The orientation of the activity 's display on the device. The value can be any one of the following strings: "un specified" "landscape" "portrait" "user" "behind" "sensor" The default value. Th e system chooses the orientation. The policy it uses, and therefore the choices made in specific contexts, may differ from device to device. Landscape orientati on (the display is wider than it is tall). Portrait orientation (the display is taller than it is wide). The user's current preferred orientation. The same orie ntation as the activity that's immediately beneath it in the activity stack. The orientation determined by a physical orientation sensor. The orientation of the display depends on how the user is holding the device; it changes when the user rotates the device. An orientation determined without reference to a physical o rientation sensor. The sensor is ignored, so the display will not rotate based o n how the user moves the device. Except for this distinction, the system chooses the orientation using the same policy as for the "unspecified" setting. "nosensor" android:stateNotNeeded Whether or not the activity can be killed and successfull y restarted without having saved its state "true" if it can be restarted without reference to its previous state, and "false" if its previous state is required. The default value is "false". Normally, before an activity is temporarily shut down to save resources, its onSaveInstanceState() method is called. This method stores the current state of the activity in a Bundle object, which is then passe d to onCreate() when the activity is restarted. If this attribute is set to "tru e", onSaveInstanceState() may not be called and onCreate() will be passed null i nstead of the Bundle just as it was when the activity started for the first time . A "true" setting ensures that the activity can be restarted in the absence of retained state. For example, the activity that displays the home screen uses thi s setting to make sure that it does not get removed if it crashes for some reaso n. android:taskAffinity The task that the activity has an affinity for. Activiti es with the same affinity conceptually belong to the same task (to the same "app lication" from the user's perspective). The affinity of a task is determined by the affinity of its root activity. The affinity determines two things the task t hat the activity is re-parented to (see the allowTaskReparenting attribute) and the task that will house the activity when it is launched with the FLAG_ACTIVITY _NEW_TASK flag. By default, all activities in an application have the same affin ity. You can set this attribute to group them differently, and even place activi ties defined in different applications within the same task. To specify that the activity does not have an affinity for any task, set it to an empty string. If this attribute is not set, the activity inherits the affinity set for the applic ation (see the <application> element's taskAffinity attribute). The name of the default affinity for an application is the package name set by the <manifest> el ement. http://developer.android.com/guide/topics/manifest/activity-element.html Page 6 of 8

<activity> | Android Developers 29.04.09 0:43 set by the <manifest> element. android:theme A reference to a style resource def ining an overall theme for the activity. This automatically sets the activity's context to use this theme (see setTheme(), and may also cause "starting" animati ons prior to the activity being launched (to better match what the activity actu ally looks like). If this attribute is not set, the activity inherits the theme set for the application as a whole see the <application> element's theme attribu te. If that attribute is also not set, the default system theme is used. android :windowSoftInputMode How the main window of the activity interacts with the wind ow containing the on-screen soft keyboard. The setting for this attribute affect s two things: The state of the soft keyboard whether it is hidden or visible whe n the activity becomes the focus of user attention. The adjustment made to the a ctivity's main window whether it is resized smaller to make room for the soft ke yboard or whether its contents pan to make the current focus visible when part o f the window is covered by the soft keyboard. The setting must be one of the val ues listed in the following table, or a combination of one "state..." value plus one "adjust..." value. Setting multiple values in either group multiple "state. .." values, for example has undefined results. Individual values are separated b y a vertical bar (|). For example: <activity android:windowSoftInputMode="stateV isible|adjustResize" . . . > Values set here (other than "stateUnspecified" and "adjustUnspecified") override values set in the theme. Value "stateUnspecified" Description The state of the soft keyboard (whether it is hidden or visible) is not specified. The system will choose an appropriate state or rely on the settin g in the theme. This is the default setting for the behavior of the soft keyboar d. "stateUnchanged" "stateHidden" The soft keyboard is kept in whatever state it was last in, whether visible or hidden, when the activity comes to the fore. Th e soft keyboard is hidden when the user chooses the activity that is, when the u ser affirmatively navigates forward to the activity, rather than backs into it b ecause of leaving another activity. The soft keyboard is always hidden when the activity's main window has input focus. The soft keyboard is visible when that's normally appropriate (when the user is navigating forward to the activity's mai n window). The soft keyboard is made visible when the user chooses the activity that is, when the user affirmatively navigates forward to the activity, rather t han backs into it because of leaving another activity. It is unspecified whether the activity's main window resizes to make room for the soft keyboard, or wheth er the contents of the window pan to make the currentfocus visible on-screen. Th e system will automatically select one of these modes depending on whether the c ontent of the window has any layout views that can scroll their contents. Page 7 of 8 "stateAlwaysHidden" "stateVisible" "stateAlwaysVisible" "adjustUnspecified" http://developer.android.com/guide/topics/manifest/activity-element.html

<activity> | Android Developers 29.04.09 0:43 content of the window has any layout views that can scroll their contents. If th ere is such a view, the window will be resized, on the assumption that scrolling can make all of the window's contents visible within a smaller area. This is th e default setting for the behavior of the main window. "adjustResize" "adjustPan " The activity's main window is always resized to make room for the soft keyboar d on screen. The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that t he current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desireable than resizing, because the u ser may need to close the soft keyboard to get at and interact with obscured par ts of the window. This attribute was introduced in API Level 3. INTRODUCED IN: API Level 1 for all attributes except for noHistory and windowSoftInputMode, whi ch were added in API Level 3. SEE ALSO: <application> <activity-alias> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/activity-element.html Page 8 of 8

<activity-alias> | Android Developers 29.04.09 0:43 <activity-alias> SYNTAX: <activity-alias android:enabled=["true" | "false"] android:exported=["true" | "f alse"] android:icon="drawable resource" android:label="string resource" android: name="string" android:permission="string" android:targetActivity="string" > . . . </activity-alias> CONTAINED IN: <application> CAN CONTAIN: <intent-filter> <meta-data> DESCRIPTION: An alias for an activity, named by the targetActivity attribute. The target must be in the same application as the alias and it must be declared before the alia s in the manifest. The alias presents the target activity as a independent entit y. It can have its own set of intent filters, and they, rather than the intent f ilters on the target activity itself, determine which intents can activate the t arget through the alias and how the system treats the alias. For example, the in tent filters on the alias may specify the "android.intent.action.MAIN" and "andr oid.intent.category.LAUNCHER" flags, causing it to be represented in the applica tion launcher, even though none of the filters on the target activity itself set these flags. With the exception of targetActivity, <activity-alias> attributes are a subset of <activity> attributes. For attributes in the subset, none of the values set for the target carry over to the alias. However, for attributes not in the subset, the values set for the target activity also apply to the alias. ATTRIBUTES: android:enabled Whether or not the target activity can be instantiated by the sy stem through this alias "true" if it can be, and "false" if not. The default val ue is "true". The <application> element has its own enabled attribute that appli es to all application components, including activity aliases. The <application> and <activity-alias> attributes must both be "true" for the system to be able to instantiate the target activity through the alias. If either is "false", the al ias does not work. android:exported Whether or not components of other applicati ons can launch the target activity through this alias "true" if they can, and "f alse" if not. If "false", the target activity can be launched through the alias only by components of the same application as the alias or applications with the same user ID. The default value depends on whether the alias contains intent fi lters. The absence of any filters means that the activity can be invoked through the alias only by specifying the exact name of the alias. This implies that http://developer.android.com/guide/topics/manifest/activity-alias-element.html P age 1 of 2

<activity-alias> | Android Developers 29.04.09 0:43 the activity can be invoked through the alias only by specifying the exact name of the alias. This implies that the alias is intended only for application-inter nal use (since others would not know its name) so the default value is "false". On the other hand, the presence of at least one filter implies that the alias is intended for external use so the default value is "true". android:icon An icon for the target activity when presented to users through the alias. See the <acti vity> element's icon attribute for more information. android:label A user-readab le label for the alias when presented to users through the alias. See the the <a ctivity> element's label attribute for more information. android:name A unique n ame for the alias. The name should resemble a fully qualified class name. But, u nlike the name of the target activity, the alias name is arbitrary; it does not refer to an actual class. android:permission The name of a permission that clien ts must have to launch the target activity or get it to do something via the ali as. If a caller of startActivity() or startActivityForResult() has not been gran ted the specified permission, the target activity will not be activated. This at tribute supplants any permission set for the target activity itself. If it is no t set, a permission is not needed to activate the target through the alias. For more information on permissions, see the Permissions section in the introduction . android:targetActivity The name of the activity that can be activated through the alias. This name must match the name attribute of an <activity> element that precedes the alias in the manifest. INTRODUCED IN: API Level 1 SEE ALSO: <activity> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/activity-alias-element.html Page 2 of 2

<application> | Android Developers 29.04.09 0:43 <application> SYNTAX: <application android:allowClearUserData=["true" | "false"] android:allowTaskRepa renting=["true" | "false"] android:debuggable=["true" | "false"] android:descrip tion="string resource" android:enabled=["true" | "false"] android:hasCode=["true " | "false"] android:icon="drawable resource" android:label="string resource" an droid:manageSpaceActivity="string" android:name="string" android:permission="str ing" android:persistent=["true" | "false"] android:process="string" android:task Affinity="string" android:theme="resource or theme" > . . . </application> CONTAINED IN: <manifest> CAN CONTAIN: <activity> <activity-alias> <service> <receiver> <provider> <uses-library> DESCRIPTION: The declaration of the application. This element contains subelements that decla re each of the application's components and has attributes that can affect all t he components. Many of these attributes (such as icon, label, permission, proces s, taskAffinity, and allowTaskReparenting) set default values for corresponding attributes of the component elements. Others (such as debuggable, enabled, descr iption, and allowClearUserData) set values for the application as a whole and ca nnot be overridden by the components. ATTRIBUTES android:allowClearUserData Whether or not users are given the option to remove u ser data "true" if they are, and "false" if not. If the value is "true", as it i s by default, the application manager includes an option that allows users to cl ear the data. android:allowTaskReparenting Whether or not activities that the ap plication defines can move from the task that started them to the task they have an affinity for when that task is next brought to the front "true" if they can move, and "false" if they must remain with the task where they started. The defa ult value is "false". http://developer.android.com/guide/topics/manifest/application-element.html Page 1 of 3

<application> | Android Developers 29.04.09 0:43 The <activity> element has its own allowTaskReparenting attribute that can overr ide the value set here. See that attribute for more information. android:debugga ble Whether or not the application can be debugged, even when running on a devic e in user mode "true" if it can be, and "false" if not. The default value is "fa lse". android:description User-readable text about the application, longer and m ore descriptive than the application label. The value must be set as a reference to a string resource. Unlike the label, it cannot be a raw string. There is no default value. android:enabled Whether or not the Android system can instantiate components of the application "true" if it can, and "false" if not. If the valu e is "true", each component's enabled attribute determines whether that componen t is enabled or not. If the value is "false", it overrides the component-specifi c values; all components are disabled. The default value is "true". android:hasC ode Whether or not the application contains any code "true" if it does, and "fal se" if not. When the value is "false", the system does not try to load any appli cation code when launching components. The default value is "true". An applicati on would not have any code of its own only if it's using nothing but built-in co mponent classes, such as an activity that uses the AliasActivity class, a rare o ccurrence. android:icon An icon for the application as whole, and the default ic on for each of the application's components. See the individual icon attributes for <activity>, <activity-alias>, <service>, <receiver>, and <provider> elements . This attribute must be set as a reference to a drawable resource containing th e image definition. There is no default icon. android:label A user-readable labe l for the application as a whole, and a default label for each of the applicatio n's components. See the individual label attributes for <activity>, <activity-al ias>, <service>, <receiver>, and <provider> elements. The label should be set as a reference to a string resource, so that it can be localized like other string s in the user interface. However, as a convenience while you're developing the a pplication, it can also be set as a raw string. android:manageSpaceActivity The fully qualified name of an Activity subclass that the system can launch to let u sers manage the memory occupied by the application on the device. The activity s hould also be declared with an <activity> element. android:name The fully qualif ied name of an Application subclass implemented for the application. When the ap plication process is started, this class is instantiated before any of the appli cation's components. The subclass is optional; most applications won't need one. In the absence of a subclass, Android uses an instance of the base Application class. android:permission The name of a permission that clients must have in ord er to interact with the application. This attribute is a convenient way to set a permission that applies to all of the application's components. It can be overw ritten by setting the permission attributes of individual components. http://developer.android.com/guide/topics/manifest/application-element.html Page 2 of 3

<application> | Android Developers 29.04.09 0:43 setting the permission attributes of individual components. For more information on permissions, see the Permissions section in the introduction and another doc ument, Security and Permissions. android:persistent Whether or not the applicati on should remain running at all times "true" if it should, and "false" if not. T he default value is "false". Applications should not normally set this flag; per sistence mode is intended only for certain system applications. android:process The name of a process where all components of the application should run. Each c omponent can override this default by setting its own process attribute. By defa ult, Android creates a process for an application when the first of its componen ts needs to run. All components then run in that process. The name of the defaul t process matches the package name set by the <manifest> element. By setting thi s attribute to a process name that's shared with another application, you can ar range for components of both applications to run in the same process but only if the two applications also share a user ID and be signed with the same certifica te. If the name assigned to this attribute begins with a colon (':'), a new proc ess, private to the application, is created when it's needed. If the process nam e begins with a lowercase character, a global process of that name is created. A global process can be shared with other applications, reducing resource usage. android:taskAffinity An affinity name that applies to all activities within the application, except for those that set a different affinity with their own taskA ffinity attributes. See that attribute for more information. By default, all act ivities within an application share the same affinity. The name of that affinity is the same as the package name set by the <manifest> element. android:theme A reference to a style resource defining a default theme for all activities in the application. Individual activities can override the default by setting their ow n theme attributes; see that attribute for more information. INTRODUCED IN: API Level 1 SEE ALSO: <activity> <service> <receiver> <provider> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/application-element.html Page 3 of 3

<category> | Android Developers 29.04.09 0:43 <category> SYNTAX: <category android:name="string" /> CONTAINED IN: <intent-filter> DESCRIPTION: Adds a category name to an intent filter. See Intents and Intent Filters for det ails on intent filters and the role of category specifications within a filter. ATTRIBUTES: android:name The name of the category. Standard categories are defined in the In tent class as CATEGORY_name constants. The name assigned here can be derived fro m those constants by prefixing "android.intent.category." to the name that follo ws CATEGORY_. For example, the string value for CATEGORY_LAUNCHER is "android.in tent.category.LAUNCHER". Custom categories should use the package name as a pref ix, to ensure that they are unique. INTRODUCED IN: API Level 1 SEE ALSO: <action> <data> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/category-element.html Page 1 of 1

<data> | Android Developers 29.04.09 0:44 <data> SYNTAX: <data android:host="string" android:mimeType="string" android:path="string" andr oid:pathPattern="string" android:pathPrefix="string" android:port="string" andro id:scheme="string" /> CONTAINED IN: <intent-filter> DESCRIPTION: Adds a data specification to an intent filter. The specification can be just a d ata type (the mimeType attribute), just a URI, or both a data type and a URI. A URI is specified by separate attributes for each of its parts: scheme://host:por t/path or pathPrefix or pathPattern These attributes are optional, but also mutu ally dependent: If a scheme is not specified for the intent filter, all the othe r URI attributes are ignored. If a host is not specified for the filer, the port attribute and all the path attributes are ignored. All the <data> elements cont ained within the same <intent-filter> element contribute to the same filter. So, for example, the following filter specification, <intent-filter . . . > <data a ndroid:scheme="something" android:host="project.example.com" /> . . . </intent-f ilter> is equivalent to this one: <intent-filter . . . > <data android:scheme="s omething" /> <data android:host="project.example.com" /> . . . </intent-filter> You can place any number of <data> elements inside an <intent-filter> to give it multiple data options. None of its attributes have default values. Information on how intent filters work, including the rules for how Intent objects are match ed against filters, can be found in another document, Intents and Intent Filters . See also the Intent Filters section in the introduction. ATTRIBUTES: android:host The host part of a URI authority. This attribute is meaningless unl ess a scheme attribute is also specified for the filter. http://developer.android.com/guide/topics/manifest/data-element.html Page 1 of 2

<data> | Android Developers 29.04.09 0:44 the filter. Note: host name matching in the Android framework is case-sensitive, unlike the formal RFC. As a result, you should always specify host names using lowercase letters. android:mimeType A MIME media type, such as image/jpeg or aud io/mpeg4-generic. The subtype can be the asterisk wildcard (*) to indicate that any subtype matches. Note: MIME type matching in the Android framework is case-s ensitive, unlike formal RFC MIME types. As a result, you should always specify M IME types using lowercase letters. android:path android:pathPrefix android:pathP attern The path part of a URI. The path attribute specifies a complete path that is matched against the complete path in an Intent object. The pathPrefix attrib ute specifies a partial path that is matched against only the initial part of th e path in the Intent object. The pathPattern attribute specifies a complete path that is matched against the complete path in the Intent object, but it can cont ain the following wildcards: An asterisk ('*') matches a sequence of 0 to many o ccurrences of the immediately preceding character. A period followed by an aster isk (".*") matches any sequence of 0 to many characters. Because '\' is used as an escape character when the string is read from XML (before it is parsed as a p attern), you will need to double-escape: For example, a literal '*' would be wri tten as "\\*" and a literal '\' would be written as "\\\\". This is basically th e same as what you would need to write if constructing the string in Java code. For more information on these three types of patterns, see the descriptions of P ATTERN_LITERAL, PATTERN_PREFIX, and PATTERN_SIMPLE_GLOB in the PatternMatcher cl ass. These attributes are meaningful only if the scheme and host attributes are also specified for the filter. android:port The port part of a URI authority. Th is attribute is meaningful only if the scheme and host attributes are also speci fied for the filter. android:scheme The scheme part of a URI. This is the minima l essential attribute for specifying a URI; at least one scheme attribute must b e set for the filter, or none of the other URI attributes are meaningful. A sche me is specified without the trailing colon (for example, http, rather than http: ). If the filter has a data type set (the mimeType attribute) but no scheme, the content: and file: schemes are assumed. Note: scheme matching in the Android fr amework is case-sensitive, unlike the RFC. As a result, you should always specif y schemes using lowercase letters. INTRODUCED IN: API Level 1 SEE ALSO: <action> <category> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/data-element.html Page 2 of 2

<grant-uri-permission> | Android Developers 29.04.09 0:44 <grant-uri-permission> SYNTAX: <grant-uri-permission android:path="string" android:pathPattern="string" android :pathPrefix="string" /> CONTAINED IN: <provider> DESCRIPTION: Specifies which data subsets of the parent content provider permission can be gr anted for. Data subsets are indicated by the path part of a content: URI. (The a uthority part of the URI identifies the content provider.) Granting permission i s a way of enabling clients of the provider that don't normally have permission to access its data to overcome that restriction on a one-time basis. If a conten t provider's grantUriPermissions attribute is "true", permission can be granted for any the data under the provider's purview. However, if that attribute is "fa lse", permission can be granted only to data subsets that are specified by this element. A provider can contain any number of <grant-uri-permission> elements. E ach one can specify only one path (only one of the three possible attributes). F or information on how permission is granted, see the <intent-filter> element's g rantUriPermissions attribute. ATTRIBUTES: android:path android:pathPrefix android:pathPattern A path identifying the data subset or subsets that permission can be granted for. The path attribute specifi es a complete path; permission can be granted only to the particular data subset identified by that path. The pathPrefix attribute specifies the initial part of a path; permission can be granted to all data subsets with paths that share tha t initial part. The pathPattern attribute specifies a complete path, but one tha t can contain the following wildcards: An asterisk ('*') matches a sequence of 0 to many occurrences of the immediately preceding character. A period followed b y an asterisk (".*") matches any sequence of 0 to many characters. Because '\' i s used as an escape character when the string is read from XML (before it is par sed as a pattern), you will need to double-escape: For example, a literal '*' wo uld be written as "\\*" and a literal '\' would be written as "\\\\". This is ba sically the same as what you would need to write if constructing the string in J ava code. For more information on these types of patterns, see the descriptions of PATTERN_LITERAL, PATTERN_PREFIX, and PATTERN_SIMPLE_GLOB in the PatternMatche r class. INTRODUCED IN: API Level 1 http://developer.android.com/guide/topics/manifest/grant-uri-permission-element. html Page 1 of 2

<grant-uri-permission> | Android Developers 29.04.09 0:44 SEE ALSO: the grantUriPermissions attribute of the <provider> element Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/grant-uri-permission-element. html Page 2 of 2

<instrumentation> | Android Developers 29.04.09 0:44 <instrumentation> SYNTAX: <instrumentation android:functionalTest=["true" | "false"] android:handleProfili ng=["true" | "false"] android:icon="drawable resource" android:label="string res ource" android:name="string" android:targetPackage="string" /> CONTAINED IN: <manifest> DESCRIPTION: Declares an Instrumentation class that enables you to monitor an application's i nteraction with the system. The Instrumentation object is instantiated before an y of the application's components. ATTRIBUTES: android:functionalTest Whether or not the Instrumentation class should run as a functional test "true" if it should, and "false" if not. The default value is "f alse". android:handleProfiling Whether or not the Instrumentation object will tu rn profiling on and off "true" if it determines when profiling starts and stops, and "false" if profiling continues the entire time it is running. A value of "t rue" enables the object to target profiling at a specific set of operations. The default value is "false". android:icon An icon that represents the Instrumentat ion class. This attribute must be set as a reference to a drawable resource. and roid:label A user-readable label for the Instrumentation class. The label can be set as a raw string or a reference to a string resource. android:name The name of the Instrumentation subclass. This should be a fully qualified class name (su ch as, "com.example.project.StringInstrumentation"). However, as a shorthand, if the first character of the name is a period, it is appended to the package name specified in the <manifest> element. There is no default. The name must be spec ified. introduced in: API Level 1 android:targetPackage The application that the Instrumentation object will run against. An application is identified by the pa ckage name assigned in its manifest file by the <manifest> element. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/instrumentation-element.html Page 1 of 1

<intent-filter> | Android Developers 29.04.09 0:44 <intent-filter> SYNTAX: <intent-filter android:icon="drawable resource" android:label="string resource" android:priority="integer" > . . . </intent-filter> CONTAINED IN: <activity> <activity-alias> <service> <receiver> MUST CONTAIN: <action> CAN CONTAIN: <category> <data> DESCRIPTION: Specifies the types of intents that an activity, service, or broadcast receiver can respond to. An intent filter declares the capabilities of its parent compone nt what an activity or service can do and what types of broadcasts a receiver ca n handle. It opens the component to receiving intents of the advertised type, wh ile filtering out those that are not meaningful for the component. Most of the c ontents of the filter are described by its <action>, <category>, and <data> sube lements. For a more detailed discussion of filters, see the separate Intents and Intent Filters document, as well as the Intents Filters section in the introduc tion. ATTRIBUTES: android:icon An icon that represents the parent activity, service, or broadcast receiver when that component is presented to the user as having the capability d escribed by the filter. This attribute must be set as a reference to a drawable resource containing the image definition. The default value is the icon set by t he parent component's icon attribute. If the parent does not specify an icon, th e default is the icon set by the <application> element. For more on intent filte r icons, see Icons and Labels in the introduction. android:label A user-readable label for the parent component. This label, rather than the one set by the pare nt component, is used when the component is presented to the user as having the capability described by the filter. The label should be set as a reference to a string resource, so that it can be localized like other strings in the user inte rface. However, as a convenience while you're developing the application, it can also be set as a raw http://developer.android.com/guide/topics/manifest/intent-filter-element.html Pa ge 1 of 2

<intent-filter> | Android Developers 29.04.09 0:44 user interface. However, as a convenience while you're developing the applicatio n, it can also be set as a raw string. The default value is the label set by the parent component. If the parent does not specify a label, the default is the la bel set by the <application> element's label attribute. For more on intent filte r labels, see Icons and Labels in the introduction. android:priority The priorit y that should be given to the parent component with regard to handling intents o f the type described by the filter. This attribute has meaning for both activiti es and broadcast receivers: It provides information about how able an activity i s to respond to an intent that matches the filter, relative to other activities that could also respond to the intent. When an intent could be handled by multip le activities with different priorities, Android will consider only those with h igher priority values as potential targets for the intent. It controls the order in which broadcast receivers are executed to receive broadcast messages. Those with higher priority values are called before those with lower values. (The orde r applies only to synchronous messages; it's ignored for asynchronous messages.) Use this attribute only if you really need to impose a specific order in which the broadcasts are received, or want to force Android to prefer one activity ove r others. The value must be an integer, such as "100". Higher numbers have a hig her priority. INTRODUCED IN: API Level 1 SEE ALSO: <action> <category> <data> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/intent-filter-element.html Page 2 of 2

<manifest> | Android Developers 29.04.09 0:44 <manifest> SYNTAX: <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="st ring" android:sharedUserId="string" android:sharedUserLabel="string resource" an droid:versionCode="integer" android:versionName="string" > . . . </manifest> CONTAINED IN: none MUST CONTAIN: <application> CAN CONTAIN: <instrumentation> <permission> <permission-group> <permission-tree> <uses-config uration> <uses-permission> <uses-sdk> DESCRIPTION: The root element of the AndroidManifest.xml file. It must contain an <applicatio n> element and specify xlmns:android and package attributes. ATTRIBUTES: xmlns:android Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android". package A full Java package na me for the application. The name should be unique. For example, applications pub lished by Google could have names in the form com.google.app.application_name. T he package name serves as a unique identifier for the application. It's also the default name for the application process (see the <application> element's proce ss process attribute) and the default task affinity of an activity (see the <act ivity> element's taskAffinity attribute). android:sharedUserId The name of a Lin ux user ID that will be shared with other applications. By default, Android assi gns each application its own unique user ID. However, if this attribute is set t o the same value for two or more applications, they will all share the same ID p rovided that they are also signed by the same certificate. http://developer.android.com/guide/topics/manifest/manifest-element.html Page 1 of 2

<manifest> | Android Developers 29.04.09 0:44 applications, they will all share the same ID provided that they are also signed by the same certificate. Application with the same user ID can access each othe r's data and, if desired, run in the same process. android:sharedUserLabel A use r-readable label for the shared user ID. The label must be set as a reference to a string resource; it cannot be a raw string. This attribute was introduced in API Level 3. It is meaningful only if the sharedUserId attribute is also set. an droid:versionCode An internal version number. This number is used only to determ ine whether one version is more recent than another, with higher numbers indicat ing more recent versions. This is not the version number shown to users; that nu mber is set by the versionName attribute. The value must be set as an integer, s uch as "100". You can define it however you want, as long as each successive ver sion has a higher number. For example, it could be a build number. Or you could translate a version number in "x.y" format to an integer by encoding the "x" and "y" separately in the lower and upper 16 bits. Or you could simply increase the number by one each time a new version is released. android:versionName The vers ion number shown to users. This attribute can be set as a raw string or as a ref erence to a string resource. The string has no other purpose than to be displaye d to users. The versionCode attribute holds the significant version number used internally. INTRODUCED IN: API Level 1 for all attributes except for sharedUserLabel, which was added in le vel 3. SEE ALSO: <application> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/manifest-element.html Page 2 of 2

<meta-data> | Android Developers 29.04.09 0:44 <meta-data> SYNTAX: <meta-data android:name="string" android:resource="resource specification" andro id:value="string" /> CONTAINED IN: <activity> <activity-alias> <service> <receiver> DESCRIPTION: A name-value pair for an item of additional, arbitrary data that can be supplied to the parent component. A component element can contain any number of <meta-da ta> subelements. The values from all of them are collected in a single Bundle ob ject and made available to the component as the PackageItemInfo.metaData field. Ordinary values are specified through the value attribute. However, to assign a resource ID as the value, use the resource attribute instead. For example, the f ollowing code assigns whatever value is stored in the @string/kangaroo resource to the "zoo" name: <meta-data android:name="zoo" android:value="@string/kangaroo " /> On the other hand, using the resource attribute would assign "zoo" the nume ric ID of the resource, not the value stored in the resource: <meta-data android :name="zoo" android:resource="@string/kangaroo" /> It is highly recommended that you avoid supplying related data as multiple separate <meta-data> entries. Inst ead, if you have complex data to associate with a component, store it as a resou rce and use the resource attribute to inform the component of its ID. ATTRIBUTES: android:name A unique name for the item. To ensure that the name is unique, use a Java-style naming convention for example, "com.example.project.activity.fred". android:resource A reference to a resource. The ID of the resource is the value assigned to the item. The ID can be retrieved from the meta-data Bundle by the Bundle.getInt() method. android:value The value assigned to the item. The data t ypes that can be assigned as values and the Bundle methods that components use t o retrieve those values are listed in the following table: http://developer.android.com/guide/topics/manifest/meta-data-element.html Page 1 of 2

<meta-data> | Android Developers 29.04.09 0:44 Type String value, using double backslashes (\\) to escape characters such as "\ \n" and "\\uxxxxx" for a Unicode character. Integer value, such as "100" Boolean value, either "true" or "false" Color value, in the form "#rgb", "#argb", "#rrg gbb", or "#aarrggbb" Float value, such as "1.23" INTRODUCED IN: Bundle method getString() getInt() getBoolean() getString() getFloat() API Level 1 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/meta-data-element.html Page 2 of 2

<permission> | Android Developers 29.04.09 0:44 <permission> SYNTAX: <permission android:description="string resource" android:icon="drawable resourc e" android:label="string resource" android:name="string" android:permissionGroup ="string" android:protectionLevel=["normal" | "dangerous" | "signature" | "signa tureOrSystem"] /> CONTAINED IN: <manifest> DESCRIPTION: Declares a security permission that can be used to limit access to specific comp onents or features of this or other applications. See the Permissions section in the introduction, and the Security and Permissions document for more informatio n on how permissions work. ATTRIBUTES: android:description A user-readable description of the permission, longer and mo re informative than the label. It may be displayed to explain the permission to the user for example, when the user is asked whether to grant the permission to another application. This attribute must be set as a reference to a string resou rce; unlike the label attribute, it cannot be a raw string. android:icon A refer ence to a drawable resource for an icon that represents the permission. android: label A name for the permission, one that can be displayed to users. As a conven ience, the label can be directly set as a raw string while you're developing the application. However, when the application is ready to be published, it should be set as a reference to a string resource, so that it can be localized like oth er strings in the user interface. android:name The name of the permission. This is the name that will be used in code to refer to the permission for example, in a <uses-permission> element and the permission attributes of application compon ents. The name must be unique, so it should use Java-style scoping for example, "com.example.project.PERMITTED_ACTION". android:permissionGroup Assigns this per mission to a group. The value of this attribute is the name of the group, which must be declared with the <permission-group> element in this or another applicat ion. If this attribute is not set, the permission does not belong to a group. http://developer.android.com/guide/topics/manifest/permission-element.html Page 1 of 2

<permission> | Android Developers 29.04.09 0:44 android:protectionLevel Characterizes the potential risk implied in the permissi on and indicates the procedure the system should follow when determining whether or not to grant the permission to an application requesting it. The value can b e set to one of the following strings: Value "normal" Meaning The default value. A lower-risk permission that gives requesting applications access to isolated a pplication-level features, with minimal risk to other applications, the system, or the user. The system automatically grants this type of permission to a reques ting application at installation, without asking for the user's explicit approva l (though the user always has the option to review these permissions before inst alling). A higher-risk permission that would give a requesting application acces s to private user data or control over the device that can negatively impact the user. Because this type of permission introduces potential risk, the system may not automatically grant it to the requesting application. For example, any dang erous permissions requested by an application may be displayed to the user and r equire confirmation before proceeding, or some other approach may be taken to av oid the user automatically allowing the use of such facilities. A permission tha t the system grants only if the requesting application is signed with the same c ertificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user's explicit approval. A permission that the system grants only to applications that are in the Android system image or that are signed wi th the same certificates as those in the system image. Please avoid using this o ption, as the signature protection level should be sufficient for most needs and works regardless of exactly where applications are installed. The "signatureOrS ystem" permission is used for certain special situations where multiple vendors have applications built into a system image and need to share specific features explicitly because they are being built together. "dangerous" "signature" "signatureOrSystem" INTRODUCED IN: API Level 1 SEE ALSO: <uses-permission> <permission-tree> <permission-group> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/permission-element.html Page 2 of 2

<permission-group> | Android Developers 29.04.09 0:45 <permission-group> SYNTAX: <permission-group android:description="string resource" android:icon="drawable r esource" android:label="string resource" android:name="string" /> CONTAINED IN: <manifest> DESCRIPTION: Declares a name for a logical grouping of related permissions. Individual permis sion join the group through the permissionGroup attribute of the <permission> el ement. Members of a group are presented together in the user interface. Note tha t this element does not declare a permission itself, only a category in which pe rmissions can be placed. See the <permission> element for element for informatio n on declaring permissions and assigning them to groups. ATTRIBUTES: android:description User-readable text that describes the group. The text should be longer and more explanatory than the label. This attribute must be set as a reference to a string resource. Unlike the label attribute, it cannot be a raw s tring. android:icon An icon representing the permission. This attribute must be set as a reference to a drawable resource containing the image definition. andro id:label A user-readable name for the group. As a convenience, the label can be directly set as a raw string while you're developing the application. However, w hen the application is ready to be published, it should be set as a reference to a string resource, so that it can be localized like other strings in the user i nterface. android:name The name of the group. This is the name that can be assig ned to a <permission> element's <permissionGroup> attribute. INTRODUCED IN: API Level 1 SEE ALSO: <permission> <permission-tree> <uses-permission> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/permission-group-element.html Page 1 of 1

<permission-tree> | Android Developers 29.04.09 0:45 <permission-tree> SYNTAX: <permission-tree android:icon="drawable resource" android:label="string resource " ] android:name="string" /> CONTAINED IN: <manifest> DESCRIPTION: Declares the base name for a tree of permissions. The application takes ownershi p of all names within the tree. It can dynamically add new permissions to the tr ee by calling PackageManager.addPermission(). Names within the tree are separate d by periods ('.'). For example, if the base name is com.example.project.taxes, permissions like the following might be added: com.example.project.taxes.CALCULA TE com.example.project.taxes.deductions.MAKE_SOME_UP com.example.project.taxes.d eductions.EXAGGERATE Note that this element does not declare a permission itself , only a namespace in which further permissions can be placed. See the <permissi on> element for information on declaring permissions. ATTRIBUTES: android:icon An icon representing all the permissions in the tree. This attribut e must be set as a reference to a drawable resource containing the image definit ion. android:label A user-readable name for the group. As a convenience, the lab el can be directly set as a raw string for quick and dirty programming. However, when the application is ready to be published, it should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. android:name The name that's at the base of the permission tree. It serves as a prefix to all permission names in the tree. Java-style scoping shoul d be used to ensure that the name is unique. The name must have more than two pe riod-separated seqments in its path for example, com.example.base is OK, but com .example is not. INTRODUCED IN: API Level 1 SEE ALSO: <permission> <permission-group> <uses-permission> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/permission-tree-element.html Page 1 of 1

<provider> | Android Developers 29.04.09 0:45 <provider> SYNTAX: <provider android:authorities="list" android:enabled=["true" | "false"] android: exported=["true" | "false"] android:grantUriPermissions=["true" | "false"] andro id:icon="drawable resource" android:initOrder="integer" android:label="string re source" android:multiprocess=["true" | "false"] android:name="string" android:pe rmission="string" android:process="string" android:readPermission="string" andro id:syncable=["true" | "false"] android:writePermission="string" > . . . </provid er> CONTAINED IN: <application> CAN CONTAIN: <meta-data> <grant-uri-permission> DESCRIPTION: Declares a content provider a subclass of ContentProvider that supplies structur ed access to data managed by the application. All content providers that are par t of the application must be represented by <provider> elements in the manifest file. The system cannot see, and therefore will not run, any that are not declar ed. (You need to declare only those content providers that you develop as part o f your application, not those developed by others that your application uses.) T he Android system identifies content providers by the authority part of a conten t: URI. For example, suppose that the following URI is passed to ContentResolver .query(): content://com.example.project.healthcareprovider/nurses/rn The content : scheme identifies the data as belonging to a content provider and the authorit y (com.example.project.healthcareprovider) identifies the particular provider. T he authority therefore must be unique. Typically, as in this example, it's the f ully qualified name of a ContentProvider subclass. The path part of a URI may be used by a content provider to identify particular data subsets, but those paths are not declared in the manifest. For information on using and developing conte nt providers, see a separate document, Content Providers. ATTRIBUTES: android:authorities A list of one or more URI authorities that identify data und er the purview of the content provider. Multiple authorities are listed by separ ating their names with a semicolon. To avoid conflicts, authority names should u se a Java-style naming convention (such as com.example.provider.cartoonprovider) . Typically, it's the name of the ContentProvider subclass. There is no default. At least one authority must be specified. android:enabled http://developer.android.com/guide/topics/manifest/provider-element.html Page 1 of 3

<provider> | Android Developers 29.04.09 0:45 Whether or not the content provider can be instantiated by the system "true" if it can be, and "false" if not. The default value is "true". The <application> el ement has its own enabled attribute that applies to all application components, including content providers. The <application> and <provider> attributes must bo th be "true" (as they both are by default) for the content provider to be enable d. If either is "false", the provider is disabled; it cannot be instantiated. an droid:exported Whether or not the content provider can be used by components of other applications "true" if it can be, and "false" if not. If "false", the prov ider is available only to components of the same application or applications wit h the same user ID. The default value is "true". You can export a content provid er but still limit access to it with the permission attribute. android:grantUriP ermissions Whether or not those who ordinarily would not have permission to acce ss the content provider's data can be granted permission to do so, temporarily o vercoming the restriction imposed by the readPermission, writePermission, and pe rmission attributes "true" if permission can be granted, and "{@ code false}" if not. If "true", permission can be granted to any of the content provider's data . If "false", permission can be granted only to the data subsets listed in <gran t-uri-permission> subelements, if any. The default value is "false". Granting pe rmission is a way of giving an application component one-time access to data pro tected by a permission. For example, when an e-mail message contains an attachme nt, the mail application may call upon the appropriate viewer to open it, even t hough the viewer doesn't have general permission to look at all the content prov ider's data. In such cases, permission is granted by FLAG_GRANT_READ_URI_PERMISS ION and FLAG_GRANT_WRITE_URI_PERMISSION flags in the Intent object that activate s the component. For example, the mail application might put FLAG_GRANT_READ_URI _PERMISSION in the Intent passed to Context.startActivity(). The permission is s pecific to the URI in the Intent. If you enable this feature, either by setting this attribute to "true" or by defining <grant-uripermission> subelements, you m ust call Context.revokeUriPermission() when a covered URI is deleted from the pr ovider. See also the <grant-uri-permission> element. android:icon An icon repres enting the content provider. This attribute must be set as a reference to a draw able resource containing the image definition. If it is not set, the icon specif ied for the application as a whole is used instead (see the <application> elemen t's icon attribute). android:initOrder The order in which the content provider s hould be instantiated, relative to other content providers hosted by the same pr ocess. When there are dependencies among content providers, setting this attribu te for each of them ensures that they are created in the order required by those dependencies. The value is a simple integer, with higher numbers being initiali zed first. android:label A user-readable label for the content provided. If this attribute is not set, the label set for the application as a whole is used inst ead (see the <application> element's label attribute). The label should be set a s a reference to a string resource, so that it can be localized like other strin gs in the user interface. However, as a convenience while you're developing the application, it can also be set as a raw string. android:multiprocess Whether or not an instance of the content provider can be created in every client process "true" if instances can run in multiple processes, and "false" if not. The defau lt value is "false". Normally, a content provider is instantiated in the process of the application that defined it. However, if this flag is set to "true", the system can create an instance in every process where there's a client that want s to interact withit, thus avoiding the overhead of interprocess communication. http://developer.android.com/guide/topics/manifest/provider-element.html Page 2 of 3

<provider> | Android Developers 29.04.09 0:45 android:name The name of the class that implements the content provider, a subcl ass of ContentProvider. This should be a fully qualified class name (such as, "c om.example.project.TransportationProvider"). However, as a shorthand, if the fir st character of the name is a period, it is appended to the package name specifi ed in the <manifest> element. There is no default. The name must be specified. a ndroid:permission The name of a permission that clients must have to read or wri te the content provider's data. This attribute is a convenient way of setting a single permission for both reading and writing. However, the readPermission and writePermission attributes take precedence over this one. If the readPermission attribute is also set, it controls access for querying the content provider. And if the writePermission attribute is set, it controls access for modifying the p rovider's data. For more information on permissions, see the Permissions section in the introduction and a separate document, Security and Permissions. android: process The name of the process in which the content provider should run. Normal ly, all components of an application run in the default process created for the application. It has the same name as the application package. The <application> element's process attribute can set a different default for all components. But each component can override the default with its own process attribute, allowing you to spread your application across multiple processes. If the name assigned to this attribute begins with a colon (':'), a new process, private to the appli cation, is created when it's needed and the activity runs in that process. If th e process name begins with a lowercase character, the activity will run in a glo bal process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage . android:readPermission A permission that clients must have to query the conten t provider. See also the permission and writePermission attributes. android:sync able Whether or not the data under the content provider's control is to be synch ronized with data on a server "true" if it is to be synchronized, and "{@ code f alse}" if not. android:writePermission A permission that clients must have to ma ke changes to the data controlled by the content provider. See also the permissi on and readPermission attributes. INTRODUCED IN: API Level 1 SEE ALSO: Content Providers Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/provider-element.html Page 3 of 3

<receiver> | Android Developers 29.04.09 0:45 <receiver> SYNTAX: <receiver android:enabled=["true" | "false"] android:exported=["true" | "false"] android:icon="drawable resource" android:label="string resource" android:name=" string" android:permission="string" android:process="string" > . . . </receiver> CONTAINED IN: <application> CAN CONTAIN: <intent-filer> <meta-data> DESCRIPTION: Declares a broadcast receiver (a BroadcastReceiver subclass) as one of the appli cation's components. Broadcast receivers enable applications to receive intents that are broadcast by the system or by other applications, even when other compo nents of the application are not running. There are two ways to make a broadcast receiver known to the system: One is declare it in the manifest file with this element. The other is to create the receiver dynamically in code and register it with the Context.registerReceiver() method. See the BroadcastReceiver class des cription for more on dynamically created receivers. ATTRIBUTES: android:enabled Whether or not the broadcast receiver can be instantiated by the system "true" if it can be, and "false" if not. The default value is "true". Th e <application> element has its own enabled attribute that applies to all applic ation components, including broadcast receivers. The <application> and <receiver > attributes must both be "true" for the broadcast receiver to be enabled. If ei ther is "false", it is disabled; it cannot be instantiated. android:exported Whe ther or not the broadcast receiver can receive messages from sources outside its application "true" if it can, and "false" if not. If "false", the only messages the broadcast receiver can receive are those sent by components of the same app lication or applications with the same user ID. The default value depends on whe ther the broadcast receiver contains intent filters. The absence of any filters means that it can be invoked only by Intent objects that specify its exact class name. This implies that the receiver is intended only for application-internal use (since others would not normally know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the broadcast receiver is intended to receive intents broadcast by the system or other applications, so the default value is "true". http://developer.android.com/guide/topics/manifest/receiver-element.html Page 1 of 2

<receiver> | Android Developers 29.04.09 0:45 This attribute is not the only way to limit a broadcast receiver's external expo sure. You can also use a permission to limit the external entities that can send it messages (see the permission attribute). android:icon An icon representing t he broadcast receiver. This attribute must be set as a reference to a drawable r esource containing the image definition. If it is not set, the icon specified fo r the application as a whole is used instead (see the <application> element's ic on attribute). The broadcast receiver's icon whether set here or by the <applica tion> element is also the default icon for all the receiver's intent filters (se e the <intent-filter> element's icon attribute). android:label A user-readable l abel for the broadcast receiver. If this attribute is not set, the label set for the application as a whole is used instead (see the <application> element's lab el attribute). The broadcast receiver's label whether set here or by the <applic ation> element is also the default label for all the receiver's intent filters ( see the <intent-filter> element's label attribute). The label should be set as a reference to a string resource, so that it can be localized like other strings in the user interface. However, as a convenience while you're developing the app lication, it can also be set as a raw string. android:name The name of the class that implements the broadcast receiver, a subclass of BroadcastReceiver. This s hould be a fully qualified class name (such as, "com.example.project.ReportRecei ver"). However, as a shorthand, if the first character of the name is a period ( for example, ". ReportReceiver"), it is appended to the package name specified i n the <manifest> element. There is no default. The name must be specified. andro id:permission The name of a permission that broadcasters must have to send a mes sage to the broadcast receiver. If this attribute is not set, the permission set by the <application> element's permission attribute applies to the broadcast re ceiver. If neither attribute is set, the receiver is not protected by a permissi on. For more information on permissions, see the Permissions section in the intr oduction and a separate document, Security and Permissions. android:process The name of the process in which the broadcast receiver should run. Normally, all co mponents of an application run in the default process created for the applicatio n. It has the same name as the application package. The <application> element's process attribute can set a different default for all components. But each compo nent can override the default with its own process attribute, allowing you to sp read your application across multiple processes. If the name assigned to this at tribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the broadcast receiver runs in that process. If th e process name begins with a lowercase character, the receiver will run in a glo bal process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage . INTRODUCED IN: API Level 1 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/receiver-element.html Page 2 of 2

<service> | Android Developers 29.04.09 0:45 <service> SYNTAX: <service android:enabled=["true" | "false"] android:exported[="true" | "false"] android:icon="drawable resource" android:label="string resource" android:name="s tring" android:permission="string" android:process="string" > . . . </service> CONTAINED IN: <application> CAN CONTAIN: <intent-filer> <meta-data> DESCRIPTION: Declares a service (a Service subclass) as one of the application's components. Unlike activities, services lack a visual user interface. They're used to implem ent long-running background operations or a rich communications API that can be called by other applications. All services must be represented by <service> elem ents in the manifest file. Any that are not declared there will not be seen by t he system and will never be run. ATTRIBUTES: android:enabled Whether or not the service can be instantiated by the system "tr ue" if it can be, and "false" if not. The default value is "true". The <applicat ion> element has its own enabled attribute that applies to all application compo nents, including services. The <application> and <service> attributes must both be "true" (as they both are by default) for the service to be enabled. If either is "false", the service is disabled; it cannot be instantiated. android:exporte d Whether or not components of other applications can invoke the service or inte ract with it "true" if they can, and "false" if not. When the value is "false", only components of the same application or applications with the same user ID ca n start the service or bind to it. The default value depends on whether the serv ice contains intent filters. The absence of any filters means that it can be inv oked only by specifying its exact class name. This implies that the service is i ntended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the pr esence of at least one filter implies that the service is intended for external use, so the default value is "true". This attribute is not the only way to limit the exposure of a service to other applications. You can also use a permission to limit the external entities that can interact with the service (see the permi ssion attribute). android:icon An icon representing the service. This attribute must be set as a reference to a drawable resource containing the image definitio n. If it is not set, the icon specified for the application as a whole is used i nstead (see the <application> element's icon attribute). http://developer.android.com/guide/topics/manifest/service-element.html Page 1 o f 2

<service> | Android Developers 29.04.09 0:45 The service's icon whether set here or by the <application> element is also the default icon for all the service's intent filters (see the <intent-filter> eleme nt's icon attribute). android:label A name for the service that can be displayed to users. If this attribute is not set, the label set for the application as a whole is used instead (see the <application> element's label attribute). The ser vice's label whether set here or by the <application> element is also the defaul t label for all the service's intent filters (see the <intent-filter> element's label attribute). The label should be set as a reference to a string resource, s o that it can be localized like other strings in the user interface. However, as a convenience while you're developing the application, it can also be set as a raw string. android:name The name of the Service subclass that implements the se rvice. This should be a fully qualified class name (such as, "com.example.projec t.RoomService"). However, as a shorthand, if the first character of the name is a period (for example, ".RoomService"), it is appended to the package name speci fied in the <manifest> element. There is no default. The name must be specified. android:permission The name of a permission that that an entity must have in or der to launch the service or bind to it. If a caller of startService(), bindServ ice(), or stopService(), has not been granted this permission, the method will n ot work and the Intent object will not be delivered to the service. If this attr ibute is not set, the permission set by the <application> element's permission a ttribute applies to the service. If neither attribute is set, the service is not protected by a permission. For more information on permissions, see the Permiss ions section in the introduction and a separate document, Security and Permissio ns. android:process The name of the process where the service is to run. Normall y, all components of an application run in the default process created for the a pplication. It has the same name as the application package. The <application> e lement's process attribute can set a different default for all components. But c omponent can override the default with its own process attribute, allowing you t o spread your application across multiple processes. If the name assigned to thi s attribute begins with a colon (':'), a new process, private to the application , is created when it's needed and the service runs in that process. If the proce ss name begins with a lowercase character, the service will run in a global proc ess of that name, provided that it has permission to do so. This allows componen ts in different applications to share a process, reducing resource usage. SEE ALSO: <application> <activity> INTRODUCED IN: API Level 1 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/service-element.html Page 2 of 2

<uses-configuration> | Android Developers 29.04.09 0:45 <uses-configuration> SYNTAX: <uses-configuration android:reqFiveWayNav=["true" | "false"] android:reqHardKeyb oard=["true" | "false"] android:reqKeyboardType=["undefined" | "nokeys" | "qwert y" | "twelvekey"] android:reqNavigation=["undefined" | "nonav" | "dpad" | "track ball" | "wheel"] android:reqTouchScreen=["undefined" | "notouch" | "stylus" | "f inger"] /> CONTAINED IN: <manifest> DESCRIPTION: Indicates what hardware and software features the application requires. For exam ple, an application might specify that it requires a physical keyboard or a part icular navigation device, like a trackball. The specification is used to avoid i nstalling the application on devices where it will not work. If an application c an work with different device configurations, it should include separate <usesco nfiguration> declarations for each one. Each declaration must be complete. For e xample, if an application requires a five-way navigation control, a touch screen that can be operated with a finger, and either a standard QWERTY keyboard or a numeric 12-key keypad like those found on most phones, it would specify these re quirements with two <uses-configuration> elements as follows: <uses-configuratio n android:reqFiveWayNav="true" android:reqTouchScreen="finger" android:reqKeyboa rdType="qwerty" /> <uses-configuration android:reqFiveWayNav="true" android:reqT ouchScreen="finger" android:reqKeyboardType="twelvekey" /> ATTRIBUTES: android:reqFiveWayNav Whether or not the application requires a five-way navigat ion control "true" if it does, and "false" if not. A five-way control is one tha t can move the selection up, down, right, or left, and also provides a way of in voking the current selection. It could be a D-pad (directional pad), trackball, or other device. If an application requires a directional control, but not a con trol of a particular type, it can set this attribute to "true" and ignore the re qNavigation attribute. However, if it requires a particular type of directional control, it can ignore this attribute and set reqNavigation instead. android:req HardKeyboard Whether or not the application requires a hardware keyboard "true" if it does, and "false" if not. android:reqKeyboardType The type of keyboard the application requires, if any at all. This attribute does not distinguish betwee n hardware and software keyboards. If a hardware keyboard of a certain type is r equired, specify the type here and also set the reqHardKeyboard attribute to "tr ue". The value must be one of the following strings: http://developer.android.com/guide/topics/manifest/uses-configuration-element.ht ml Page 1 of 2

<uses-configuration> | Android Developers 29.04.09 0:45 Value "undefined" "nokeys" "qwerty" "twelvekey" Description The application does not require a keyboard. (A keyboard requirement is not defined.) This is the default value. The application does not require a keyboard. The application requires a standard QWERTY keyboard. The application r equires a twelve-key keypad, like those on most phones with keys for the digits from 0 through 9 plus star (*) and pound (#) keys. android:reqNavigation The navigation device required by the application, if any. The value must be one of the following strings: Value "undefined" "nonav" "dpad " "trackball" "wheel" Description The application does not require any type of n avigation control. (The navigation requirement is not defined.) This is the defa ult value. The application does not require a navigation control. The applicatio n requires a D-pad (directional pad) for navigation. The application requires a trackball for navigation. The application requires a navigation wheel. If an application requires a navigational control, but the exact type of control doesn't matter, it can set the reqFiveWayNav attribute to "true" rather than se t this one. android:reqTouchScreen The type of touch screen the application requ ires, if any at all. The value must be one of the following strings: Value "unde fined" "notouch" "stylus" "finger" INTRODUCED IN: Description The application doesn't require a touch screen. (The touch screen re quirement is undefined.) This is the default value. The application doesn't requ ire a touch screen. The application requires a touch screen that's operated with a stylus. The application requires a touch screen that can be operated with a f inger. API Level 3 SEE ALSO: configChanges attribute of the <activity> element Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/uses-configuration-element.ht ml Page 2 of 2

<uses-library> | Android Developers 29.04.09 0:45 <uses-library> SYNTAX: <uses-library android:name="string" /> CONTAINED IN: <application> DESCRIPTION: Specifies a shared library that the application must be linked against. This ele ment tells the system to include the library's code in the class loader for the package. All of the android packages (such as android.app, android.content, andr oid.view, and android.widget) are in the default library that all applications a re automatically linked against. However, some packages (such as maps and awt ar e in separate libraries that are not automatically linked. Consult the documenta tion for the packages you're using to determine which library contains the packa ge code. ATTRIBUTES: android:name The name of the library. INTRODUCED IN: API Level 1 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/uses-library-element.html Page 1 of 1

<uses-permission> | Android Developers 29.04.09 0:46 <uses-permission> SYNTAX: <uses-permission android:name="string" /> CONTAINED IN: <manifest> DESCRIPTION: Requests a permission that the application must be granted in order for it to op erate correctly. Permissions are granted when the application is installed, not while it's running. For more information on permissions, see the Permissions sec tion in the introduction and the separate Security and Permissions document. A l ist of permissions defined by the base platform can be found at android.Manifest .permission. ATTRIBUTES: android:name The name of the permission. It can be a permission defined by the a pplication with the <permission> element, a permission defined by another applic ation, or one of the standard system permissions, such as "android.permission.CA MERA" or "android.permission.READ_CONTACTS". As these examples show, a permissio n name typically includes the package name as a prefix. INTRODUCED IN: API Level 1 SEE ALSO: <permission> Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/uses-permission-element.html Page 1 of 1

<uses-sdk> | Android Developers 29.04.09 0:46 <uses-sdk> SYNTAX: <uses-sdk android:minSdkVersion="integer" /> CONTAINED IN: <manifest> DESCRIPTION: Lets you express an application's compatibility with one or more versions of the Android platform, by means of an API Level integer. The API Level expressed by an application will be compared to the API Level of a given Android system, whic h may vary among different Android devices. To declare your application's minimu m API Level compatibility, use the minSdkVersion attribute. The default level is 1. For more information on the API level, see the Specifying Minimum System API Version section of Versioning Your Applications. ATTRIBUTES: android:minSdkVersion An integer designating the minimum level of the Android AP I that's required for the application to run. Despite its name, this attribute s pecifies the API Level, not the version number of the SDK (software development kit). The API Level is always a single integer; the SDK version may be split int o major and minor components (such as 1.5). You cannot derive the API Level from the SDK version number (for example, it is not the same as the major version or the sum of the major and minor versions). To learn what the API Level is, check the notes that came with the SDK you're using. Prior to installing an applicati on, the Android system checks the value of this attribute and allows the install ation only if the API Level is less than or equal to the API Level used by the s ystem itself. If you do not declare this attribute, then a value of "1" is assum ed, which indicates that your application is compatible with all versions of And roid. If your application is not universally compatible (for instance if it uses APIs introduced in Android 1.5) and you have not declared the proper minSdkVers ion, then when installed on a system with a lower API Level, the application wil l crash during runtime. For this reason, be certain to declare the appropriate A PI Level in the minSdkVersion attribute. INTRODUCED IN: API Level 1 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/manifest/uses-sdk-element.html Page 1 of 1

Graphics | Android Developers 29.04.09 0:49 Graphics Android graphics are powered by a custom 2D graphics library and OpenGL ES 1.0 f or high performance 3D graphics. The most common 2D graphics APIs can be found i n the drawable package. OpenGL APIs are available from the Khronos OpenGL ES pac kage, plus some Android OpenGL utilities. When starting a project, it's importan t to consider exactly what your graphical demands will be. Varying graphical tas ks are best accomplished with varying techniques. For example, graphics and anim ations for a rather static application should be implemented much differently th an graphics and animations for an interactive game or 3D rendering. Here, we'll discuss a few of the options you have for drawing graphics on Android, and which tasks they're best suited for. If you're specifically looking for information o n drawing 3D graphics, this page won't help a lot. However, the information belo w, on Drawing with a Canvas (and the section on SurfaceView), will give you a qu ick idea of how you should draw to the View hierarchy. For more information on A ndroid's 3D graphic utilities (provided by the OpenGL ES API), read 3D with Open GL and refer to other OpenGL documentation. Consider your Options When drawing 2D graphics, you'll typically do so in one of two ways: a. Draw you r graphics or animations into a View object from your layout. In this manner, th e drawing (and any animation) of your graphics is handled by the system's normal View hierarchy drawing process you simply define the graphics to go inside the View. b. Draw your graphics directly to a Canvas. This way, you personally call the appropriate class's draw() method (passing it your Canvas), or one of the Ca nvas draw...() methods (like drawPicture()). In doing so, you are also in contro l of any animation. Option "a," drawing to a View, is your best choice when you want to draw simple graphics that do not need to change dynamically and are not part of a performance-intensive game. For example, you should draw your graphics into a View when you want to display a static graphic or predefined animation, within an otherwise static application. Read Simple Graphics Inside a View. Opti on "b," drawing to a Canvas, is better when you're application needs to regularl y re-draw itself. Basically, any video game should be drawing to the Canvas on i ts own. However, there's more than one way to do this: In the same thread as you r UI Activity, wherein you create a custom View component in your layout, call i nvalidate() and then handle the onDraw() callback.. Or, in a separate thread, wh erein you manage a SurfaceView and perform draws to the Canvas as fast as your t hread is capable (you do not need to request invalidate()). ...Begin by reading Draw with a Canvas. Simple Graphics Inside a View http://developer.android.com/guide/topics/graphics/index.html Page 1 of 3

Graphics | Android Developers 29.04.09 0:49 If you'll be drawing some simple graphics (images, shapes, colors, pre-defined a nimations, etc.), then you should probably just draw to the background of a View or to the content of an ImageView in your layout. In this case, you can skip th e rest of this document and learn how to draw graphics and animations in the 2D Graphics document. Draw with a Canvas When you're writing an application in which you would like to perform specialize d drawing and/or control the animation of graphics, you should do so by drawing through a Canvas. A Canvas works for you as a pretense, or interface, to the act ual surface upon which your graphics will be drawn it holds all of your "draw" c alls. Via the Canvas, your drawing is actually performed upon an underlying Bitm ap, which is placed into the window. In the event that you're drawing within the onDraw() callback method, the Canvas is provided for you and you need only plac e your drawing calls upon it. You can also acquire a Canvas from SurfaceHolder.l ockCanvas(), when dealing with a SurfaceView object. (Both of these scenarios ar e discussed in the following sections.) However, if you need to create a new Can vas, then you must define the Bitmap upon which drawing will actually be perform ed. The Bitmap is always required for a Canvas. You can set up a new Canvas like this: Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); Now your Canvas will draw onto the defined Bitmap. After dra wing upon it with the Canvas, you can then carry your Bitmap to another Canvas w ith one of the Canvas.drawBitmap(Bitmap,...) methods. It's recommended that you ultimately draw your final graphics through a Canvas offered to you by View.onDr aw() or SurfaceHolder.lockCanvas() (see the following sections). The Canvas clas s has its own set of drawing methods that you can use, like drawBitmap(...), dra wRect(...), drawText(...), and many more. Other classes that you might use also have draw() methods. For example, you'll probably have some Drawable objects tha t you want to put on the Canvas. Drawable has its own draw() method that takes y our Canvas as an arguement. On a View If you're application does not require a significant amount of processing or fra me-rate speed (perhaps for a chess game, a snake game, or another slowly-animate d application), then you should consider creating a custom View component and dr awing with a Canvas in View.onDraw(). The most convenient aspect of doing so is that the Android framework will provide you with a pre-defined Canvas to which y ou will place your drawing calls. To start, extend the View class (or descendent thereof) and define the onDraw() callback method. This method will be called by the Android framework to request that your View draw itself. This is where you will perform all your calls to draw through the Canvas, which is passed to you t hrough the onDraw() callback. The Android framework will only call onDraw() as n ecessary. Each time that your application is prepared to be drawn, you must requ est your View be invalidated by calling invalidate(). This indicates that you'd like your View to be drawn and Android will then call your onDraw() method (thou gh is not guaranteed that the callback will be instantaneous). Inside your View component's onDraw(), use the Canvas given to you for all your drawing, using va rious Canvas.draw...() methods, or other class draw() methods that take your Can vas as an argument. Once your onDraw() is complete, the Android framework will u se your Canvas to draw a Bitmap handled by the system. Note: In order to request an invalidate from a thread other than your main Activity's thread, you must ca ll postInvalidate(). Also read Building Custom Components for a guide to extendi ng a View class, and 2D Graphics: Drawables for information on using Drawable ob jects like images from your resources and other primitive shapes. http://developer.android.com/guide/topics/graphics/index.html

Page 2 of 3

Graphics | Android Developers 29.04.09 0:49 For a sample application, see the Snake game, in the SDK samples folder: <your-s dkdirectory>/samples/Snake/. On a SurfaceView The SurfaceView is a special subclass of View that offers a dedicated drawing su rface within the View hierarchy. The aim is to offer this drawing surface to an application's secondary thread, so that the application isn't required to wait u ntil the system's View hierarchy is ready to draw. Instead, a secondary thread t hat has reference to a SurfaceView can draw to its own Canvas at its own pace. T o begin, you need to create a new class that extends SurfaceView. The class shou ld also implement SurfaceHolder.Callback. This subclass is an interface that wil l notify you with information about the underlying Surface, such as when it is c reated, changed, or destroyed. These events are important so that you know when you can start drawing, whether you need to make adjustments based on new surface properties, and when to stop drawing and potentially kill some tasks. Inside yo ur SurfaceView class is also a good place to define your secondary Thread class, which will perform all the drawing procedures to your Canvas. Instead of handli ng the Surface object directly, you should handle it via a SurfaceHolder. So, wh en your SurfaceView is initialized, get the SurfaceHolder by calling getHolder() . You should then notify the SurfaceHolder that you'd like to receive SurfaceHol der callbacks (from SurfaceHolder.Callback) by calling addCallback() (pass it th is). Then override each of the SurfaceHolder.Callback methods inside your Surfac eView class. In order to draw to the Surface Canvas from within your second thre ad, you must pass the thread your SurfaceHandler and retrieve the Canvas with lo ckCanvas(). You can now take the Canvas given to you by the SurfaceHolder and do your necessary drawing upon it. Once you're done drawing with the Canvas, call unlockCanvasAndPost(), passing it your Canvas object. The Surface will now draw the Canvas as you left it. Perform this sequence of locking and unlocking the ca nvas each time you want to redraw. Note: On each pass you retrieve the Canvas fr om the SurfaceHolder, the previous state of the Canvas will be retained. In orde r to properly animate your graphics, you must re-paint the entire surface. For e xample, you can clear the previous state of the Canvas by filling in a color wit h drawColor() or setting a background image with drawBitmap(). Otherwise, you wi ll see traces of the drawings you previously performed. For a sample application , see the Lunar Landar game, in the SDK samples folder: <your-sdkdirectory>/samp les/LunarLander/. Or, browse the source in the Sample Code section. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/graphics/index.html Page 3 of 3

2D Graphics | Android Developers 29.04.09 0:49 2D and 3D Graphics > 2D Graphics Android offers a custom 2D graphics library for drawing and animating shapes and images. The android.graphics.drawable and android.view.animation packages are w here you'll find the common classes used for drawing and animating in two-dimens ions. This document offers an introduction to drawing graphics in your Android a pplication. We'll discuss the basics of using Drawable objects to draw graphics, how to use a couple subclasses of the Drawable class, and how to create animati ons that either tween (move, stretch, rotate) a single graphic or animate a seri es of graphics (like a roll of film). Drawables A Drawable is a general abstraction for "something that can be drawn." You'll di scover that the Drawable class extends to define a variety of specific kinds of drawable graphics, including BitmapDrawable, ShapeDrawable, PictureDrawable, Lay erDrawable, and several more. Of course, you can also extend these to define you r own custom Drawable objects that behave in unique ways. There are three ways t o define and instantiate a Drawable: using an image saved in your project resouc es; using an XML file that defines the Drawable properties; or using the normal class constructors. Below, we'll discuss each the first two techniques (using co nstructors is nothing new for an experienced developer). Creating from resource images A simple way to add graphics to your application is by referencing an image file from your project resources. Supported file types are PNG (preferred), JPG (acc eptable) and GIF (discouraged). This technique would obviously be preferred for application icons, logos, or other graphics such as those used in a game. To use an image resource, just add your file to the res/drawable/ directory of your pr oject. From there, you can reference it from your code or your XML layout. Eithe r way, it is referred using a resource ID, which is the file name without the fi le type extension (E.g., my_image.png is referenced as my_image). Example code The following code snippet demonstrates how to build an ImageView that uses an i mage from drawable resources and add it to the layout. LinearLayout mLinearLayou t; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInst anceState); // Create a LinearLayout in which to add the ImageView mLinearLayout = new LinearLayout(this); // Instantiate an ImageView and define its properties ImageView i = new ImageView(this); i.setImageResource(R.drawable.my_image); i.s etAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's di mensions i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, L ayoutParams.WRAP_CONTENT)); http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 1 of 8

2D Graphics | Android Developers 29.04.09 0:49 LayoutParams.WRAP_CONTENT)); // Add the ImageView to the layout and set the layo ut as the content view mLinearLayout.addView(i); setContentView(mLinearLayout); } In other cases, you may want to handle your image resource as a Drawable objec t. To do so, create a Drawable from the resource like so: Resources res = mConte xt.getResources(); Drawable myImage = res.getDrawable(R.drawable.my_image); Caut ion: Each unique resource in your project can maintain only one state, no matter how many different objects you may instantiate for it. For example, if you inst antiate two Drawable objects from the same image resource, then change a propert y (such as the alpha) for one of the Drawables, then it will also affect the oth er. So when dealing with multiple instances of an image resource, instead of dir ectly transforming the Drawable, you should perform a tween animation. Example XML The XML snippet below shows how to add a resource Drawable to an ImageView in th e XML layout (with some red tint just for fun). <ImageView android:layout_width= "wrap_content" android:layout_height="wrap_content" android:tint="#55ff0000" and roid:src="@drawable/my_image"/> For more information on using project resources, read about Resources and Assets. Creating from resource XML By now, you should be familiar with Android's principles of developing a User In terface. Hence, you understand the power and flexibility inherent in defining ob jects in XML. This philosophy caries over from Views to Drawables. If there is a Drawable object that you'd like to create, which is not initially dependent on variables defined by your applicaton code or user interaction, then defining the Drawable in XML is a good option. Even if you expect your Drawable to change it s properties during the user's experience with your application, you should cons ider defining the object in XML, as you can always modify properties once it is instantiated. Once you've defined your Drawable in XML, save the file in the res /drawable/ directory of your project. Then, retrieve and instantiate the object by calling Resources.getDrawable(), passing it the resource ID of your XML file. (See the example below.) Any Drawable subclass that supports the inflate() meth od can be defined in XML and instantiated by your application. Each Drawable tha t supports XML inflation utilizes specific XML attributes that help define the o bject properties (see the class reference to see what these are). See the class documentation for each Drawable subclass for information on how to define it in XML. Example Here's some XML that defines a TransitionDrawable: <transition xmlns:android="ht tp://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ima ge_expand"> <item android:drawable="@drawable/image_collapse"> </transition> http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 2 of 8

2D Graphics | Android Developers 29.04.09 0:49 With this XML saved in the file res/drawable/expand_collapse.xml, the following code will instantiate the TransitionDrawable and set it as the content of an Ima geView: Resources res = mContext.getResources(); TransitionDrawable transition = (TransitionDrawable) res.getDrawable(R.drawable.expand_collapse); ImageView ima ge = (ImageView) findViewById(R.id.toggle_image); image.setImageDrawable(transit ion); Then this transition can be run forward (for 1 second) with: transition.st artTransition(1000); Refer to the Drawable classes listed above for more informa tion on the XML attributes supported by each. ShapeDrawable When you want to dynamically draw some two-dimensional graphics, a ShapeDrawable object will probably suit your needs. With a ShapeDrawable, you can programmati cally draw primitive shapes and style them in any way imaginable. A ShapeDrawabl e is an extension of Drawable, so you can use one where ever a Drawable is expec ted perhaps for the background of a View, set with setBackgroundDrawable(). Of c ourse, you can also draw your shape as its own custom View, to be added to your layout however you please. Because the ShapeDrawable has its own draw() method, you can create a subclass of View that draws the ShapeDrawable during the View.o nDraw() method. Here's a basic extension of the View class that does just this, to draw a ShapeDrawable as a View: public class CustomDrawableView extends View { private ShapeDrawable mDrawable; public CustomDrawableView(Context context) { super(context); int int int int x = 10; y = 10; width = 300; height = 50; } protected void onDraw(Canvas canvas) { mDrawable.draw(canvas); } } In the cons tructor, a ShapeDrawable is defines as an OvalShape. It's then given a color and the bounds of the shape are set. If you do not set the bounds, then the shape w ill not be drawn, whereas if you don't set the color, it will default to black. With the custom View defined, it can be drawn any way you like. With the sample above, we can draw the shape progammatically in an Activity: CustomDrawableView mCustomDrawableView; protected void onCreate(Bundle savedInstanceState) { http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 3 of 8 mDrawable = new ShapeDrawable(new OvalShape()); mDrawable.getPaint().setColor(0x ff74AC23); mDrawable.setBounds(x, y, x + width, y + height);

2D Graphics | Android Developers 29.04.09 0:49 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanc eState); mCustomDrawableView = new CustomDrawableView(this); setContentView(mCus tomDrawableView); } If you'd like to draw this custom drawable from the XML layo ut instead of from the Activity, then the CustomDrawable class must override the View(Context, AttributeSet) constructor, which is called when instantiating a V iew via inflation from XML. Then add a CustomDrawable element to the XML, like s o: <com.example.shapedrawable.CustomDrawableView android:layout_width="fill_pare nt" android:layout_height="wrap_content" /> The ShapeDrawable class (like many o ther Drawable types in the android.graphics.drawable package) allows you to defi ne various properties of the drawable with public methods. Some properties you m ight want to adjust include alpha transparency, color filter, dither, opacity an d color. NinePatchDrawable A NinePatchDrawable graphic is a stretchable bitmap image, which Android will au tomatically resize to accomodate the contents of the View in which you have plac ed it as the background. An example use of a NinePatch is the backgrounds used b y standard Android buttons buttons must stretch to accommodate strings of variou s lengths. A NinePatch drawable is a standard PNG image that includes an extra 1 -pixel-wide border. It must be saved with the extension .9.png, and saved into t he res/drawable/ directory of your project. The border is used to define the str etchable and static areas of the image. You indicate a stretchable section by dr awing one (or more) 1-pixel-wide black line(s) in the left and top part of the b order. (You can have as many stretchable sections as you want.) The relative siz e of the stretchable sections stays the same, so the largest sections always rem ain the largest. You can also define an optional drawable section of the image ( effectively, the padding lines) by drawing a line on the right and bottom lines. If a View object sets the NinePatch as its background and then specifies the Vi ew's text, it will stretch itself so that all the text fits inside only the area designated by the right and bottom lines (if included). If the padding lines ar e not included, Android uses the left and top lines to define this drawable area . To clarify the difference between the different lines, the left and top lines define which pixels of the image are allowed to be replicated in order to strech the image. The bottom and right lines define the relative area within the image that the contents of the View are allowed to lie within. Here is a sample NineP atch file used to define a button: http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 4 of 8

2D Graphics | Android Developers 29.04.09 0:49 This NinePatch defines one stretchable area with the left and top lines and the drawable area with the bottom and right lines. In the top image, the dotted grey lines identify the regions of the image that will be replicated in order to str ech the image. The pink rectangle in the bottom image identifies the region in w hich the contents of the View are allowed. If the contents don't fit in this reg ion, then the image will be stretched so that they do. The Draw 9-patch tool off ers an extremely handy way to create your NinePatch images, using a WYSIWYG grap hics editor. It even raises warnings if the region you've defined for the stretc hable area is at risk of producing drawing artifacts as a result of the pixel re plication. Example XML Here's some sample layout XML that demonstrates how to add a NinePatch image to a couple of buttons. (The NinePatch image is saved as res/drawable/my_button_bac kground.9.png <Button id="@+id/tiny" android:layout_width="wrap_content" android :layout_height="wrap_content" android:layout_alignParentTop="true" android:layou t_centerInParent="true" android:text="Tiny" android:textSize="8sp" android:backg round="@drawable/my_button_background"/> <Button id="@+id/big" android:layout_wi dth="wrap_content" android:layout_height="wrap_content" android:layout_alignPare ntBottom="true" android:layout_centerInParent="true" android:text="Biiiiiiig tex t!" android:textSize="30sp" android:background="@drawable/my_button_background"/ > Note that the width and height are set to "wrap_content" to make the button fi t neatly around the text. Below are the two buttons rendered from the XML and Ni nePatch image shown above. Notice how the width and height of the button varies with the text, and the background image stretches to accommodate it. http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 5 of 8

2D Graphics | Android Developers 29.04.09 0:49 Tween Animation A tween animation can perform a series of simple transformations (position, size , rotation, and transparency) on the contents of a View object. So, if you have a TextView object, you can move, rotate, grow, or shrink the text. If it has a b ackground image, the background image will be transformed along with the text. T he animation package provides all the classes used in a tween animation. A seque nce of animation instructions defines the twen animation, defined by either XML or Android code. Like defining a layout, an XML file is recommended because it's more readable, reusable, and swappable than hard-coding the animation. In the e xample below, we use XML. (To learn more about defining an animation in your app lication code, instead of XML, refer to the AnimationSet class and other Animati on subclasses.) The animation instructions define the transformations that you w ant to occur, when they will occur, and how long they should take to apply. Tran sformations can be sequential or simultaneous for example, you can have the cont ents of a TextView move from left to right, and then rotate 180 degrees, or you can have the text move and rotate simultaneously. Each transformation takes a se t of parameters specific for that transformation (starting size and ending size for size change, starting angle and ending angle for rotation, and so on), and a lso a set of common parameters (for instance, start time and duration). To make several transformations happen simultaneously, give them the same start time; to make them sequential, calculate the start time plus the duration of the precedi ng transformation. The animation XML file belongs in the res/anim/ directory of your Android project. The file must have a single root element: this will be eit her a single <alpha>, <scale>, <translate>, <rotate>, interpolator element, or < set> element that holds groups of these elements (which may include another <set >). By default, all animation instructions are applied simultaneously. To make t hem occur sequentially, you must specify the startOffset attribute, as shown in the example below. The following XML from one of the ApiDemos is used to stretch , then simultaneously spin and rotate a View object. <set android:shareInterpola tor="false"> <scale android:interpolator="@android:anim/accelerate_decelerate_in terpolator" android:fromXScale="1.0" android:toXScale="1.4" android:fromYScale=" 1.0" android:toYScale="0.6" android:pivotX="50%" android:pivotY="50%" android:fi llAfter="false" android:duration="700" /> <set android:interpolator="@android:an im/decelerate_interpolator"> <scale android:fromXScale="1.4" android:toXScale="0 .0" android:fromYScale="0.6" android:toYScale="0.0" android:pivotX="50%" android :pivotY="50%" android:startOffset="700" android:duration="400" android:fillBefor e="false" /> <rotate android:fromDegrees="0" android:toDegrees="-45" android:toY Scale="0.0" android:pivotX="50%" http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 6 of 8

2D Graphics | Android Developers 29.04.09 0:49 android:pivotX="50%" android:pivotY="50%" android:startOffset="700" android:dura tion="400" /> </set> </set> Screen coordinates (not used in this example) are (0 ,0) at the upper left hand corner, and increase as you go down and to the right. Some values, such as pivotX, can be specified relative to the object itself or relative to the parent. Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% relative to itself). You can d etermine how a transformation is applied over time by assigning an Interpolator. Android includes several Interpolator subclasses that specify various speed cur ves: for instance, AccelerateInterpolator tells a transformation to start slow a nd speed up. Each one has an attribute value that can be applied in the XML. Wit h this XML saved as hyperspace_jump.xml in the res/anim/ directory of the projec t, the following Java code will reference it and apply it to an ImageView object from the layout. ImageView spaceshipImage = (ImageView) findViewById(R.id.space shipImage); Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(thi s, R.anim.hyperspace_jump); spaceshipImage.startAnimation(hyperspaceJumpAnimatio n); As an alternative to startAnimation(), you can define a starting time for th e animation with Animation.setStartTime(), then assign the animation to the View with View.setAnimation(). For more information on the XML syntax, available tag s and attributes, see the discussion on animation in the Available Resources. No te: Regardless of how your animation may move or resize, the bounds of the View that holds your animation will not automatically adjust to accomodate it. Even s o, the animation will still be drawn beyond the bounds of its View and will not be clipped. However, clipping will occur if the animation exceeds the bounds of the parent View. Frame Animation This is a traditional animation in the sense that it is created with a sequence of different images, played in order, like a roll of film. The AnimationDrawable class is the basis for frame animations. While you can define the frames of an animation in your code, using the AnimationDrawable class API, it's more simply accomplished with a single XML file that lists the frames that compose the anima tion. Like the tween animation above, the XML file for this kind of animation be longs in the res/anim/ directory of your Android project. In this case, the inst ructions are the order and duration for each frame of the animation. The XML fil e consists of an <animation-list> element as the root node and a series of child <item> nodes that each define a frame: a drawable resource for the frame and th e frame duration. Here's an example XML file for a frame-by-frame animation: <an imation-list xmlns:android="http://schemas.android.com/apk/res/android" android: oneshot="true"> <item android:drawable="@drawable/rocket_thrust1" android:durati on="200" /> <item android:drawable="@drawable/rocket_thrust2" android:duration=" 200" /> <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> </animation-list> This animation runs for just three frames. By setting the android:oneshot attribute of the list to true, it will cycle just once then stop and hold on the last frame. If it is set false then the animation will loop. Wi th this XML saved as http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 7 of 8

2D Graphics | Android Developers 29.04.09 0:49 just once then stop and hold on the last frame. If it is set false then the anim ation will loop. With this XML saved as rocket_thrust.xml in the res/anim/ direc tory of the project, it can be added as the background image to a View and then called to play. Here's an example Activity, in which the animation is added to a n ImageView and then animated when the screen is touched: AnimationDrawable rock etAnimation; public void onCreate(Bundle savedInstanceState) { super.onCreate(sa vedInstanceState); setContentView(R.layout.main); ImageView rocketImage = (Image View) findViewById(R.id.rocket_image); rocketImage.setBackgroundResource(R.anim. rocket_thrust); rocketAnimation = (AnimationDrawable) rocketImage.getBackground( ); } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == M otionEvent.ACTION_DOWN) { rocketAnimation.start(); return true; } return super.o nTouchEvent(event); } It's important to note that the start() method called on t he AnimationDrawable cannot be called during the onCreate() method of your Activ ity, because the AnimationDrawable is not yet fully attached to the window. If y ou want to play the animation immediately, without requiring interaction, then y ou might want to call it from the onWindowFocusChanged() method in your Activity , which will get called when Android brings your window into focus. " Back to 2D and 3D Graphics Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/graphics/2d-graphics.html Page 8 of 8

3D with OpenGL | Android Developers 29.04.09 0:49 2D and 3D Graphics > 3D with OpenGL Android includes support for high performance 3D graphics via the OpenGL API spe cifically, the OpenGL ES API. OpenGL ES is a flavor of the OpenGL specification intended for embedded devices. Versions of OpenGL ES are loosely peered to versi ons of the primary OpenGL standard. Android currently supports OpenGL ES 1.0, wh ich corresponds to OpenGL 1.3. So, if the application you have in mind is possib le with OpenGL 1.3 on a desktop system, it should be possible on Android. The sp ecific API provided by Android is similar to the J2ME JSR239 OpenGL ES API. Howe ver, it may not be identical, so watch out for deviations. Using the API Here's how to use the API at an extremely high level: 1. Write a custom View sub class. 2. Obtain a handle to an OpenGLContext, which provides access to the Open GL functionality. 3. In your View's onDraw() method, get a handle to a GL object , and use its methods to perform GL operations. For an example of this usage mod el (based on the classic GL ColorCube), showing how to use it with threads can b e found in com.android.samples.graphics.GLSurfaceViewActivity.java. Writing a su mmary of how to actually write 3D applications using OpenGL is beyond the scope of this text and is left as an exercise for the reader. Links to Additional Information Information about OpenGL ES can be found at http://www.khronos.org/opengles/. In formation specifically about OpenGL ES 1.0 (including a detailed specification) can be found at http://www.khronos.org/opengles/1_X/. The documentation for the Android OpenGL ES implementations are also available. Finally, note that though Android does include some basic support for OpenGL ES 1.1, the support is not co mplete, and should not be relied upon at this time. " Back to 2D and 3D Graphics Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/graphics/opengl.html Page 1 of 1

Audio and Video | Android Developers 29.04.09 0:49 Audio and Video The Android platform offers built-in encoding/decoding for a variety of common m edia types, so that you can easily integrate audio, video, and images into your applications. Accessing the platform's media capabilities is fairly straightforw ard you do so using the same intents and activities mechanism that the rest of A ndroid uses. Android lets you play audio and video from several types of data so urces. You can play audio or video from media files stored in the application's resources (raw resources), from standalone files in the filesystem, or from a da ta stream arriving over a network connection. To play audio or video from your a pplication, use the MediaPlayer class. The platform also lets you record audio a nd video, where supported by the mobile device hardware. To record audio or vide o, use the MediaRecorder class. Note that the emulator doesn't have hardware to capture audio or video, but actual mobile devices are likely to provide these ca pabilities, accessible through the MediaRecorder class. For a list of media form ats for which Android offers built-in support, see the Android Media Formats app endix. Audio and Video Playback Media can be played from anywhere: from a raw resource, from a file from the sys tem, or from an available network (URL). You can play back the audio data only t o the standard output device; currently, that is the mobile device speaker or Bl uetooth headset. You cannot play sound files in the conversation audio. Playing from a Raw Resource Perhaps the most common thing to want to do is play back media (notably sound) w ithin your own applications. Doing this is easy: 1. Put the sound (or other medi a resource) file into the res/raw folder of your project, where the Eclipse plug in (or aapt) will find it and make it into a resource that can be referenced fro m your R class 2. Create an instance of MediaPlayer, referencing that resource u sing MediaPlayer.create, and then call start() on the instance: MediaPlayer mp = MediaPlayer.create(context, R.raw.sound_file_1); mp.start(); To stop playback, call stop(). If you wish to later replay the media, then you must reset() and pr epare() the MediaPlayer object before calling start() again. (create() calls pre pare() the first time.) To pause playback, call pause(). Resume playback from wh ere you paused with start(). Playing from a File or Stream You can play back media files from the filesystem or a web URL: 1. Create an ins tance of the MediaPlayer using new http://developer.android.com/guide/topics/media/index.html Page 1 of 3

Audio and Video | Android Developers 29.04.09 0:49 2. Call setDataSource() with a String containing the path (local filesystem or U RL) to the file you want to play 3. First prepare() then start() on the instance : MediaPlayer mp = new MediaPlayer(); mp.setDataSource(PATH_TO_FILE); mp.prepare (); mp.start(); stop() and pause() work the same as discussed above. Note: It is possible that mp could be null, so good code should null check after the new. A lso, IllegalArgumentException and IOException either need to be caught or passed on when using setDataSource(), since the file you are referencing may not exist . Note: If you're passing a URL to an online media file, the file must be capabl e of progressive download. Playing JET content The Android platform includes a JET engine that lets you add interactive playbac k of JET audio content in your applications. You can create JET content for inte ractive playback using the JetCreator authoring application that ships with the SDK. To play and manage JET content from your application, use the JetPlayer cla ss. For a description of JET concepts and instructions on how to use the JetCrea tor authoring tool, see the JetCreator User Manual. The tool is available fullyfeatured on the OS X and Windows platforms and the Linux version supports all th e content creation features, but not the auditioning of the imported assets. Her e's an example of how to set up JET playback from a .jet file stored on the SD c ard: JetPlayer myJet = JetPlayer.getJetPlayer(); myJet.loadJetFile("/sdcard/leve l1.jet"); byte segmentId = 0; // queue segment 5, repeat once, use General MIDI, transpose by -1 octave myJet.queueJetSegment(5, -1, 1, -1, 0, segmentId++); // queue segment 2 myJet.queueJetSegment(2, -1, 0, 0, 0, segmentId++); myJet.play() ; The SDK includes an example application JetBoy that shows how to use JetPlayer to create an interactive music soundtrack in your game. It also illustrates how to use JET events to synchronize music and game logic. The application is locat ed at <sdk>/platforms/android-1.5/samples/JetBoy. Audio Capture Audio capture from the device is a bit more complicated than audio/video playbac k, but still fairly simple: 1. Create a new instance of android.media.MediaRecor der using new 2. Create a new instance of android.content.ContentValues and put in some standard properties like TITLE, TIMESTAMP, and the all important MIME_TY PE 3. Create a file path for the data to go to (you can use android.content.Cont entResolver to create an entry in the Content database and get it to assign a pa th automatically which you can then use) 4. Set the audio source using MediaReco rder.setAudioSource(). You will probably want to use MediaRecorder.AudioSource.M IC http://developer.android.com/guide/topics/media/index.html Page 2 of 3

Audio and Video | Android Developers 29.04.09 0:49 5. Set output file format using MediaRecorder.setOutputFormat() 6. Set the audio encoder using MediaRecorder.setAudioEncoder() 7. Call prepare() on the MediaRec order instance. 8. To start audio capture, call start(). 9. To stop audio captur e, call stop(). 10. When you are done with the MediaRecorder instance, call rele ase() on it. Example: Audio Capture Setup and Start The example below illustrates how to set up, then start audio capture. recorder = new MediaRecorder(); ContentValues values = new ContentValues(3); values.put(M ediaStore.MediaColumns.TITLE, SOME_NAME_HERE); values.put(MediaStore.MediaColumn s.TIMESTAMP, System.currentTimeMillis()); values.put(MediaStore.MediaColumns.MIM E_TYPE, recorder.getMimeContentType()); ContentResolver contentResolver = new Co ntentResolver(); Uri base = MediaStore.Audio.INTERNAL_CONTENT_URI; Uri newUri = contentResolver.insert(base, values); if (newUri == null) { // need to handle ex ception here - we were not able to create a new // content entry } String path = contentResolver.getDataFilePath(newUri); // could use setPreviewDisplay() to di splay a preview to suitable View here recorder.setAudioSource(MediaRecorder.Audi oSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); re corder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFil e(path); recorder.prepare(); recorder.start(); Stop Recording Based on the example above, here's how you would stop audio capture. recorder.st op(); recorder.release(); Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/media/index.html Page 3 of 3

Location and Maps | Android Developers 29.04.09 0:49 Location and Maps Location- and maps-based applications and services are compelling for mobile dev ice users. You can build these capabilities into your applications using the cla sses of the android.location package and the Google Maps external library. The s ections below provide details. Location Services Android gives your applications access to the location services supported by the device through the classes in the android.location package. The central compone nt of the location framework is the LocationManager system service, which provid es an API to determine location and bearing if the underlying device (if it supp orts location capabilities). As with other system services, you do not instantia te a LocationManager directly. Rather, you request an LocationManager instance f rom the system by calling getSystemService(Context.LOCATION_SERVICE). The method returns a handle to a new LocationManager instance. Once your application has a handle to a LocationManager instance, your application will be able to do three things: Query for the list of all LocationProviders known to the LocationManage r for its last known location. Register/unregister for periodic updates of curre nt location from a LocationProvider (specified either by Criteria or name). Regi ster/unregister for a given Intent to be fired if the device comes within a give n proximity (specified by radius in meters) of a given lat/long. However, during initial development in the emulator, you may not have access to real data from a real location provider (Network or GPS). In that case, it may be necessary to spoof some data for your application using a mock location provider. Note: If yo u've used mock LocationProviders in previous versions of the SDK, you can no lon ger provide canned LocationProviders in the /system/etc/location directory. Thes e directories will be wiped during boot-up. Please follow the new procedures out lined below. Providing Mock Location Data When testing your application on the Android emulator, there are a couple differ ent ways to send it some mock location data: you can use the DDMS tool or the "g eo" command option in the emulator console. Using DDMS With the DDMS tool, you can simulate location data a few different ways: Manuall y send individual longitude/latitude coordinates to the device. Use a GPX file d escribing a route for playback to the device. Use a KML file describing individu al placemarks for sequenced playback to the device. For more information on usin g DDMS to spoof location data, see the Using DDMS guide. http://developer.android.com/guide/topics/location/index.html Page 1 of 2

Location and Maps | Android Developers 29.04.09 0:49 Using the "geo" command in the emulator console Launch your application in the Android emulator and open a terminal/console in y our SDK's /tools directory. Connect to the emulator console. Now you can use: ge o fix to send a fixed geo-location. This command accepts a longitude and latitud e in decimal degrees, and an optional altitude in meters. For example: geo fix 121.45356 46.51119 4392 geo nmea to send an NMEA 0183 sentence. This command acc epts a single NMEA sentence of type '$GPGGA' (fix data) or '$GPRMC' (transit dat a). For example: geo nmea $GPRMC,081836,A,3751.65,S,14507.36,E,000.0,360.0,13099 8,011.3,E*62 For information about how to connect to the emulator console, see U sing the Emulator Console. Google Maps External Library To make it easier for you to add powerful mapping capabilities to your applicati on, Google provides a Maps external library that includes the com.google.android .maps package. The classes of the com.google.android.maps package offer built-in downloading, rendering, and caching of Maps tiles, as well as a variety of disp lay options and controls. The key class in the Maps package is com.google.androi d.maps.MapView, a subclass of ViewGroup. A MapView displays a map with data obta ined from the Google Maps service. When the MapView has focus, it will capture k eypresses and touch gestures to pan and zoom the map automatically, including ha ndling network requests for additional maps tiles. It also provides all of the U I elements necessary for users to control the map. Your application can also use MapView class methods to control the MapView programmatically and draw a number of Overlay types on top of the map. In general, the MapView class provides a wr apper around the Google Maps API that lets your application manipulate Google Ma ps data through class methods, and it lets you work with Maps data as you would other types of Views. The Maps external library is not part of the standard Andr oid library, so it may not be present on some compliant Android-powered devices (although it is likely to be present on most devices). Similarly, the Maps exter nal library is not included in the standard Android library provided in the SDK. So that you can develop using the classes of the com.google.android.maps packag e, the Maps external library is made available to you as part of the Google APIs addon for the Android SDK. To learn more about the Maps external library and ho w to download and use the Google APIs add-on, visit http://code.google.com/andro id/add-ons/google-apis For your convenience, the Google APIs add-on is also incl uded in the Android SDK. Note: In order to display Google Maps data in a MapView , you must register with the Google Maps service and obtain a Maps API Key. For information about how to get a Maps API Key, see Obtaining a Maps API Key. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/location/index.html Page 2 of 2

AppWidgets | Android Developers 29.04.09 0:49 AppWidgets AppWidgets are miniature application views that can be embedded in other applica tions (e.g., the Home). These views are called "widgets" and you can publish one with an "AppWidget provider." An application component that is able to hold oth er widgets is called an "AppWidget host." AppWidget Providers Any application can publish widgets. All an application needs to do to publish a widget is to have a BroadcastReceiver that receives the AppWidgetManager.ACTION _APPWIDGET_UPDATE intent, and provide some meta-data about the widget. Android p rovides the AppWidgetProvider class, which extends BroadcastReceiver, as a conve nience class to aid in handling the broadcasts. Declaring a widget in the AndroidManifest First, declare the BroadcastReceiver in your application's AndroidManifest.xml f ile. <receiver android:name="TestAppWidgetProvider" android:label="@string/oh_ha i" android:icon="@drawable/oh_hai_icon" > <intent-filter> <action android:name=" android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data androi d:name="android.appwidget.provider" android:resource="@xml/appwidget_info" /> </ receiver> The <receiver> element has the following attributes: android:name - sp ecifies the BroadcastReceiver or AppWidgetProvider class. android:label - specif ies the string resource that will be shown by the widget picker as the label. an droid:icon - specifies the drawable resource that will be shown by the widget pi cker as the icon. The <intent-filter> element tells the PackageManager that this BroadcastReceiver receives the AppWidgetManager.ACTION_APPWIDGET_UPDATE broadca st. The widget manager will send other broadcasts directly to your widget provid er as required. It is only necessary to explicitly declare that you accept the A ppWidgetManager.ACTION_APPWIDGET_UPDATE broadcast. The <meta-data> element tells the widget manager which xml resource to read to find the AppWidgetProviderInfo for your widget provider. It has the following attributes: android:name="androi d.appwidget.provider" - identifies this meta-data as the AppWidgetProviderInfo d escriptor. android:resource - is the xml resource to use as that descriptor. http://developer.android.com/guide/topics/appwidgets/index.html Page 1 of 3

AppWidgets | Android Developers 29.04.09 0:49 Adding the AppWidgetProviderInfo meta-data For a widget, the values in the AppWidgetProviderInfo structure are supplied in an XML resource. In the example above, the xml resource is referenced with andro id:resource="@xml/appwidget_info". That XML file would go in your application's directory at res/xml/appwidget_info.xml. Here is a simple example. <appwidget-pr ovider xmlns:android="http://schemas.android.com/apk/res/android" android:minWid th="40dp" android:minHeight="30dp" android:updatePeriodMillis="86400000" android :initialLayout="@layout/test_appwidget" android:configure="com.android.tests.app widgethost.TestAppWidgetConfigure" > </appwidget-provider> The attributes are as documented in the AppWidgetProviderInfo class. Using the AppWidgetProvider class The AppWidgetProvider class is the easiest way to handle the widget provider int ent broadcasts. See the src/com/example/android/apis/appwidget/ExampleAppWidgetP rovider.java sample class in ApiDemos for an example. Keep in mind that since th e the AppWidgetProvider is a BroadcastReceiver, your process is not guaranteed t o keep running after the callback methods return. See Application Fundamentals > Broadcast Receiver Lifecycle for more information. AppWidget Configuration UI Widget hosts have the ability to start a configuration activity when a widget is instantiated. The activity should be declared as normal in AndroidManifest.xml, and it should be listed in the AppWidgetProviderInfo XML file in the android:co nfigure attribute. The activity you specified will be launched with the ACTION_A PPWIDGET_CONFIGURE action. See the documentation for that action for more info. See the src/com/example/android/apis/appwidget/ExampleAppWidgetConfigure.java sa mple class in ApiDemos for an example. AppWidget Broadcast Intents AppWidgetProvider is just a convenience class. If you would like to receive the widget broadcasts directly, you can. The four intents you need to care about are : ACTION_APPWIDGET_UPDATE ACTION_APPWIDGET_DELETED ACTION_APPWIDGET_ENABLED ACTI ON_APPWIDGET_DISABLED By way of example, the implementation of onReceive(Context , Intent) is quite simple: public void onReceive(Context context, Intent intent) { // Protect against rogue update broadcasts (not really a security issue, // j ust filter bad broacasts out so subclasses are less likely to crash). String act ion = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(ac tion)) { Bundle extras = intent.getExtras(); http://developer.android.com/guide/topics/appwidgets/index.html Page 2 of 3

AppWidgets | Android Developers 29.04.09 0:49 Bundle extras = intent.getExtras(); if (extras != null) { int[] appWidgetIds = e xtras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != nul l && appWidgetIds.length > 0) { this.onUpdate(context, AppWidgetManager.getInsta nce(context), appWidgetIds); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DE LETED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null) { int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null && appWidgetIds.length > 0) { this.onDeleted(context, appWidgetIds); } } } else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(a ction)) { this.onEnabled(context); } else if (AppWidgetManager.ACTION_APPWIDGET_ DISABLED.equals(action)) { this.onDisabled(context); } } AppWidget Hosts Widget hosts are the containers in which widgets can be placed. Most of the look and feel details are left up to the widget hosts. For example, the home screen has one way of viewing widgets, but the lock screen could also contain widgets, and it would have a different way of adding, removing and otherwise managing wid gets. For more information on implementing your own widget host, see the AppWidg etHost class. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/topics/appwidgets/index.html Page 3 of 3

Developing In Eclipse, with ADT | Android Developers 29.04.09 0:49 Developing In Eclipse, with ADT The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse integrated development environment. It allows you to create and d ebug Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications: It gives you a ccess to other Android development tools from inside the Eclipse IDE. For exampl e, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage port-forwarding, set breakpoints, and view thread and process informatio nd irectly from Eclipse. It provides a New Project Wizard, which helps you quick ly create and set up all of the basic files you'll need for a new Android applic ation. It automates and simplifies the process of building your Android applicat ion. It provides an Android code editor that helps you write valid XML for your Android manifest and resource files. It will even export your project into a sig ned APK, which can be distributed to users. To begin developing Android applicat ions in the Eclipse IDE with ADT, you first need to download the Eclipse IDE and then download and install the ADT plugin. To do so, follow the steps given in I nstalling the ADT Plugin. If you are already developing applications using a ver sion of ADT earlier than 0.9, make sure to upgrade to the latest version before continuing. See the guide to Update Your Eclipse ADT Plugin. Note: This guide as sumes you are using the latest version of the ADT plugin (0.9). While most of th e information covered also applies to previous versions, if you are using an old er version, you may want to consult this document from the set of documentation included in your SDK package (instead of the online version). Creating an Android Project The ADT plugin provides a New Project Wizard that you can use to quickly create a new Android project (or a project from existing code). To create a new project : 1. Select File > New > Project. 2. Select Android > Android Project, and click Next. 3. Select the contents for the project: Enter a Project Name. This will b e the name of the folder where your project is created. Under Contents, select C reate new project in workspace. Select your project workspace location. Under Ta rget, select an Android target to be used as the project's Build Target. The Bui ld Target specifies which Android platform you'd like your application built aga inst. Unless you know that you'll be using new APIs introduced in the latest SDK , you should select a target with the lowest platform version possible, such as Android 1.1. Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target. Under Properties, fill in al l necessary fields. Enter an Application name. This is the human-readable title for your application the name that will appear on the Android device. Enter a Pa ckage name. This is the package namespace (following the same rules as for packa ges in the Java programming language) where all your source code will reside. Se lect Create Activity (optional, of course, but common) and enter a name for your main Activity class. Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the <useshttp://developer .android.com/guide/developing/eclipse-adt.html Page 1 of 5

Developing In Eclipse, with ADT | Android Developers 29.04.09 0:49 run your application. Entering this here automatically sets the minSdkVersion at tribute in the <usessdk> of your Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab. 4. Click Finish. Tip: You can also start the New Pr oject Wizard from the New icon in the toolbar. Once you complete the New Project Wizard, ADT creates the following folders and files in your new project: src/ I ncludes your stub Activity Java file. All other Java files for your application go here. <Android Version>/ (e.g., Android 1.1/) Includes the android.jar file t hat your application will build against. This is determined by the build target that you have chosen in the New Project Wizard. gen/ This contains the Java file s generated by ADT, such as your R.java file and interfaces created from AIDL fi les. assets/ This is empty. You can use it to store raw asset files. See Resourc es and Assets. res/ A folder for your application resources, such as drawable fi les, layout files, string values, etc. See Resources and Assets. AndroidManifest .xml The Android Manifest for your project. See The AndroidManifest.xml File. de fault.properties This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Sou rce Revision Control system. It should never be edited manually to edit project properties, right-click the project folder and select "Properties". Running Your Application Wait! Before you can run your application on the Android Emulator, you must crea te an Android Virtual Device (AVD). An AVD is a configuration that specifies the Android platform to be used on the emulator. You can read more about AVDs in th e Developing Overview, but if you just want to get started, follow the simple gu ide below to create an AVD. If you will be running your applications only on act ual device hardware, you do not need an AVD see Developing On a Device for infor mation on running your applicaiton. Creating an AVD To avoid some explanation that's beyond the scope of this document, here's the b asic procedure to create an AVD: 1. Open a command-line (e.g.,"Command Prompt" a pplication on Windows, or "Terminal" on Mac/Linux) and navigate to your SDK pack age's tools/ directory. 2. First, you need to select a Deployment Target. To vie w available targets, execute: android list targets This will output a list of av ailable Android targets, such as: id:1 Name: Android 1.1 Type: platform API leve l: 2 Skins: HVGA (default), HVGA-L, HVGA-P, QVGA-L, QVGA-P id:2 Name: Android 1. 5 http://developer.android.com/guide/developing/eclipse-adt.html Page 2 of 5

Developing In Eclipse, with ADT | Android Developers 29.04.09 0:49 Name: Android 1.5 Type: platform API level: 3 Skins: HVGA (default), HVGA-L, HVG A-P, QVGA-L, QVGA-P Find the target that matches the Android platform upon which you'd like to run your application. Note the integer value of the id you'll use this in the next step. 3. Create a new AVD using your selected Deployment Targe t. Execute: android create avd --name <your_avd_name> --target <targetID> 4. Nex t, you'll be asked whether you'd like to create a custom hardware profile. If yo u respond "yes," you'll be presented with a series of prompts to define various aspects of the device hardware (leave entries blank to use default values, which are shown in brackets). Otherwise, press return to use all default values ("no" is the default). That's it; your AVD is ready. In the next section, you'll see how the AVD is used when launching your application on an emulator. To learn mor e about creating and managing AVDs, please read the Android Virtual Devices docu mentation. Running your application Note: Before you can run your application, be sure that you have created an AVD with a target that satisfies your application's Build Target. If an AVD cannot b e found that meets the requirements of your Build Target, you will see a console error telling you so and the launch will be aborted. To run (or debug) your app lication, select Run > Run (or Run > Debug) from the Eclipse main menu. The ADT plugin will automatically create a default launch configuration for the project. When you choose to run or debug your application, Eclipse will perform the foll owing: 1. Compile the project (if there have been changes since the last build). 2. Create a default launch configuration (if one does not already exist for the project). 3. Install and start the application on an emulator or device (based on the Deployment Target defined by the run configuration). By default, Android application run configurations use an "automatic target" mode for selecting a de vice target. For information on how automatic target mode selects a deployment t arget, see Automatic and manual target modes below. If debugging, the applicatio n will start in the "Waiting For Debugger" mode. Once the debugger is attached, Eclipse will open the Debug perspective. To set or change the launch configurati on used for your project, use the launch configuration manager. See Creating a L aunch Configuration for information. Creating a Run Configuration The run configuration specifies the project to run, the Activity to start, the e mulator options to use, and so on. When you first run a project as an Android Ap plication, ADT will automatically create a run configuration. The default run co nfiguration will launch the default project Activity and use automatic target mo de for device selection (with no preferred AVD). If the default setting don't su it your project, you can customize the launch configuration or even create a new . To create or modify a launch configuration, follow these steps as appropriate for your Eclipse version: 1. Open the run configuration manager. In Eclipse 3.3 (Europa), select Run > Open Run Dialog (or Open Debug Dialog) In Eclipse 3.4 (Ga nymede), select Run > Run Configurations (or Debug Configurations) 2. Expand the Android Application item and create a new configuration or open an existing one . http://developer.android.com/guide/developing/eclipse-adt.html Page 3 of 5

Developing In Eclipse, with ADT | Android Developers 29.04.09 0:49 To create a new configuration: 1. Select Android Application and click the New l aunch configuration icon above the list (or, right-click Android Application and click New). 2. Enter a Name for your configuration. 3. In the Android tab, brow se and select the project you'd like to run with the configuration. To open an e xisting configuration, select the configuration name from the list nested below Android Application. 3. Adjust your desired launch configuration settings. In th e Target tab, consider whether you'd like to use Manual or Automatic mode when s electing an AVD to run your application. See the following section on Automatic and manual target modes). Automatic and manual target modes By default, a run configuration uses the automatic target mode in order to selec t an AVD. In this mode, ADT will select an AVD for the application in the follow ing manner: 1. If there's a device or emulator already running and its AVD confi guration meets the requirements of the application's build target, the applicati on is installed and run upon it. 2. If there's more than one device or emulator running, each of which meets the requirements of the build target, a "device cho oser" is shown to let you select which device to use. 3. If there are no devices or emulators running that meet the requirements of the build target, ADT looks at the available AVDs. If one meets the requirements of the build target, the AV D is used to launch a new emulator, upon which the application is installed and run. 4. If all else fails, the application will not be run and you will see a co nsole error warning you that there is no existing AVD that meets the build targe t requirements. However, if a "preferred AVD" is selected in the run configurati on, then the application will always be deployed to that AVD. If it's not alread y running, then a new emulator will be launched. If your run configuration uses manual mode, then the "device chooser" is presented every time that your applica tion is run, so that you can select which AVD to use. Signing your Applications As you begin developing Android applications, understand that all Android applic ations must be digitally signed before the system will install them on an emulat or or an actual device. There are two ways to do this: with a debug key (for imm ediate testing on an emulator or development device) or with a private key (for application distribution). The ADT plugin helps you get started quickly by signi ng your .apk files with a debug key, prior to installing them on an emulator or development device. This means that you can quickly run your application from Ec lipse without having to generate your own private key. No specific action on you r part is needed, provided ADT has access to Keytool.However, please note that i f you intend to publish your application, you must sign the application with you r own private key, rather than the debug key generated by the SDK tools. Please read Signing Your Applications, which provides a thorough guide to application s igning on Android and what it means to you as an Android application developer. The document also includes a guide to exporting and signing your application wit h the ADT's Export Wizard. Eclipse Tips Executing arbitrary Java expressions in Eclipse You can execute arbitrary code when paused at a breakpoint in Eclipse. For examp le, when in a function with a String argument called "zip", you can get informat ion about packages and call class methods. You can also invoke arbitrary static methods: for example, entering android.os.Debug.startMethodTracing() will start dmTrace. http://developer.android.com/guide/developing/eclipse-adt.html Page 4 of 5

Developing In Eclipse, with ADT | Android Developers 29.04.09 0:49 Open a code execution window, select Window>Show View>Display from the main menu to open the Display window, a simple text editor. Type your expression, highlig ht the text, and click the 'J' icon (or CTRL + SHIFT + D) to run your code. The code runs in the context of the selected thread, which must be stopped at a brea kpoint or singlestep point. (If you suspend the thread manually, you have to sin gle-step once; this doesn't work if the thread is in Object.wait().) If you are currently paused on a breakpoint, you can simply highlight and execute a piece o f source code by pressing CTRL + SHIFT + D. You can highlight a block of text wi thin the same scope by pressing ALT +SHIFT + UP ARROW to select larger and large r enclosing blocks, or DOWN ARROW to select smaller blocks. Here are a few sampl e inputs and responses in Eclipse using the Display window. Input zip zip.endsWi th(".zip") zip.endsWith(".jar") Response (java.lang.String) /work/device/out/lin ux-x86debug/android/app/android_sdk.zip (boolean) true (boolean) false You can also execute arbitrary code when not debugging by using a scrapbook page . Search the Eclipse documentation for "scrapbook". Running DDMS Manually Although the recommended way to debug is to use the ADT plugin, you can manually run DDMS and configure Eclipse to debug on port 8700. (Note: Be sure that you h ave first started DDMS). Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/eclipse-adt.html Page 5 of 5

Developing In Other IDEs | Android Developers 29.04.09 0:50 Developing In Other IDEs The recommended way to develop an Android application is to use Eclipse with the ADT plugin. The ADT plugin provides editing, building, debugging, and .apk pack aging and signing functionality integrated right into the IDE. However, if you'd rather develop your application in another IDE, such as IntelliJ, or in a basic editor, such as Emacs, you can do that instead. The SDK includes all the tools you need to set up an Android project, build it, debug it and then package it fo r distribution. This document is your guide to using these tools. Essential Tools When developing in IDEs or editors other than Eclipse, you'll require familiarit y with the following Android SDK tools: android To create/update Android project s and to create/move/delete AVDs. Android Emulator To run your Android applicati ons on an emulated Android platform. Android Debug Bridge To interface with your emulator or connected device (install apps, shell the device, issue commands, e tc.). In addition to the above tools, included with the SDK, you'll use the foll owing open source and third-party tools: Ant To compile and build your Android p roject into an installable .apk file. Keytool To generate a keystore and private key, used to sign your .apk file. Jarsigner (or similar signing tool) To sign y our .apk file with a private key generated by keytool. In the topics that follow , you'll be introduced to each of these tools as necessary. For more advanced op erations, please read the respective documentation for each tool. Creating an Android Project To create an Android project, you must use the android tool. When you create a n ew project with android, it will generate a project directory with some default application files, stub files, configuration files and a build file. Creating a new Project If you're starting a new project, use the android create project command to gene rate all the necessary files and folders. To create a new Android project, open a command-line, navigate to the tools/ directory of your SDK and run: http://developer.android.com/guide/developing/other-ide.html Page 1 of 6

Developing In Other IDEs | Android Developers 29.04.09 0:50 android create project \ --target <targetID> \ --path /path/to/your/project \ -activity <your_activity_name> \ --package <your_package_namespace> target is the "build target" for your application. It corresponds to an Android platform libr ary (including any addons, such as Google APIs) that you would like to build you r project against. To see a list of available targets and their corresponding ID s, execute: android list targets. path is the location of your project directory . If the directory does not exist, it will be created for you. activity is the n ame for your Activity class. This class file will be created for you inside <pat h_to_your_project>/src/<your_package_namespace_path>/. package is the package na mespace for your project, following the same rules as for packages in the Java p rogramming language. Here's an example: android create project \ --target 1 \ -path ./myProject \ --activity MyActivity \ --package com.example.myproject The t ool generates the following files and directories: AndroidManifest.xml - The app lication manifest file, synced to the specified Activity class for the project. build.xml - Build file for Ant. default.properties - Properties for the build sy stem. Do not modify this file. build.properties - Customizable properties for th e build system. You can edit this file to overried default build settings used b y Ant. src/your/package/namespace/ActivityName.java - The Activity class you spe cified during project creation. bin/ - Output directory for the build script. ge n/ - Holds Ant-generated files, such as R.java. libs/ - Holds private libraries. res/ - Holds project resources. src/ - Holds source code. tests/ - Holds a dupl icate of all-of-the-above, for testing purposes. Once you've created your projec t, you're ready to begin development. You can move your project folder wherever you want for development, but keep in mind that you must use the Android Debug B ridge (adb) located in the SDK tools/ directory to send your application to the emulator (discussed later). So you need access between your project solution and the tools/ folder. Note: You should refrain from moving the location of the SDK directory, because this will break the build scripts. (They will need to be man ually updated to reflect the new SDK location before they will work again.) Updating a project If you're upgrading a project from an older version of the Android SDK or want t o create a new project from existing code, use the android update project comman d to update the project to the new development environment. You can also use thi s command to revise the build target of an existing project (with the --target o ption). The android tool will generate any files and folders (listed in the prev ious section) that are either missing or need to be http://developer.android.com/guide/developing/other-ide.html Page 2 of 6

Developing In Other IDEs | Android Developers 29.04.09 0:50 android tool will generate any files and folders (listed in the previous section ) that are either missing or need to be updated, as needed for the Android proje ct. To update an existing Android project, open a command-line and navigate to t he tools/ directory of your SDK. Now run: android update project --target <targe tID> --path path/to/your/project/ target is the "build target" for your applicat ion. It corresponds to an Android platform library (including any addons, such a s Google APIs) that you would like to build your project against. To see a list of available targets and their corresponding IDs, execute: android list targets. path is the location of your project directory. Here's an example: android upda te project --target 2 --path ./myProject Preparing to Sign Your Application As you begin developing Android applications, understand that all Android applic ations must be digitally signed before the system will install them on an emulat or or device. There are two ways to do this: with a debug key (for immediate tes ting on an emulator or development device) or with a private key (for applicatio n distribution). The Android build tools help you get started by automatically s igning your .apk files with a debug key at build time. This means that you can c ompile your application and install it on the emulator without having to generat e your own private key. However, please note that if you intend to publish your application, you must sign the application with your own private key, rather tha n the debug key generated by the SDK tools. Please read Signing Your Application s, which provides a thorough guide to application signing on Android and what it means to you as an Android application developer. Building Your Application There are two ways to build your application: one for testing/debugging your app lication debug mode and one for building your final package for release release mode. As described in the previous section, your application must be signed befo re it can be installed on an emulator or device. Whether you're building in debu g mode or release mode, you need to use the Ant tool to compile and build your p roject. This will create the .apk file that is installed onto the emulator or de vice. When you build in debug mode, the .apk file is automatically signed by the SDK tools with a debug key, so it's instantly ready for installation (but only onto an emulator or attached development device). When you build in release mode , the .apk file is unsigned, so you must manually sign it with your own private key, using Keytool and Jarsigner. It's important that you read and understand Si gning Your Applications, particularly once you're ready to release your applicat ion and share it with end-users. That document describes the procedure for gener ating a private key and then using it to sign your .apk file. If you're just get ting started, however, you can quickly run your applications on an emulator or y our own development device by building in debug mode. If you don't have Ant, you can obtain it from the Apache Ant home page. Install it and make sure it is in your executable PATH. Before calling Ant, you need to declare the JAVA_HOME envi ronment variable to specify the path to where the JDK is installed. http://developer.android.com/guide/developing/other-ide.html Page 3 of 6

Developing In Other IDEs | Android Developers 29.04.09 0:50 Note: When installing JDK on Windows, the default is to install in the "Program Files" directory. This location will cause ant to fail, because of the space. To fix the problem, you can specify the JAVA_HOME variable like this: set JAVA_HOM E=c:\Prora~1\Java\. The easiest solution, however, is to install JDK in a non-sp ace directory, for example: c:\java\jdk1.6.0_02. Building in debug mode For immediate application testing and debugging, you can build your application in debug mode and immediately install it on an emulator. In debug mode, the buil d tools automatically sign your application with a debug key. However, you can ( and should) also test your application in release mode. Debug mode simply allows you to run your application without manually signing the application. To build in debug mode: 1. Open a command-line and navigate to the root of your project d irectory. 2. Use Ant to compile your project in debug mode: ant debug This creat es your Android application .apk file inside the project bin/ directory, named < your_DefaultActivity_name>-debug.apk. The file is already signed with the debug key. Each time you change a source file or resource, you must run Ant again in o rder to package up the latest version of the application. To install and run you r application on an emulator, see the following section about Running Your Appli cation. Building in release mode When you're ready to release and distribute your application to end-users, you m ust build your application in release mode. Once you have built in release mode, it's a good idea to perform additional testing and debugging with the final .ap k. To build in release mode: 1. Open a command-line and navigate to the root of your project directory. 2. Use Ant to compile your project in release mode: ant release This creates your Android application .apk file inside the project bin/ directory, named <your_DefaultActivity_name>.apk. Note: The .apk file is unsigne d at this point. You can't install it on an emulator or device until you sign it with your private key. Because release mode builds your application unsigned, y our next step is to sign it with your private key, in order to distribute it to end-users. To complete this procedure, read Signing Your Applications. Once you have signed your application with a private key, you can install it on an emulat or or device as discussed in the following section about Running Your Applicatio n. You can also try installing it onto a device from a web server. Simply upload the signed APK to a web site, then load the .apk URL in your Android web browse r to download the application and begin installation. (On your device, be sure y ou have enabled Settings > Applications > Unknown sources.) Running Your Application http://developer.android.com/guide/developing/other-ide.html Page 4 of 6

Developing In Other IDEs | Android Developers 29.04.09 0:50 Unless you'll be running your application on device hardware, you need to launch an emulator upon which you will install your application. An instance of the An droid emulator runs a specific Android platform with specific device configurati on settings. The platform and configuration is defined with an Android Virtual D evice (AVD). So before you can launch your emulator, you must define an AVD. If you'll be running your application on device hardware, please read about Develop ing On a Device instead. 1. Create an AVD 1. Open a command-line and navigate to your SDK package's tools/ directory. 2. First, you need to select a "deployment target." To view available targets, execute: android list targets This will out put a list of available Android targets, such as: id:1 Name: Android 1.1 Type: p latform API level: 2 Skins: HVGA (default), HVGA-L, HVGA-P, QVGA-L, QVGA-P id:2 Name: Android 1.5 Type: platform API level: 3 Skins: HVGA (default), HVGA-L, HVG A-P, QVGA-L, QVGA-P Find the target that matches the Android platform upon which you'd like to run your application. Note the integer value of the id you'll use this in the next step. 3. Create a new AVD using your selected deployment targe t: android create avd --name <your_avd_name> --target <targetID> 4. Next, you'll be asked whether you'd like to create a custom hardware profile. If you respond "yes," you'll be presented with a series of prompts to define various aspects o f the device hardware (leave entries blank to use default values, which are show n in brackets). Otherwise, press return to use all default values ("no" is the d efault). 2. Launch an emulator From your SDK's tools/ directory, launch an emula tor using an existing AVD (created above): emulator -avd <your_avd_name> An inst ance of the emulator will now launch, running the target and configuration defin ed by your AVD. 3. Install your application From your SDK's tools/ directory, in stall the .apk on the emulator: adb install /path/to/your/application.apk If the re is more than one emulator running, you must specify the emulator upon which t o install the application, by its serial number, with the -s option. For example : adb -s emulator-5554 install /my/project/path/myapp.apk 4. Open your applicati on In the emulator, open the list of available applications to find and open you r application. http://developer.android.com/guide/developing/other-ide.html Page 5 of 6

Developing In Other IDEs | Android Developers 29.04.09 0:50 If you don't see your application on the emulator. Try restarting the emulator ( with the same AVD). Sometimes when you install an Activity for the first time, i t won't show up in the application launcher or be accessible by other applicatio ns. This is because the package manager usually examines manifests completely on ly on emulator startup. Tip: If you have only one emulator running, you can buil d your application and install it on the emulator in one simple step. Navigate t o the root of your project directory and use Ant to compile the project with ins tall mode: ant install. This will build your application, sign it with the debug key, and install it on the currently running emulator. If there is more than on e emulator currently running when using the install command, it will fail it can 't select between the multiple emulators. For more information on the tools used above, please see the following documents: android Tool Android Emulator Androi d Debug Bridge (ADB) Attaching a Debugger to Your Application This section describes how to display debug information on the screen (such as C PU usage), as well as how to hook up your IDE to debug running applications on t he emulator. Attaching a debugger is automated using the Eclipse plugin, but you can configure other IDEs to listen on a debugging port to receive debugging inf ormation: 1. Start the Dalvik Debug Monitor Server (DDMS) tool, which acts as a port forwarding service between your IDE and the emulator. 2. Set optional debug ging configurations on your emulator, such as blocking application startup for a n Activity until a debugger is attached. Note that many of these debugging optio ns can be used without DDMS, such as displaying CPU usage or screen refresh rate on the emulator. 3. Configure your IDE to attach to port 8700 for debugging. Re ad about Configuring Your IDE to Attach to the Debugging Port. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/other-ide.html Page 6 of 6

Developing on a Device | Android Developers 29.04.09 0:50 Developing on a Device When building mobile applications, it's vital to test them on real devices prior to releasing them to users. This page covers what you need to know, including t he types of devices that you can use, and how to set one up for developing and d ebugging. Available Devices While developers can use regular consumer devices purchased at retail to test an d use their apps, some developers may choose not to use a retail device, preferr ing an unlocked or no-contract device. Here are some options for obtaining devic es capable of testing your applications. T-Mobile G1 The T-Mobile G1 device makes an excellent development device. You can write appl ications in the SDK and install them on the G1, then run them as users would, us ing the same hardware, system, and network. For more information about obtaining a G1, visit the T-Mobile G1 site. Android Dev Phone 1 The Android Dev Phone 1 is a SIM-unlocked and hardwareunlocked device that is de signed for advanced developers. The device ships with a system image that is ful ly compatible with Android 1.0, so you can rely on it when developing your appli cations. You can use any SIM in the device and can flash custom Android builds t hat will work with the unlocked bootloader. Unlike the bootloader on retail devi ces, the bootloader on the Android Dev Phone 1 does not enforce signed system im ages. The Android Dev Phone 1 should also appeal to developers who live outside of T-Mobile geographies. To purchase an Android Dev Phone 1 device, you must fir st register as an Android developer on the Android Market site, if you haven't d one so already. Once you've logged into your developer account on Android Market , you can purchase the device by following the link to "Development phones." To accommodate demand, there is a limit of 1 device per developer account, for now. Selected specs for Android Dev Phone 1: Touch screen Trackball 3.2 megapixel cam era with autofocus Wi-Fi GPS-enabled Bluetooth v2.0 Handsfree profile v1.5 Heads et profile v1.0 3G WCDMA (1700/2100 MHz) Quad-band GSM (850/900/1800/1900 MHz) Q WERTY slider keyboard Includes 1GB MicroSD card (can be replaced with up to 16GB card) The device currently costs $399 (USD) (including free shipping in the US), and i s available for purchase in 18 international markets, including the US, UK, Germ any, Japan, India, Canada, France, Taiwan, Spain, Australia, Singapore, Switzerl and, Netherlands, Austria, Sweden, Finland, Poland, and Hungary. We will continu e to expand this program into new geographies over time. Check this page for upd ated information. Note that Android Dev Phone 1 devices are not intended for non -developer end-users. Because the device can be configured with system software not provided by or supported by Google or any other company, end-users operate t hese devices at their own risk. http://developer.android.com/guide/developing/device.html Page 1 of 3

Developing on a Device | Android Developers 29.04.09 0:50 For full device specs and more information about obtaining an Android Dev Phone 1 device, see the Android Market site. Setting up a Device for Development With a T-mobile G1 or Android Dev Phone 1, you can develop and debug your Androi d applications just as you would on the emulator. There are just a few things to do before you can start. 1. Declare your application as "debuggable" in your An droid Manifest. In Eclipse, you can do this from the Application tab when viewin g the Manifest (on the right side, set Debuggable to true). Otherwise, in the An droidManifest.xml file, add android:debuggable="true" to the <application> eleme nt. 2. Turn on "USB Debugging" on your device. On the device, go to the home scr een, press MENU, select Applications > Development, then enable USB debugging. 3 . Setup your system to detect your device. If you're developing on 32-bit Window s, you need to install the 32-bit USB driver for adb. The USB driver is included in the SDK package. To install it, follow these steps: 1. Connect your Android device via USB. When the Found New Hardware Wizard appears, you'll be asked if y ou'd like Windows Update to search for software. Select No, not this time and cl ick Next. 2. Select Install from a list or specified location and click Next. 3. Select Search for the best driver in these locations. Browse to the usb_driver/ x86 in the SDK package (<sdk>\usb_driver\x86). 4. Click Finish. The system shoul d install the driver files as necessary. Your machine may require a reboot. If y ou're developing on 64-bit Windows Vista, you need to install the 64-bit USB dri ver for adb. The USB driver is included in the SDK package. To install it, follo w these steps: 1. Connect your Android device via USB. When the Found New Hardwa re Wizard appears, you'll be asked if you'd like Windows Update to search for so ftware. Select No, not this time and click Next. 2. Select Install from a list o r specified location and click Next. 3. Select Search for the best driver in the se locations. Browse to the usb_driver/amd64 in the SDK package (<sdk>\usb_drive r\amd64). 4. Click Finish. The system should install the driver files as necessa ry. Your machine may require a reboot. If you're developing on Mac OS X, it just works. Skip this step. If you're developing on Ubuntu Linux, you need to add a rules file: 1. Login as root and create this file: /etc/udev/rules.d/50-android. rules. For Gusty/Hardy, edit the file to read: SUBSYSTEM=="usb", SYSFS{idVendor} =="0bb4", MODE="0666" For Dapper, edit the file to read: SUBSYSTEM=="usb_device" , SYSFS{idVendor}=="0bb4", MODE="0666" 2. Now execute: chmod a+rx /etc/udev/rule s.d/50-android.rules You can verify that your device is connected by executing a db devices from your SDK tools/ directory. If connected, you'll see the device n ame listed as a "device." If using Eclipse, select run or debug as usual. You wi ll be presented with a Device Chooser dialog that lists the available emulator(s ) and connected device(s). Select the device to install and run the application there. http://developer.android.com/guide/developing/device.html Page 2 of 3

Developing on a Device | Android Developers 29.04.09 0:50 If using the Android Debug Bridge (adb), you can issue commands with the -d flag to target your connected device. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/device.html Page 3 of 3

Debugging Tasks | Android Developers 29.04.09 0:50 Debugging Tasks This document offers some helpful guidance to debugging applications on Android. Tools The Android SDK includes a fairly extensive set of tools to help you debug your programs: DDMS - A graphical program that supports port forwarding (so you can s et up breakpoints in your code in your IDE), screen captures on the emulator, th read and stack information, and many other features. You can also run logcat to retrieve your Log messages. See the linked topic for more information. logcat Dumps a log of system messages. The messages include a stack trace when the emul ator throws an error, as well as Log messages. To run logcat, see the linked top ic. ... I/MemoryDealer( 763): MemoryDealer (this=0x54bda0): Creating 2621440 byt es heap at 0x438db000 I/Logger( 1858): getView() requesting item number 0 I/Logg er( 1858): getView() requesting item number 1 I/Logger( 1858): getView() request ing item number 2 D/ActivityManager( 763): Stopping: HistoryRecord{409dbb20 com. android.home.AllApps} ... Android Log- A logging class to print out messages to a log file on the emulator. You can read messages in real time if you run logcat on DDMS (covered next). Add a few logging method calls to your code. To use the Log class, you just call Log.v() (verbose), Log.d() (debug), Log.i() (informati on), Log.w() (warning) or Log.e (error) depending on the importance you wish to assign the log message. Log.i("MyActivity", "MyClass.getView() Requesting item n umber " + position) You can use logcat to read these messages Traceview - Androi d can save a log of method calls and times to a logging file that you can view i n a graphical reader called Traceview. See the linked topic for more information . Eclipse plugin - The ADT Plugin for Eclipse integrates a number of these tools (ADB, DDMS, logcat output, and other functionality). See the linked topic for m ore information. Debug and Test Device Settings - Android exposes several settin gs that expose useful information such as CPU usage and frame rate. See Debug an d Test Settings on the Emulator below. Also, see the Troubleshooting section of the doc to figure out why your application isn't appearing on the emulator, or w hy it's not starting. Debug and Test Settings With the Dev Tools application, you can turn on a number of settings that will m ake it easier to test and debug your applications. To get to the development set tings page on the emulator, launch the Dev Tools application and open Developmen t Settings. This will open the development settings page with the following opti ons (among others): http://developer.android.com/guide/developing/debug-tasks.html Page 1 of 3

Debugging Tasks | Android Developers 29.04.09 0:50 Development Settings. This will open the development settings page with the foll owing options (among others): Debug app Selects the application that will be deb ugged. You do not need to set this to attach a debugger, but setting this value has two effects: It will prevent Android from throwing an error if you pause on a breakpoint for a long time while debugging. It will enable you to select the W ait for Debugger option to pause application startup until your debugger attache s (described next). Wait for debugger Blocks the selected application from loadi ng until a debugger attaches. This way you can set a breakpoint in onCreate(), w hich is important to debug the startup process of an Activity. When you change t his option, any currently running instances of the selected application will be killed. In order to check this box, you must have selected a debug application a s described in the previous option. You can do the same thing by adding waitForD ebugger() to your code. Immediately destroy activities Tells the system to destr oy an activity as soon as it is stopped (as if Android had to reclaim memory). T his is very useful for testing the onSaveInstanceState(Bundle) / onCreate(androi d.os.Bundle) code path, which would otherwise be difficult to force. Choosing th is option will probably reveal a number of problems in your application due to n ot saving state. Show screen updates Flashes a momentary pink rectangle on any s creen sections that are being redrawn. This is very useful for discovering unnec essary screen drawing. Show CPU usage Displays CPU meters at the top of the scre en, showing how much the CPU is being used. The top red bar shows overall CPU us age, and the green bar underneath it shows the CPU time spent in compositing the screen. Note: You cannot turn this feature off once it is on, without restartin g the emulator. Show background Displays a background pattern when no activity s creens are visible. This typically does not happen, but can happen during debugg ing. These settings will be remembered across emulator restarts. Top Debugging Tips Quick stack dump To obtain a stack dump from emulator, you can log in with adb s hell, use "ps" to find the process you want, and then "kill -3 ". The stack trac e appears in the log file. Displaying useful info on the emulator screen The dev ice can display useful information such as CPU usage or highlights around redraw n areas. Turn these features on and off in the developer settings window as desc ribed in Setting debug and test configurations on the emulator. Getting system s tate information from the emulator (dumpstate) You can access dumpstate informat ion from the Dalvik Debug Monitor Service tool. See dumpsys and dumpstate on the adb topic page. Getting application state information from the emulator (dumpsy s) You can access dumpsys information from the Dalvik Debug Monitor Service tool . See dumpsys and dumpstate on the adb topic page. Getting wireless connectivity information You can get information about wireless connectivity using the Dalvi k Debug Monitor Service tool. From the Device menu, select "Dump radio state". L ogging Trace Data You can log method calls and other tracing data in an activity by calling android.os.Debug.startMethodTracing(). See Running the Traceview Deb ugging Program for details. http://developer.android.com/guide/developing/debug-tasks.html Page 2 of 3

Debugging Tasks | Android Developers 29.04.09 0:50 Logging Radio Data By default, radio information is not logged to the system (it is a lot of data). However, you can enable radio logging using the following co mmands: adb shell logcat -b radio Running adb Android ships with a tool called a db that provides various capabilities, including moving and syncing files to the emulator, forwarding ports, and running a UNIX shell on the emulator. See Using adb for details. Getting screen captures from the emulator Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Using debugging helper classes Android provides debug helper classes such as util.Log and Debug for yo ur convenience. Configuring Your IDE to Attach to the Debugging Port DDMS will assign a specific debugging port to every virtual machine that it find s on the emulator. You must either attach your IDE to that port (listed on the I nfo tab for that VM), or you can use a default port 8700 to connect to whatever application is currently selected on the list of discovered virtual machines. Yo ur IDE should attach to your application running on the emulator, showing you it s threads and allowing you to suspend them, inspect their state, and set breakpo ints. If you selected "Wait for debugger" in the Development settings panel the application will run when Eclipse connects, so you will need to set any breakpoi nts you want before connecting. Changing either the application being debugged o r the "Wait for debugger" option causes the system to kill the selected applicat ion if it is currently running. You can use this to kill your application if it is in a bad state by simply going to the settings and toggling the checkbox. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/debug-tasks.html Page 3 of 3

Tools Overview | Android Developers 29.04.09 0:53 Tools Overview The Android SDK includes a variety of custom tools that help you develop mobile applications on the Android platform. The most important of these are the Androi d Emulator and the Android Development Tools plugin for Eclipse, but the SDK als o includes a variety of other tools for debugging, packaging, and installing you r applications on the emulator. Android Development Tools Plugin (for the Eclips e IDE) The ADT plugin adds powerful extensions to the Eclipse integrated environ ment, making creating and debugging your Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications. Android Emulator A QEMU-based device-emulation tool that y ou can use to design, debug, and test your applications in an actual Android run -time environment. Android Virtual Devices (AVDs) Virtual device configurations that you create, to model device characteristics in the Android Emulator. In eac h configuration, you can specify the Android platform to run, the hardware optio ns, and the emulator skin to use. Each AVD functions as an independent device wi th it's own storage for user data, SD card, and so on. Hierarchy Viewer The Hier archy Viewer tool allows you to debug and optimize your user interface. It provi des a visual representation of your layout's hierarchy of Views and a magnified inspector of the current display with a pixel grid, so you can get your layout j ust right. Draw 9-patch The Draw 9-patch tool allows you to easily create a Nine Patch graphic using a WYSIWYG editor. It also previews stretched versions of the image, and highlights the area in which content is allowed. Dalvik Debug Monito r Service (ddms) Integrated with Dalvik, the Android platform's custom VM, this tool lets you manage processes on an emulator or device and assists in debugging . You can use it to kill processes, select a specific process to debug, generate trace data, view heap and thread information, take screenshots of the emulator or device, and more. Android Debug Bridge (adb) The adb tool lets you install yo ur application's .apk files on an emulator or device and access the emulator or device from a command line. You can also use it to link a standard debugger to a pplication code running on an Android emulator or device. Android Asset Packagin g Tool (aapt) The aapt tool lets you create .apk files containing the binaries a nd resources of Android applications. Android Interface Description Language (ai dl) Lets you generate code for an interprocess interface, such as what a service might use. sqlite3 Included as a convenience, this tool lets you access the SQL ite data files created and used by Android applications. Traceview This tool pro duces graphical analysis views of trace log data that you can generate from your Android application. http://developer.android.com/guide/developing/tools/index.html Page 1 of 2

Tools Overview | Android Developers 29.04.09 0:53 mksdcard Helps you create a disk image that you can use with the emulator, to si mulate the presence of an external storage card (such as an SD card). dx The dx tool rewrites .class bytecode into Android bytecode (stored in .dex files.) UI/A pplication Exerciser Monkey The Monkey is a program that runs on your emulator o r device and generates pseudo-random streams of user events such as clicks, touc hes, or gestures, as well as a number of system- level events. You can use the M onkey to stress-test applications that you are developing, in a random yet repea table manner. android A script that lets you manage AVDs and generate Ant build files that you can use to compile your Android applications. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/index.html Page 2 of 2

Using aapt | Android Developers 29.04.09 0:53 Using aapt aapt stands for Android Asset Packaging Tool and is included in the tools/ direc tory of the SDK. This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets. Tho ugh you probably won't often use aapt directly, build scripts and IDE plugins ca n utilize this tool to package the apk file that constitutes an Android applicat ion. For more usage details, open a terminal, go to the tools/ directory, and ru n the command: Linux or Mac OS X: ./aapt Windows: aapt.exe ! Go to top Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines http://developer.android.com/guide/developing/tools/aapt.html Page 1 of 1

Android Debug Bridge | Android Developers 29.04.09 0:53 Android Debug Bridge Android Debug Bridge (adb) is a versatile tool lets you manage the state of an e mulator instance or Android-powered device. It is a client-server program that i ncludes three components: A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients. A server, which runs as a background process on your development machine. The server manages communicat ion between the client and the adb daemon running on an emulator or device. A da emon, which runs as a background process on each emulator or device instance. Wh en you start an adb client, the client first checks whether there is an adb serv er process already running. If there isn't, it starts the server process. When t he server starts, it binds to local TCP port 5037 and listens for commands sent from adb clientsall adb clients use port 5037 to communicate with the adb server. The server then sets up connections to all running emulator/device instances. I t locates emulator/device instances by scanning odd-numbered ports in the range 5555 to 5585, the range used by emulators/devices. Where the server finds an adb daemon, it sets up a connection to that port. Note that each emulator/device in stance acquires a pair of sequential ports an even-numbered port for console con nections and an odd-numbered port for adb connections. For example: Emulator Emu lator Emulator Emulator 1, 1, 2, 2, console: 5554 adb: 5555 console: 5556 adb: 5 557 ... As shown, the emulator instance connected to adb on port 5555 is the same as the instance whose console listens on port 5554. Once the server has set up connect ions to all emulator instances, you can use adb commands to control and access t hose instances. Because the server manages connections to emulator/device instan ces and handles commands from multiple adb clients, you can control any emulator /device instance from any client (or from a script). The sections below describe the commands that you can use to access adb capabilities and manage the state o f an emulator/device. Note that if you are developing Android applications in Ec lipse and have installed the ADT plugin, you do not need to access adb from the command line. The ADT plugin provides a trasparent integration of adb into the E clipse IDE. However, you can still use adb directly as necessary, such as for de bugging. Issuing adb Commands You can issue adb commands from a command line on your development machine or fr om a script. The usage is: adb [-d|-e|-s <serialNumber>] <command> When you issu e a command, the program invokes an adb client. The client is not specifically a ssociated with any emulator instance, so if multiple emulators/devices are runni ng, you need to use the -d option to specify the target instance to which the co mmand should be directed. For more information about using this option, see Dire cting Commands to a Specific Emulator/Device Instance. http://developer.android.com/guide/developing/tools/adb.html Page 1 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 Querying for Emulator/Device Instances Before issuing adb commands, it is helpful to know what emulator/device instance s are connected to the adb server. You can generate a list of attached emulators /devices using the devices command: adb devices In response, adb prints this sta tus information for each instance: Serial number A string created by adb to uniq uely identify an emulator/device instance by its console port number. The format of the serial number is <type>-<consolePort>. Here's an example serial number: emulator-5554 State The connection state of the instance. Three states are suppo rted: offline the instance is not connected to adb or is not responding. device the instance is now connected to the adb server. Note that this state does not i mply that the Android system is fully booted and operational, since the instance connects to adb while the system is still booting. However, after boot-up, this is the normal operational state of an emulator/device instance. The output for each instance is formatted like this: [serialNumber] [state] Here's an example s howing the devices command and its output: $ adb devices List of devices attache d emulator-5554 device emulator-5556 device emulator-5558 device If there is no emulator/device running, adb returns no device. Directing Commands to a Specific Emulator/Device Instance If multiple emulator/device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is: adb -s <serialNumber> <command> As shown, you s pecify the target instance for a command using its adb-assigned serial number. Y ou can use the devices command to obtain the serial numbers of running emulator/ device instances. Here is an example: adb -s emulator-5556 install helloWorld.ap k Note that, if you issue a command without specifying a target emulator/device instance using -s, adb generates an error. http://developer.android.com/guide/developing/tools/adb.html Page 2 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 Installing an Application You can use adb to copy an application from your development computer and instal l it on an emulator/device instance. To do so, use the install command. With the command, you must specify the path to the .apk file that you want to install: a db install <path_to_apk> For more information about how to create an .apk file t hat you can install on an emulator/device instance, see Android Asset Packaging Tool (aapt). Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your applic ation on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you. Forwarding Ports You can use the forward command to set up arbitrary port forwarding forwarding o f requests on a specific host port to a different port on an emulator/device ins tance. Here's how you would set up forwarding of host port 6100 to emulator/devi ce port 7100: adb forward tcp:6100 tcp:7100 You can also use adb to set up forwa rding to named abstract UNIX domain sockets, as illustrated here: adb forward tc p:6100 local:logd Copying Files to or from an Emulator/Device Instance You can use the adb commands pull and push to copy files to and from an emulator /device instance's data file. Unlike the install command, which only copies an . apk file to a specific location, the pull and push commands let you copy arbitra ry directories and files to any location in an emulator/device instance. To copy a file or directory (recursively) from the emulator or device, use adb pull <re mote> <local> To copy a file or directory (recursively) to the emulator or devic e, use adb push <local> <remote> In the commands, <local> and <remote> refer to the paths to the target files/directory on your development machine (local) and on the emulator/device instance (remote). Here's an example: adb push foo.txt /s dcard/foo.txt http://developer.android.com/guide/developing/tools/adb.html Page 3 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 Listing of adb Commands The table below lists all of the supported adb commands and explains their meani ng and usage. Category Options Command -d Description Direct an adb command to t he only attached USB device. Direct an adb command to the only running emulator instance. Comments Returns an error if more than one USB device is attached. Ret urns an error if more than one emulator instance is running. If not specified, a db generates an error. -e -s <serialNumber> Direct an adb command a specific emulator/device instance, referred to by its ad b-assigned serial number (such as "emulator-5556"). Prints a list of all attache d emulator/device instances. General devices See Querying for Emulator/Device Instances for more information. help version Debug logcat [<option>] [<filter-specs>] bugreport Prints a list of supported adb commands. Prints the adb version number. Prints l og data to the screen. Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting. Prints a list of available JDWP processes on a given device. You can use the forward jdwp:<pid> portforwarding specification to connect to a specific JDWP process. For example: adb forward tcp:8000 jdwp:4 72 jdb -attach localhost:8000 jdwp Data install <path-to-apk> Pushes an Android application (specified as a full path to an .apk file) to the data file of an emulator/device. Copies a specified file from an emulator/device instance to your development computer. Copies a specified file from your develo pment computer to an emulator/device instance. Page 4 of 11 pull <remote> <local> push <local> <remote> http://developer.android.com/guide/developing/tools/adb.html

Android Debug Bridge | Android Developers 29.04.09 0:53 Ports and Networking forward <local> <remote> Forwards socket connections from a specified local port to a specified remote po rt on the emulator/device instance. Port specifications can use these schemes: tcp:<portnum> local:<UNIX domain sock et name> dev:<character device name> jdwp:<pid> ppp <tty> [parm]... Run PPP over USB. <tty> the tty for PPP stream. For example dev:/dev/omap_csmi_t tyl. [parm]... zero or more PPP/PPPD options, such as defaultroute, local, notty , etc. Note that you should not automatically start a PDP connection. Scripting get-serialno get-state wait-for-device Prints the adb instance serial number string. Prints the adb state of an emulato r/device instance. Blocks execution until the device is online that is, until th e instance state is device. See Querying for Emulator/Device Instances for more information. You can prepend this command to other adb commands, in which case adb will wait until the emula tor/device instance is connected before issuing the other commands. Here's an ex ample: adb waitfor-device shell getprop Note that this command does not cause ad b to wait until the entire system is fully booted. For that reason, you should n ot prepend it to other commands that require a fully booted system. As an exampl e, the install requires the Android package manager, which is http://developer.android.com/guide/developing/tools/adb.html Page 5 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 available only after the system is fully booted. A command such as adb waitfor-d evice install <app>.apk would issue the install command as soon as the emulator or device instance connected to the adb server, but before the Android system wa s fully booted, so it would result in an error. Server start-server Checks wheth er the adb server process is running and starts it, if not. Terminates the adb s erver process. Starts a remote shell in the target emulator/device instance. Iss ues a shell command in the target emulator/device instance and then exits the re mote shell. See Issuing Shell Commands for more information. kill-server Shell shell shell [<shellCommand>] Issuing Shell Commands Adb provides an ash shell that you can use to run a variety of commands on an em ulator or device. The command binaries are stored in the file system of the emul ator or device, in this location: /system/bin/... You can use the shell command to issue commands, with or without entering the adb remote shell on the emulator /device. To issue a single command without entering a remote shell, use the shel l command like this: adb [-d|-e|-s {<serialNumber>}] shell <shellCommand> To dro p into a remote shell on a emulator/device instance, use the shell command like this: adb [-d|-e|-s {<serialNumber>}] shell When you are ready to exit the remot e shell, use CTRL+D or exit to end the shell session. The sections below provide more information about shell commands that you can use. Examining sqlite3 Databases from a Remote Shell http://developer.android.com/guide/developing/tools/adb.html Page 6 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite databases created by Android applications. The sqlite3 tool includes man y useful commands, such as .dump to print out the contents of a table and .schem a to print the SQL CREATE statement for an existing table. The tool also gives y ou the ability to execute SQLite commands on the fly. To use sqlite3, enter a re mote shell on the emulator instance, as described above, then invoke the tool us ing the sqlite3 command. Optionally, when invoking sqlite3 you can specify the f ull path to the database you want to explore. Emulator/device instances store SQ Lite3 databases in the folder /data/data/<package_name>/databases/. Here's an ex ample: $ adb -s emulator-5554 shell # sqlite3 /data/data/com.example.google.rss. rssexample/databases/rssitems.db SQLite version 3.3.12 Enter ".help" for instruc tions .... enter commands, then quit... sqlite> .exit Once you've invoked sqlite 3, you can issue sqlite3 commands in the shell. To exit and return to the adb re mote shell, use exit or CTRL+D. UI/Application Exerciser Monkey The Monkey is a program that runs on your emulator or device and generates pseud o-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stresstest applicati ons that you are developing, in a random yet repeatable manner. The simplest way to use the monkey is with the following command, which will launch your applica tion and send 500 pseudo-random events to it. $ adb shell monkey -v -p your.pack age.name 500 For more information about command options for Monkey, see the comp lete UI/Application Exerciser Monkey documentation page. Other Shell Commands The table below lists several of the adb shell commands available. For a complet e list of commands and programs, start an emulator instance and use the adb -hel p command. adb shell ls /system/bin Help is available for most of the commands. Shell Command dumpsys dumpstate logcat [<option>]... [<filterspec>]... Descripti on Dumps system data to the screen. Dumps state to a file. Enables radio logging and prints output to the screen. Page 7 of 11 Comments The Dalvik Debug Monitor Service (DDMS) tool offers integrated debug en vironment that you may find easier to use. http://developer.android.com/guide/developing/tools/adb.html

Android Debug Bridge | Android Developers 29.04.09 0:53 dmesg Prints kernel debugging messages to the screen. Starts (restarts) an emulator/de vice instance. Stops execution of an emulator/device instance. start stop Enabling logcat Logging The Android logging system provides a mechanism for collecting and viewing syste m debug output. Logs from various applications and portions of the system are co llected in a series of circular buffers, which then can be viewed and filtered b y the logcat command. Using logcat Commands You can use the logcat command to view and follow the contents of the system's l og buffers. The general usage is: [adb] logcat [<option>] ... [<filter-spec>] .. . The sections below explain filter specifications and the command options. See Listing of logcat Command Options for a summary of options. You can use the logc at command from your development computer or from a remote adb shell in an emula tor/device instance. To view log output in your development computer, you use $ adb logcat and from a remote adb shell you use # logcat Filtering Log Output Every Android log message has a tag and a priority associated with it. The tag o f a log message is a short string indicating the system component from which the message originates (for example, "View" for the view system). The priority is o ne of the following character values, ordered from lowest to highest priority: V Verbose (lowest priority) D Debug I Info W Warning E Error F Fatal http://developer.android.com/guide/developing/tools/adb.html Page 8 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 S Silent (highest priority, on which nothing is ever printed) You can obtain a l ist of tags used in the system, together with priorities, by running logcat and observing the first two columns of each message, given as <priority>/<tag>. Here 's an example of logcat output that shows that the message relates to priority l evel "I" and tag "ActivityManager": I/ActivityManager( 585): Starting activity: Intent { action=android.intent.action...} To reduce the log output to a manageab le level, you can restrict log output using filter expressions. Filter expressio ns let you indicate to the system the tags-priority combinations that you are in terested in the system suppresses other messages for the specified tags. A filte r expression follows this format tag:priority ..., where tag indicates the tag o f interest and priority indicates the minimum level of priority to report for th at tag. Messages for that tag at or above the specified priority are written to the log. You can supply any number of tag:priority specifications in a single fi lter expression. The series of specifications is whitespace-delimited. Here's an example of a filter expression that suppresses all log messages except those wi th the tag "ActivityManager", at priority "Info" or above, and all log messages with tag "MyApp", with priority "Debug" or above: adb logcat ActivityManager:I M yApp:D *:S The final element in the above expression, *:S, sets the priority lev el for all tags to "silent", thus ensuring only log messages with "View" and "My App" are displayed. Using *:S is an excellent way to ensure that log output is r estricted to the filters that you have explicitly specified it lets your filters serve as a "whitelist" for log output. The following filter expression displays all log messages with priority level "warning" and higher, on all tags: adb log cat *:W If you're running logcat from your development computer (versus running it on a remote adb shell), you can also set a default filter expression by expor ting a value for the environment variable ANDROID_LOG_TAGS: export ANDROID_LOG_T AGS="ActivityManager:I MyApp:D *:S" Note that ANDROID_LOG_TAGS filter is not exp orted to the emulator/device instance, if you are running logcat from a remote s hell or using adb shell logcat. Controlling Log Output Format Log messages contain a number of metadata fields, in addition to the tag and pri ority. You can modify the output format for messages so that they display a spec ific metadata field. To do so, you use the -v option and specify one of the supp orted output formats listed below. brief Display priority/tag and PID of origina ting process (the default format). process Display PID only. tag Display the pri ority/tag only. thread Display process:thread and priority/tag only. raw Display the raw log message, with no other metadata fields. time Display the date, invo cation time, priority/tag, and PID of the originating process. long Display all metadata fields and separate messages with a blank lines. http://developer.android.com/guide/developing/tools/adb.html Page 9 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 When starting logcat, you can specify the output format you want by using the -v option: [adb] logcat [-v <format>] Here's an example that shows how to generate messages in thread output format: adb logcat -v thread Note that you can only s pecify one output format with the -v option. Viewing Alternative Log Buffers The Android logging system keeps multiple circular buffers for log messages, and not all of the log messages are sent to the default circular buffer. To see add itional log messages, you can start logcat with the -b option, to request viewin g of an alternate circular buffer. You can view any of these alternate buffers: radio View the buffer that contains radio/telephony related messages. events Vie w the buffer containing events-related messages. main View the main log buffer ( default) The usage of the -b option is: [adb] logcat [-b <buffer>] Here's an exa mple of how to view a log buffer containing radio and telephony messages: adb lo gcat -b radio Viewing stdout and stderr By default, the Android system sends stdout and stderr (System.out and System.er r) output to /dev/null. In processes that run the Dalvik VM, you can have the sy stem write a copy of the output to the log file. In this case, the system writes the messages to the log using the log tags stdout and stderr, both with priorit y I. To route the output in this way, you stop a running emulator/device instanc e and then use the shell command setprop to enable the redirection of output. He re's how you do it: $ adb shell stop $ adb shell setprop log.redirect-stdio true $ adb shell start The system retains this setting until you terminate the emula tor/device instance. To use the setting as a default on the emulator/device inst ance, you can add an entry to /data/local.prop on the device. Listing of logcat Command Options Option -b <buffer> -c Description Loads an alternate log buffer for viewing, suc h as event or radio. The main buffer is used by default. See Viewing Alternative Log Buffers. Clears (flushes) the entire log and exits. http://developer.android.com/guide/developing/tools/adb.html Page 10 of 11

Android Debug Bridge | Android Developers 29.04.09 0:53 -d f <filename> -g -n <count> -r <kbytes> -s -v <format> Dumps the log to the screen and exits. Writes log message output to <filename>. The default is stdout. Prints the size of the specified log buffer and exits. Se ts the maximum number of rotated logs to <count>. The default value is 4. Requir es the -r option. Rotates the log file every <kbytes> of output. The default val ue is 16. Requires the -f option. Sets the default filter spec to silent. Sets t he output format for log messages. The default is brief format. For a list of su pported formats, see Controlling Log Output Format. Stopping the adb Server In some cases, you might need to terminate the adb server process and then resta rt it. For example, if adb does not respond to a command, you can terminate the server and restart it and that may resolve the problem. To stop the adb server, use the kill-server. You can then restart the server by issuing any adb command. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/adb.html Page 11 of 11

Other Tools | Android Developers 29.04.09 0:54 Other Tools The sections below describe other tools that you can use when building Android a pplications. All of the tools are included in the Android SDK and are accessible from the <sdk>/tools/ directory. Contents android mksdcard dx android The android tool is a script that lets you create and manage Android Virtual Dev ices (AVDs) and, if you are developing using Ant, generate template Android proj ects to help you get started quickly. For information about how to use the andro id tool to manage AVDs, see Android Virtual Devices. For information about how t o use the android tool to create or update a project, see Developing in Other ID Es. Note that if you are developing in Eclipse with the ADT plugin, you will use the android tool to manage the AVDs you create, but you will not use the androi d tool for creating a project. The ADT plugin provides a New Project Wizard that helps you set up an Android project in Eclipse. If you are developing in Ant, y ou will use the android tool to manage your AVDs, and you can also use it to cre ate or update a project. Note: The android tool replaces the activitycreator too l provided in previous SDK releases. mksdcard The mksdcard tool lets you quickly create a FAT32 disk image that you can load i n the emulator, to simulate the presence of an SD card in the device. Here is th e usage for mksdcard: mksdcard [-l label] <size>[K|M] <file> The table below lis ts the available options/arguments Argument -l size Description A volume label f or the disk image to create. An integer that specifies the size (in bytes) of di sk image to create. You can also specify size in kilobytes or megabytes, by appe nding a "K" or "M" to <size>. For example, 1048576K, 1024M. Page 1 of 2 http://developer.android.com/guide/developing/tools/othertools.html#android

Other Tools | Android Developers 29.04.09 0:54 file The path/filename of the disk image to create. Once you have created the disk image file, you can load it in the emulator at st artup using the emulator's -sdcard option. For more information, see Android Emu lator. emulator -sdcard <file> dx The dx tool lets you generate Android bytecode from .class files. The tool conve rts target files and/or directories to Dalvik executable format (.dex) files, so that they can run in the Android environment. It can also dump the class files in a human-readable format and run a target unit test. You can get the usage and options for this tool by using dx -help. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/othertools.html#android Page 2 of 2

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 Designing a Remote Interface Using AIDL Since each application runs in its own process, and you can write a service that runs in a different process from your Application's UI, sometimes you need to p ass objects between processes. On the Android platform, one process can not norm ally access the memory of another process. So to talk, they need to decompose th eir objects into primitives that the operating system can understand, and "marsh all" the object across that boundary for you. The code to do that marshalling is tedious to write, so we provide the AIDL tool to do it for you. AIDL (Android I nterface Definition Language) is an IDL language used to generate code that enab les two processes on an Android-powered device to talk using interprocess commun ication (IPC). If you have code in one process (for example, in an Activity) tha t needs to call methods on an object in another process (for example, a Service) , you would use AIDL to generate code to marshall the parameters. The AIDL IPC m echanism is interface-based, similar to COM or Corba, but lighter weight. It use s a proxy class to pass values between the client and the implementation. This p age includes the following main topics: Implementing IPC Using AIDL Calling an . aidl (IPC) Class Implementing IPC Using AIDL Follow these steps to implement an IPC service using AIDL. 1. Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the meth ods and fields available to a client. 2. Add the .aidl file to your makefile - ( the ADT Plugin for Eclipse manages this for you). Android includes the compiler, called AIDL, in the tools/ directory. 3. Implement your interface methods - The AIDL compiler creates an interface in the Java programming language from your A IDL interface. This interface has an inner abstract class named Stub that inheri ts the interface (and implements a few additional methods necessary for the IPC call). You must create a class that extends YourInterface.Stub and implements th e methods you declared in your .aidl file. 4. Expose your interface to clients If you're writing a service, you should extend Service and override Service.onB ind(Intent) to return an instance of your class that implements your interface. Create an .aidl File AIDL is a simple syntax that lets you declare an interface with one or more meth ods, that can take parameters and return values. These parameters and return val ues can be of any type, even other AIDL-generated interfaces. However, it is imp ortant to note that you must import all non-built-in types, even if they are def ined in the same package as your interface. Here are the data types that AIDL ca n support: Primitive Java programming language types (int, boolean, etc) No impo rt statement is needed. One of the following classes (no import statements neede d): http://developer.android.com/guide/developing/tools/aidl.html Page 1 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 String List - All elements in the List must be one of the types in this list, in cluding other AIDL-generated interfaces and parcelables. List may optionally be used as a "generic" class (e.g. List<String>). The actual concrete class that th e other side will receive will always be an ArrayList, although the method will be generated to use the List interface. Map - All elements in the Map must be of one of the types in this list, including other AIDL-generated interfaces and pa rcelables. Generic maps, (e.g. of the form Map<String,Integer> are not supported . The actual concrete class that the other side will receive will always be a Ha shMap, although the method will be generated to use the Map interface. CharSeque nce - This is useful for the CharSequence types used by TextView and other widge t objects. Other AIDL-generated interfaces, which are always passed by reference . An import statement is always needed for these. Custom classes that implement the Parcelable protocol and are passed by value. An import statement is always n eeded for these. Here is the basic AIDL syntax: // // // // // My AIDL file, nam ed SomeClass.aidl Note that standard comment syntax is respected. Comments befor e the import or package statements are not bubbled up to the generated interface , but comments above interface/method/field declarations are added to the genera ted interface. // Include your fully-qualified package statement. package com.android.sample; / / See the list above for which classes need // import statements (hint--most of them) import com.android.sample.IAtmService; // Declare the interface. interface IBankAccountService { // Methods can take 0 or more parameters, and // return a value or void. int getAccountBalance(); void setOwnerNames(in List<String> name s); // Methods can even take other AIDL-defined parameters. BankAccount createAc count(in String name, int startingDeposit, in IAtmService atmService); // All no n-Java primitive parameters (e.g., int, bool, etc) require // a directional tag indicating which way the data will go. Available // values are in, out, inout. ( Primitives are in by default, and cannot be otherwise). // Limit the direction t o what is truly needed, because marshalling parameters // is expensive. int getC ustomerList(in String branch, out String[] customerList); } Implementing the Interface AIDL generates an interface file for you with the same name as your .aidl file. If you are using the Eclipse plugin, AIDL will automatically be run as part of t he build process (you don't need to run AIDL first and then build your project). If you are not using the plugin, you should run AIDL first. The generated inter face includes an abstract inner class named Stub that declares all the methods t hat you declared in your .aidl file. Stub also defines a few helper methods, mos t notably asInterface(), which takes an IBinder (passed to a client's onServiceC onnected() implementation when applicationContext.bindService() succeeds), and r eturns an instance of the interface used to call the IPC methods. See the sectio n Calling an IPC Method for more details on how http://developer.android.com/guide/developing/tools/aidl.html Page 2 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 instance of the interface used to call the IPC methods. See the section Calling an IPC Method for more details on how to make this cast. To implement your inter face, extend YourInterface.Stub, and implement the methods. (You can create the .aidl file and implement the stub methods without building between--the Android build process will process .aidl files before .java files.) Here is an example o f implementing an interface called IRemoteService, which exposes a single method , getPid(), using an anonymous instance: // No need to import IRemoteService if it's in the same project. private final IRemoteService.Stub mBinder = new IRemot eService.Stub(){ public int getPid(){ return Process.myPid(); } } A few rules ab out implementing your interface: No exceptions that you throw will be sent back to the caller. IPC calls are synchronous. If you know that an IPC service takes more than a few milliseconds to complete, you should not call it in the Activity /View thread, because it might hang the application (Android might display an "A pplication is Not Responding" dialog). Try to call them in a separate thread. On ly methods are supported; you cannot declare static fields in an AIDL interface. Exposing Your Interface to Clients Now that you've got your interface implementation, you need to expose it to clie nts. This is known as "publishing your service." To publish a service, inherit S ervice and implement Service.onBind(Intent) to return an instance of the class t hat implements your interface. Here's a code snippet of a service that exposes t he IRemoteService interface to clients. public class RemoteService extends Servi ce { ... @Override public IBinder onBind(Intent intent) { // Select the interfac e to return. If your service only implements // a single interface, you can just return it here without checking // the Intent. if (IRemoteService.class.getName ().equals(intent.getAction())) { return mBinder; } if (ISecondary.class.getName( ).equals(intent.getAction())) { return mSecondaryBinder; } return null; } /** * The IRemoteInterface is defined through IDL */ private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public void registerCallback(IRemoteServi ceCallback cb) { if (cb != null) mCallbacks.register(cb); } public void unregist erCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.unregister(cb ); } }; /** * A secondary interface to the service. http://developer.android.com/guide/developing/tools/aidl.html Page 3 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 * A secondary interface to the service. */ private final ISecondary.Stub mSecond aryBinder = new ISecondary.Stub() { public int getPid() { return Process.myPid() ; } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat , double aDouble, String aString) { } }; } Pass by value Parameters using Parcelables If you have a class that you would like to send from one process to another thro ugh an AIDL interface, you can do that. You must ensure that the code for your c lass is available to the other side of the IPC. Generally, that means that you'r e talking to a service that you started. There are five parts to making a class support the Parcelable protocol: 1. Make your class implement the Parcelable int erface. 2. Implement the method public void writeToParcel(Parcel out) that takes the current state of the object and writes it to a parcel. 3. Implement the met hod public void readFromParcel(Parcel in) that reads the value in a parcel into your object. 4. Add a static field called CREATOR to your class which is an obje ct implementing the Parcelable.Creator interface. 5. Last but not least: If you are developing with Eclipse/ADT, follow these steps: a. In the Package Explorer view, right-click on the project. b. Choose Android Tools > Create Aidl preproce ss file for Parcelable classes. c. This will create a file called "project.aidl" in the root of the project. The file will be automatically used when compiling an aidl file that uses the parcelable classes. If you are developing with Ant or are using a custom build process, create an aidl file that declares your parcel able class (as shown below). If you are using a custom build process, do not add the aidl file to your build. Similar to a header file in C, the aidl file isn't compiled. AIDL will use these methods and fields in the code it generates to ma rshall and unmarshall your objects. Here is an example of how the Rect class imp lements the Parcelable protocol. import android.os.Parcel; import android.os.Par celable; public final class Rect implements Parcelable { public int left; public int top; public int right; public int bottom; public static final Parcelable.Cr eator<Rect> CREATOR = new Parcelable.Creator<Rect>() { public Rect createFromPar cel(Parcel in) { return new Rect(in); } public Rect[] newArray(int size) { retur n new Rect[size]; } http://developer.android.com/guide/developing/tools/aidl.html Page 4 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 }; public Rect() { } private Rect(Parcel in) { readFromParcel(in); } public void writeToParcel(Parcel out) { out.writeInt(left); out.writeInt(top); out.writeInt (right); out.writeInt(bottom); } public void readFromParcel(Parcel in) { left = in.readInt(); top = in.readInt(); right = in.readInt(); bottom = in.readInt(); } } Here is Rect.aidl for this example package android.graphics; // Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. par celable Rect; The marshalling in the Rect class is pretty simple. Take a look at the other methods on Parcel to see the other kinds of values you can write to a Parcel. Warning: Don't forget the security implications of receiving data from other processes. In this case, the rect will read four numbers from the parcel, but it is up to you to ensure that these are within the acceptable range of valu es for whatever the caller is trying to do. See Security and Permissions for mor e on how to keep your application secure from malware. } Calling an IPC Method Here are the steps a calling class should make to call your remote interface: 1. Declare a variable of the interface type that your .aidl file defined. 2. Imple ment ServiceConnection. 3. Call Context.bindService(), passing in your ServiceCo nnection implementation. 4. In your implementation of ServiceConnection.onServic eConnected(), you will receive an IBinder instance (called service). Call YourIn terfaceName.Stub.asInterface((IBinder)service) to cast the returned parameter to YourInterface type. 5. Call the methods that you defined on your interface. You should always trap DeadObjectException exceptions, which are thrown when the co nnection has broken; this will be the only exception thrown by remote methods. 6 . To disconnect, call Context.unbindService() with the instance of your interfac e. A few comments on calling an IPC service: Objects are reference counted acros s processes. http://developer.android.com/guide/developing/tools/aidl.html Page 5 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 You can send anonymous objects as method arguments. Here is some sample code dem onstrating calling an AIDL-created service, taken from the Remote Activity sampl e in the ApiDemos project. public class RemoteServiceBinding extends Activity { /** The primary interface we will be calling on the service. */ IRemoteService m Service = null; /** Another interface we use on the service. */ ISecondary mSeco ndaryService = null; Button mKillButton; TextView mCallbackText; private boolean mIsBound; /** * Standard initialization of this activity. Set up the UI, then w ait * for the user to poke it before doing anything. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setCo ntentView(R.layout.remote_service_binding); // Watch for button clicks. Button b utton = (Button)findViewById(R.id.bind); button.setOnClickListener(mBindListener ); button = (Button)findViewById(R.id.unbind); button.setOnClickListener(mUnbind Listener); mKillButton = (Button)findViewById(R.id.kill); mKillButton.setOnClick Listener(mKillListener); mKillButton.setEnabled(false); mCallbackText = (TextVie w)findViewById(R.id.callback); mCallbackText.setText("Not attached."); } /** * C lass for interacting with the main interface of the service. */ private ServiceC onnection mConnection = new ServiceConnection() { public void onServiceConnected (ComponentName className, IBinder service) { // This is called when the connecti on with the service has been // established, giving us the service object we can use to // interact with the service. We are communicating with our // service t hrough an IDL interface, so get a client-side // representation of that from the raw service object. mService = IRemoteService.Stub.asInterface(service); mKillB utton.setEnabled(true); mCallbackText.setText("Attached."); // We want to monito r the service for as long as we are // connected to it. try { mService.registerC allback(mCallback); } catch (RemoteException e) { // In this case the service ha s crashed before we could even // do anything with it; we can count on soon bein g // disconnected (and then reconnected if it can be restarted) // so there is n o need to do anything here. } // As part of the sample, tell the user what happe ned. Toast.makeText(RemoteServiceBinding.this, R.string.remote_service_connected , http://developer.android.com/guide/developing/tools/aidl.html Page 6 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 R.string.remote_service_connected, Toast.LENGTH_SHORT).show(); } public void onS erviceDisconnected(ComponentName className) { // This is called when the connect ion with the service has been // unexpectedly disconnected -- that is, its proce ss crashed. mService = null; mKillButton.setEnabled(false); mCallbackText.setTex t("Disconnected."); // As part of the sample, tell the user what happened. Toast .makeText(RemoteServiceBinding.this, R.string.remote_service_disconnected, Toast .LENGTH_SHORT).show(); } }; /** * Class for interacting with the secondary inter face of the service. */ private ServiceConnection mSecondaryConnection = new Ser viceConnection() { public void onServiceConnected(ComponentName className, IBind er service) { // Connecting to a secondary interface is the same as any // other interface. mSecondaryService = ISecondary.Stub.asInterface(service); mKillButto n.setEnabled(true); } public void onServiceDisconnected(ComponentName className) { mSecondaryService = null; mKillButton.setEnabled(false); } }; private OnClick Listener mBindListener = new OnClickListener() { public void onClick(View v) { / / Establish a couple connections with the service, binding // by interface names . This allows other applications to be // installed that replace the remote serv ice by implementing // the same interface. bindService(new Intent(IRemoteService .class.getName()), mConnection, Context.BIND_AUTO_CREATE); bindService(new Inten t(ISecondary.class.getName()), mSecondaryConnection, Context.BIND_AUTO_CREATE); mIsBound = true; mCallbackText.setText("Binding."); } }; private OnClickListener mUnbindListener = new OnClickListener() { public void onClick(View v) { if (mIs Bound) { // If we have received the service, and hence registered with // it, th en now is the time to unregister. if (mService != null) { try { mService.unregis terCallback(mCallback); } catch (RemoteException e) { // There is nothing specia l we need to do if the service // has crashed. } } // Detach our existing connec tion. unbindService(mConnection); unbindService(mSecondaryConnection); mKillButt on.setEnabled(false); mIsBound = false; http://developer.android.com/guide/developing/tools/aidl.html Page 7 of 9

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 } }; private OnClickListener mKillListener = new OnClickListener() { public void onClick(View v) { // To kill the process hosting our service, we need to know i ts // PID. Conveniently our service has a call that will return // to us that in formation. if (mSecondaryService != null) { try { int pid = mSecondaryService.ge tPid(); // Note that, though this API allows us to request to // kill any proces s based on its PID, the kernel will // still impose standard restrictions on whi ch PIDs you // are actually able to kill. Typically this means only // the proce ss running your application and any additional // processes created by that app as shown here; packages // sharing a common UID will also be able to kill each / / other's processes. Process.killProcess(pid); mCallbackText.setText("Killed ser vice process."); } catch (RemoteException ex) { // Recover gracefully from the p rocess hosting the // server dying. // Just for purposes of the sample, put up a notification. Toast.makeText(RemoteServiceBinding.this, R.string.remote_call_fa iled, Toast.LENGTH_SHORT).show(); } } } }; // --------------------------------------------------------------------// Code showing how to deal with callbacks. / / ---------------------------------------------------------------------/** * Thi s implementation is used to receive callbacks from the remote * service. */ priv ate IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { /** * This is called by the remote service regularly to tell us about * new values. N ote that IPC calls are dispatched through a thread * pool running in each proces s, so the code executing here will * NOT be running in our main thread like most other things -- so, * to update the UI, we need to use a Handler to hop over th ere. */ public void valueChanged(int value) { mHandler.sendMessage(mHandler.obta inMessage(BUMP_MSG, value, 0)); } }; private static final int BUMP_MSG = 1; priv ate Handler mHandler = new Handler() { @Override public void handleMessage(Messa ge msg) { switch (msg.what) { case BUMP_MSG: mCallbackText.setText("Received fro m service: " + msg.arg1); break; default: super.handleMessage(msg); } } http://developer.android.com/guide/developing/tools/aidl.html Page 8 of 9 mIsBound = false; mCallbackText.setText("Unbinding."); }

Designing a Remote Interface Using AIDL | Android Developers 29.04.09 0:54 } } Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines }; ! Go to top http://developer.android.com/guide/developing/tools/aidl.html Page 9 of 9

Android Virtual Devices | Android Developers 29.04.09 0:54 Android Virtual Devices Android Virtual Devices (AVDs) are configurations of emulator options that let y ou better model an actual device. Each AVD is made up of: A hardware profile. Yo u can set options to define the hardware features of the virtual device. For exa mple, you can define whether the device has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how much memory it has, and so on. A mapping to a system image. You can define what version of the Android platform will run on the virtual device. You can choose a version of the standard Android platform or the system image packaged with an SDK add-on. Other options. You can specify the emulator skin you want to use with the AVD, which lets you control the scre en dimensions, appearance, and so on. You can also specify the emulated SD card to use with the AVD. A dedicated storage area on your development machine, in wh ich is stored the device's user data (installed applications, settings, and so o n) and emulated SD card. You can create as many AVDs as you need, based on the t ypes of devices you want to model and the Android platforms and external librari es you want to run your application on. In addition to the options in an AVD con figuration, you can also specify emulator command-line options at launch or by u sing the emulator console to change behaviors or characteristics at run time. Fo r a complete reference of emulator options, please see the Emulator documentatio n. To create and manage AVDs, you use the android tool provided in the Android S DK. For more information about how to work with AVDs from inside your developmen t environment, see Developing in Eclipse with ADT or Developing in Other IDEs, a s appropriate for your environment. Creating an AVD To create an AVD, you use the android tool, a command-line utility available in the <sdk>/tools/ directory. Managing AVDs is one of the two main function of the android tool (the other is creating and updating Android projects). Open a term inal window and change to the <sdk>/tools/ directory, if needed The Android SDK does not include any preconfigured AVDs, so you need to create a n AVD before you can run any application in the emulator (even the Hello World a pplication). To create each AVD, you issue the command android create avd, with options that specify a name for the new AVD and the system image you want to run on the emula tor when the AVD is invoked. You can specify other options on the command line a lso, such as to create an emulated SD card for the new AVD, set the emulator ski n to use, or set a custom location for the AVD's files. Here's the command-line usage for creating an AVD: android create avd -n <name> -t <targetID> [-<option> <value>] ... You can use any name you want for the AVD, but since you are likel y to be creating multiple AVDs, you should choose a name that lets you recognize the general characteristics offered by the AVD. http://developer.android.com/guide/developing/tools/avd.html Page 1 of 6

Android Virtual Devices | Android Developers 29.04.09 0:54 As shown in the usage above, you must use the -t (or --target) argument when cre ating a new AVD. The argument sets up a mapping between the AVD and the system i mage that you want to use whenever the AVD is invoked. You can specify any Andro id system image that is available in your local SDK it can be the system image o f a standard Android platform version or that of any SDK add-on. Later, when app lications use the AVD, they'll be running on the system that you specify in the -t argument. To specify the system image to use, you refer to its target ID an i nteger as assigned by the android tool. The target ID is not derived from the sy stem image name, version, or API Level, or other attribute, so you need to have the android tool list the available system images and the target ID of each, as described in the next section. You should do this before you run the android cre ate avd command. Listing targets To generate a list of system image targets, use this command: android list targe ts The android tool scans the <sdk>/platforms and <sdk>/add-ons directories look ing for valid system images and then generates the list of targets. Here's an ex ample of the command output: Available Android targets: id:1 Name: Android 1.1 T ype: platform API level: 2 Skins: HVGA (default), HVGA-L, HVGA-P, QVGA-L, QVGA-P id:2 Name: Android 1.5 Type: platform API level: 3 Skins: HVGA (default), HVGAL, HVGA-P, QVGA-L, QVGA-P id:3 Name: Google APIs Type: add-on Vendor: Google Inc . Description: Android + Google APIs Based on Android 1.5 (API level 3) Librarie s: * com.google.android.maps (maps.jar) API for Google Maps Skins: HVGA (default ), HVGA-L, QVGA-P, HVGA-P, QVGA-L Selecting a target Once you have generated the list of targets available, you can look at the chara cteristics of each system image name, API Level, external libraries, and so on a nd determine which target is appropriate for the new AVD. Keep these points in m ind when you are selecting a system image target for your AVD: The API Level of the target is important, because your application will not be able to run on a s ystem image whose API Level is less than that required by your application, as s pecified in the minSdkVersion attribute of the application's manifest file. For more information about the relationship between system API Level and application minSdkVersion, see Specifying Minimum System API Version. Creating at least one AVD that uses a target whose API Level is greater than that required by your ap plication is strongly encouraged, because it allows you to test the forward-comp atibility of your application. Forwardcompatibility testing ensures that, when u sers who have downloaded your application receive a system update, your applicat ion will continue to function normally. If your application declares a uses-libr ary element in its manifest file, the application can only run on a system image in which that external library is present. If you want your application to run on the AVD you are http://developer.android.com/guide/developing/tools/avd.html Page 2 of 6

Android Virtual Devices | Android Developers 29.04.09 0:54 system image in which that external library is present. If you want your applica tion to run on the AVD you are creating, check the application's uses-library el ement and select a system image target that includes that library. Creating the AVD When you've selected the target you want to use and made a note of its ID, use t he android create avd command to create the AVD, supplying the target ID as the -t argument. Here's an example that creates an AVD with name "my_android1.5" and target ID "2" (the standard Android 1.5 system image in the list above): androi d create avd -n my_android1.5 -t 2 If the target you selected was a standard And roid system image ("Type: platform"), the android tool next asks you whether you want to create a custom hardware profile. Android 1.5 is a basic Android platfo rm. Do you wish to create a custom hardware profile [no] If you want to set cust om hardware emulation options for the AVD, enter "yes" and set values as needed. If you want to use the default hardware emulation options for the AVD, just pre ss the return key (the default is "no"). The android tool creates the AVD with n ame and system image mapping you requested, with the options you specified. If y ou are creating an AVD whose target is an SDK add-on, the android tool does not allow you to set hardware emulation options. It assumes that the provider of the add-on has set emulation options appropriately for the device that the add-on i s modeling, and so prevents you from resetting the options. For a list of option s you can use in the android create avd command, see the table in Command-line o ptions for AVDs, at the bottom of this page. Setting hardware emulation options When are creating a new AVD that uses a standard Android system image ("Type: pl atform"), the android tool lets you set hardware emulation options for virtual d evice. The table below lists the options available and the default values, as we ll as the names of properties that store the emulated hardware options in the AV D's configuration file (the config.ini file in the AVD's local directory). Chara cteristic Device ram size Touch-screen support Trackball support Keyboard suppor t DPad support GSM modem support Camera support Description The amount of physic al RAM on the device, in megabytes. Default value is "96". Whether there is a to uch screen or not on the device. Default value is "yes". Whether there is a trac kball on the device. Default value is "yes". Whether the device has a QWERTY key board. Default value is "yes". Whether the device has DPad keys. Default value i s "yes". Whether there is a GSM modem in the device. Default value is "yes". Whe ther the device has a camera. Default value is Property hw.ramSize hw.touchScree n hw.trackBall hw.keyboard hw.dPad hw.gsmModem hw.camera Page 3 of 6 http://developer.android.com/guide/developing/tools/avd.html

Android Virtual Devices | Android Developers 29.04.09 0:54 "no". Maximum horizontal camera pixels Maximum vertical camera pixels GPS suppor t Battery support Accelerometer Audio recording support Audio playback support S D Card support Cache partition support Cache partition size Default value is "64 0". Default value is "480". Whether there is a GPS in the device. Default value is "yes". Whether the device can run on a battery. Default value is "yes". Wheth er there is an accelerometer in the device. Default value is "yes". Whether the device can record audio. Default value is "yes". Whether the device can play aud io. Default value is "yes". Whether the device supports insertion/removal of vir tual SD Cards. Default value is "yes". Whether we use a /cache partition on the device. Default value is "yes". Default value is "66MB". hw.camera.maxHorizontal Pixels hw.camera.maxVerticalPixels hw.gps hw.battery hw.accelerometer hw.audioIn put hw.audioOutput hw.sdCard disk.cachePartition disk.cachePartition.size Default location of the AVD files When you create an AVD, the android tool creates a dedicated directory for it on your development computer. The directory contains the AVD configuration file, t he user data image and SD card image (if available), and any other files associa ted with the device. Note that the directory does not contain a system image ins tead, the AVD configuration file contains a mapping to the system image, which i t loads when the AVD is launched. The android tool also creates a <AVD name>.ini file for the AVD at the root of the .android/avd directory on your computer. Th e file specifies the location of the AVD directory and always remains at the roo t the .android directory. By default, the android tool creates the AVD directory inside ~/.android/avd/ (on Linux/Mac), C:\Documents and Settings\<user>\.androi d\ on Windows XP, and C:\Users\<user>\.android\ on Windows Vista. If you want to use a custom location for the AVD directory, you can do so by using the -p <pat h> option when you create the AVD: android create avd -n my_android1.5 -t 2 -p p ath/to/my/avd If the .android directory is hosted on a network drive, we recomme nd using the -p option to place the AVD directory in another location. The AVD's .ini file remains in the .android directory on the network drive, regardless of the location of the AVD directory. Managing AVDs The sections below provide more information about how to manage AVDs once you've created them. http://developer.android.com/guide/developing/tools/avd.html Page 4 of 6

Android Virtual Devices | Android Developers 29.04.09 0:54 Moving an AVD If you want to move or rename an AVD, you can do so using this command: android move avd -n <name> [-<option> <value>] ... The options for this command are list ed in Command-line options for AVDs at the bottom of this page. Updating an AVD If, for any reason, the platform/add-on root folder has its name changed (maybe because the user has installed an update of the platform/add-on) then the AVD wi ll not be able to load the system image that it is mapped to. In this case, the android list targets command will produce this output: The following Android Vir tual Devices could not be loaded: Name: foo Path: <path>/.android/avd/foo.avd Er ror: Invalid value in image.sysdir. Run 'android update avd -n foo' To fix this error, use the android update avd command to recompute the path to the system im ages. Deleting an AVD You can use the android tool to delete an AVD. Here is the command usage: androi d delete avd -n <name> When you issue the command, the android tool looks for an AVD matching the specified name deletes the AVD's directory and files. Command-line options for AVDs The table below lists the command-line options you can use with the android tool . Action list avds create avd -n <name> or -t <targetID> Option Description List all known AVDs, with name, path, target, and skin. The name for the AVD. Target ID of the system image to use with the new AVD. The path to the SD card image t o use with this AVD or the size of a new SD card image to create for this AVD. F orce creation of the AVD Required Required. To obtain a list of available target s, use android list targets. Examples: -c path/to/sdcard or -c 1000M Comments -c <path> or -c <size>[K|M] -f By default, if the name of the AVD being created matches that of an existing AVD , the android tool will not create the new AVD or overwrite the existing AVD. If you Page 5 of 6 http://developer.android.com/guide/developing/tools/avd.html

Android Virtual Devices | Android Developers 29.04.09 0:54 specify the -f option, however, the android tool will automatically overwrite an y existing AVD that has the same name as the new AVD. The files and data of the existing AVD are deleted. -p <path> Path to the location at which to create the directory for this AVD's files. The skin to use for this AVD, identified by name or dimensions. The android tool scans for a matching skin by name or dimension in the skins/ directory of the target referenced in the -t <targetID> argument. Example: -s HVGA-L Required Required -s <name> or -s <width><height> delete avd move avd -n <name> -n <name> -p <path> -r <new-name> Delete the specified AVD. The name of the AVD to move. The path to the new locat ion for the AVD. Rename the AVD. Recompute the paths to all system images. update avds Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/avd.html Page 6 of 6

Using Dalvik Debug Monitor Service (DDMS) | Android Developers 29.04.09 0:54 Using Dalvik Debug Monitor Service (DDMS) Android ships with a debugging tool called the Dalvik Debug Monitor Service (DDM S), which provides port-forwarding services, screen capture on the device, threa d and heap information on the device, logcat, process, and radio state informati on, incoming call and SMS spoofing, location data spoofing, and more. This page provides a modest discussion of DDMS features; it is not an exhaustive explorati on of all the features and capabilities. DDMS ships in the tools/ directory of t he SDK. Enter this directory from a terminal/console and type ddms (or ./ddms on Mac/Linux) to run it. DDMS will work with both the emulator and a connected dev ice. If both are connected and running simultaneously, DDMS defaults to the emul ator. How DDMS works DDMS acts as a middleman to connect the IDE to the applications running on the d evice. On Android, every application runs in its own process, each of which host s its own virtual machine (VM). And each process listens for a debugger on a dif ferent port. When it starts, DDMS connects to adb and starts a device monitoring service between the two, which will notify DDMS when a device is connected or d isconnected. When a device is connected, a VM monitoring service is created betw een adb and DDMS, which will notify DDMS when a VM on the device is started or t erminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), v ia adb, and opens a connection to the VM's debugger, through the adb daemon (adb d) on the device. DDMS can now talk to the VM using a custom wire protocol. For each VM on the device, DDMS opens a port upon which it will listen for a debugge r. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwa rded between the debugger and the associated VM. Debugging can then process like any remote debugging session. DDMS also opens another local port, the DDMS "bas e port" (8700, by default), upon which it also listens for a debugger. When a de bugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect. For mo re information on port-forwarding with DDMS, read Configuring your IDE to attach to port 8700 for debugging. Tip: You can set a number of DDMS preferences in Fi le > Preferences. Preferences are saved to "$HOME/.ddmsrc". Known debugging issu es with Dalvik Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, when single-stepping out of synchronized code, t he "current line" cursor may jump to the last line in the method for one step. Left Pane The left side of the Debug Monitor shows each emulator/device currently found, w ith a list of all the VMs currently running within each. VMs are identified by t he package name of the application it hosts. http://developer.android.com/guide/developing/tools/ddms.html Page 1 of 5

Using Dalvik Debug Monitor Service (DDMS) | Android Developers 29.04.09 0:54 Use this list to find and attach to the VM running the activity(ies) that you wa nt to debug. Next to each VM in the list is a "debugger pass-through" port (in t he right-most column). If you connect your debugger to one of the the ports list ed, you will be connected to the corresponding VM on the device. However, when u sing DDMS, you need only connect to port 8700, as DDMS forwards all traffic here to the currently selected VM. (Notice, as you select a VM in the list, the list ed port includes 8700.) This way, there's no need to reconfigure the debugger's port each time you switch between VMs. When an application running on the device calls waitForDebugger() (or you select this option in the developer options), a red icon will be shown next to the client name, while it waits for the debugger to attach to the VM. When a debugger is connected, the icon will turn green. If you see a crossed-out bug icon, this means that the DDMS was unable to complete a connection between the debugger and the VM because it was unable to open the VM's local port. If you see this for all VMs on the device, it is likely because you have another instance of DDMS running (this includes the Eclipse plugin). I f you see a question mark in place of an application package, this means that, o nce DDMS received the application pid from adb, it somehow failed to make a succ essful handshake with the VM process. Try restarting DDMS. Right pane On the right side, the Debug Monitor provides tabs that display useful informati on and some pretty cool tools. Info This view shows some general information about the selected VM, including the pr ocess ID, package name, and VM version. Threads The threads view has a list of threads running in the process of the target VM. To reduce the amount of data sent over the wire, the thread updates are only sen t when explicitly enabled by toggling the "threads" button in the toolbar. This toggle is maintained per VM. This tab includes the following information: ID - a VM-assigned unique thread ID. In Dalvik, these are odd numbers starting from 3. Tid - the Linux thread ID. For the main thread in a process, this will match th e process ID. Status - the VM thread status. Daemon threads are shown with an as terisk (*). This will be one of the following: running - executing application c ode sleeping - called Thread.sleep() monitor - waiting to acquire a monitor lock wait - in Object.wait() native - executing native code vmwait - waiting on a VM resource zombie - thread is in the process of dying init - thread is initializi ng (you shouldn't see this) starting - thread is about to start (you shouldn't s ee this either) utime - cumulative time spent executing user code, in "jiffies" (usually 10ms). Only available under Linux. stime - cumulative time spent execut ing system code, in "jiffies" (usually 10ms). Name - the name of the thread "ID" and "Name" are set when the thread is started. The remaining fields are updated periodically (default is every 4 seconds). http://developer.android.com/guide/developing/tools/ddms.html Page 2 of 5

Using Dalvik Debug Monitor Service (DDMS) | Android Developers 29.04.09 0:54 seconds). VM Heap Displays some heap stats, updated during garbage collection. If, when a VM is se lected, the VM Heap view says that heap updates are not enabled, click the "Show heap updates" button, located in the top-left toolbar. Back in the VM Heap view , click Cause GC to perform garbage collection and update the heap stats. Allocation Tracker In this view, you can track the memory allocation of each virtual machine. With a VM selected in the left pane, click Start Tracking, then Get Allocations to vi ew all allocations since tracking started. The table below will be filled with a ll the relevant data. Click it again to refresh the list. Emulator Control With these controls, you can simulate special device states and activities. Feat ures include: Telephony Status - change the state of the phone's Voice and Data plans (home, roaming, searching, etc.), and simulate different kinds of network Speed and Latency (GPRS, EDGE, UTMS, etc.). Telephony Actions - perform simulate d phone calls and SMS messages to the emulator. Location Controls - send mock lo cation data to the emulator so that you can perform location-aware operations li ke GPS mapping. To use the Location Controls, launch your application in the And roid emulator and open DDMS. Click the Emulator Controls tab and scroll down to Location Controls. From here, you can: Manually send individual longitude/latitu de coordinates to the device. Click Manual, select the coordinate format, fill i n the fields and click Send. Use a GPX file describing a route for playback to t he device. Click GPX and load the file. Once loaded, click the play button to pl ayback the route for your location-aware application. When performing playback f rom GPX, you can adjust the speed of playback from the DDMS panel and control pl ayback with the pause and skip buttons. DDMS will parse both the waypoints (<wpt >, in the first table), and the tracks (<trk>, in the second table, with support for multiple segments, <trkseg>, although they are simply concatenated). Only t he tracks can be played. Clicking a waypoint in the first list simply sends its coordinate to the device, while selecting a track lets you play it. Use a KML fi le describing individual placemarks for sequenced playback to the device. Click KML and load the file. Once loaded, click the play button to send the coordinate s to your location-aware application. When using a KML file, it is parsed for a <coordinates> element. The value of which should be a single set of longitude, l atitude and altitude figures. For example: <coordinates>-122.084143,37.421972,4< /coordinates> In your file, you may include multiple <Placemark> elements, each containing a <coordinates> element. When you do so, the collection of placemarks will be added as tracks. DDMS will send one placemark per second to the device. One way to generate a suitable KML file is to find a location in Google Earth. Right-click the location entry that appears on the left and select "Save place a s..." with the save format set to Kml. Note: DDMS does not support routes create d with the <MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString ></MultiGeometry> methods. There is also currently no support for the <TimeStamp > node inside the <Placemark>. Future releases may support timed placement and r outes within a single coordinate element. http://developer.android.com/guide/developing/tools/ddms.html Page 3 of 5

Using Dalvik Debug Monitor Service (DDMS) | Android Developers 29.04.09 0:54 For additional methods of setting up mocks of location-based data, see the Locat ion topic. File Explorer With the File Explorer, you can view the device file system and perform basic ma nagement, like pushing and pulling files. This circumvents using the adb push an d pull commands, with a GUI experience. With DDMS open, select Device > File Exp lorer... to open the File Explorer window. You can drag-and-drop into the device directories, but cannot drag out of them. To copy files from the device, select the file and click the Pull File from Device button in the toolbar. To delete f iles, use the Delete button in the toolbar. If you're interested in using an SD card image on the emulator, you're still required to use the mksdcard command to create an image, and then mount it during emulator bootup. For example, from th e /tools directory, execute: $ mksdcard 1024M ./img $ emulator -sdcard ./img Now , when the emulator is running, the DDMS File Explorer will be able to read and write to the sdcard directory. However, your files may not appear automatically. For example, if you add an MP3 file to the sdcard, the media player won't see t hem until you restart the emulator. (When restarting the emulator from command l ine, be sure to mount the sdcard again.) For more information on creating an SD card image, see the Other Tools document. Screen Capture You can capture screen images on the device or emulator by selecting Device > Sc reen capture... in the menu bar, or press CTRL-S. Exploring Processes You can see the output of ps -x for a specific VM by selecting Device > Show pro cess status... in the menu bar. Cause a GC to Occur Cause garbage collection to occury by pressing the trash can button on the toolb ar. Running Dumpsys and Dumpstate on the Device (logcat) To run dumpsys (logcat) from Dalvik, select Device > Run logcat... in the menu b ar. To run dumpstate from Dalvik, select Device > Dump device state... in the me nu bar. Examine Radio State http://developer.android.com/guide/developing/tools/ddms.html Page 4 of 5

Using Dalvik Debug Monitor Service (DDMS) | Android Developers 29.04.09 0:54 By default, radio state is not output during a standard logcat (it is a lot of i nformation). To see radio information, either click Device > Dump radio state... or run logcat as described in Logging Radio Information. Stop a Virtual Machine You can stop a virtual machine by selecting Actions > Halt VM. Pressing this but ton causes the VM to call System.exit(1). Known issues with DDMS DDMS has the following known limitations: If you connect and disconnect a debugg er, ddms drops and reconnects the client so the VM realizes that the debugger ha s gone away. This will be fixed eventually. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/ddms.html Page 5 of 5

Draw 9-patch | Android Developers 29.04.09 0:54 Draw 9-patch The Draw 9-patch tool allows you to easily create a NinePatch graphic using a WY SIWYG editor. For an introduction to Nine-patch graphics and how they work, plea se read the section on Nine-patch in the Ninepatch Images topic. Here's a quick guide to create a Nine-patch graphic using the Draw 9-patch tool. You'll need th e PNG image with which you'd like to create a NinePatch. 1. From a terminal, lau nch the draw9patch application from your SDK /tools directory. 2. Drag your PNG image into the Draw 9-patch window (or File > Open 9-patch... to locate the file ). Your workspace will now open. The left pane is your drawing area, in which yo u can edit the lines for the stretchable patches and content area. The right pan e is the preview area, where you can preview your graphic when stretched. 3. Cli ck within the 1-pixel perimeter to draw the lines that define the stretchable pa tches and (optional) content area. Right-click (or hold Shift and click, on Mac) to erase previously drawn lines. 4. When done, select File > Save 9-patch... Yo ur image will be saved with the .9.png file name. Note: A normal PNG file (*.png ) will be loaded with an empty one-pixel border added around the image, in which you can draw the stretchable patches and content area. A previously saved 9-pat ch file (*.9.png) will be loaded as-is, with no drawing area added, because it a lready exists. Optional controls include: Zoom: Adjust the zoom level of the gra phic in the drawing area. Patch scale: Adjust the scale of the images in the pre view area. Show lock: Visualize the non-drawable area of the graphic on mouse-ov er. Show patches: Preview the stretchable patches in the drawing area (pink is a stretchable patch). Show content: Highlight the content area in the preview ima ges (purple is the area in which content is allowed). http://developer.android.com/guide/developing/tools/draw9patch.html Page 1 of 2

Draw 9-patch | Android Developers 29.04.09 0:54 Show bad patches: Adds a red border around patch areas that may produce artifact s in the graphic when stretched. Visual coherence of your stretched image will b e maintained if you eliminate all bad patches. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/draw9patch.html Page 2 of 2

Android Emulator | Android Developers 29.04.09 0:54 Android Emulator The Android SDK includes a mobile device emulator -- a virtual mobile device tha t runs on your computer. The emulator lets you prototype, develop, and test Andr oid applications without using a physical device. The Android emulator mimics al l of the typical hardware and software features of a typical mobile device, exce pt that it can not receive or place actual phone calls. It provides a variety of navigation and control keys, which you can "press" using your mouse or keyboard to generate events for your application. It also provides a screen in which you r application is displayed, together with any other Android applications running . To let you model and test your application more easily, the emulator supports Android Virtual Device (AVD) configurations. AVDs let you specify the Android pl atform that you want to run on the emulator, as well as the hardware options and emulator skin files tht you want to use. Once your application is running on th e emulator, it can use the services of the Android platform to invoke other appl ications, access the network, play audio and video, store and retrieve data, not ify the user, and render graphical transitions and themes. The emulator also inc ludes a variety of debug capabilities, such as a console from which you can log kernel output, simulate application interrupts (such as arriving SMS messages or phone calls), and simulate latency effects and dropouts on the data channel. In this document: Overview Starting and Stopping the Emulator Android Virtual Devices and the Emul ator Controlling the Emulator Emulator Startup Options Working with Emulator Dis k Images Default Images Runtime Images: User Data and SD Card Temporary Images E mulator Networking Network Address Space Local Networking Limitations Using Netw ork Redirections Configuring the Emulator's DNS Settings Using the Emulator with a Proxy Interconnecting Emulator Instances Sending a Voice Call or SMS to Anoth er Emulator Instance Using the Emulator Console Port Redirections Geo Location P rovider Emulation Sending Events Emulating Device Power Characteristics Network Status Network Delay Emulation Network Speed Emulation Telephony Emulation SMS E mulation VM State Emulator Window Terminating an Emulator Instance Using Emulato r Skins Running Multiple Instances of the Emulator Installing Applications on th e Emulator SD Card Emulation Creating an SD card image using the android tool Cr eating an SD card image using mksdcard Copying Files to a Disk Image Loading the Disk Image at Emulator Startup Troubleshooting Emulator Problems Emulator Limit ations Overview The Android emulator is a QEMU-based application that provides a virtual ARM mob ile device on which you can run your Android applications. It runs a full Androi d system stack, down to the kernel level, that includes a set of preinstalled ap plications (such as the dialer) that you can access from your applications. You can choose what version http://developer.android.com/guide/developing/tools/emulator.html Page 1 of 20

Android Emulator | Android Developers 29.04.09 0:54 preinstalled applications (such as the dialer) that you can access from your app lications. You can choose what version of the Android system you want to run in the emulator by configuring AVDs, and you can also customize the mobile device s kin and key mappings. When launching the emulator and at runtime, you can use a variety of commands and options to control the its behaviors. The Android system image distributed in the SDK contains ARM machine code for the Android Linux ke rnel, the native libraries, the Dalvik VM, and the various Android package files (such as for for the Android framework and preinstalled applications). The emul ator's QEMU layers provide dynamic binary translation of the ARM machine code to the OS and processor architecture of your development machine. Adding custom ca pabilities to the underlying QEMU services, the Android emulator supports many h ardware features likely to be found on mobile devices, including: An ARMv5 CPU a nd the corresponding memory-management unit (MMU) A 16-bit LCD display One or mo re keyboards (a Qwerty-based keyboard and associated Dpad/Phone buttons) A sound chip with output and input capabilities Flash memory partitions (emulated throu gh disk image files on the development machine) A GSM modem, including a simulat ed SIM Card The sections below provide more information about the emulator and h ow to use it for developing Android applications. Starting and Stopping the Emulator During development and testing of your application, you install and run your app lication in the Android emulator. You can launch the emulator as a standalone ap plication, from a command line, or you can use it as part of your Eclipse develo pment environment. In either case, you specify the AVD configuration to load and any startup options you want to use, as described in this document. You can run your application on a single instance of the emulator or, depending on your nee ds, you can start multiple emulator instances and run your application in more t han one emulated device. You can use the emulator's built-in commands to simulat e GSM phone calling or SMS between emulator instances, and you can set up networ k redirections that allow emulators to send data to one another. For more inform ation, see Telephony Emulation, SMS Emulation, and Emulator Networking To start an instance of the emulator from the command line, change to the tools/ folder o f the SDK. Enter emulator command like this: emulator -avd <avd_name> This initi alizes the emulator and loads an AVD configuration (see the next section for mor e information about AVDs). You will see the emulator window appear on your scree n. If you are working in Eclipse, the ADT plugin for Eclipse installs your appli cation and starts the emulator automatically, when you run or debug the applicat ion. You can specify emulator startup options in the Run/Debug dialog, in the Ta rget tab. When the emulator is running, you can issue console commands as descri bed later in this document. If you are not working in Eclipse, see Installing Ap plications on the Emulator for information about how to install your application . To stop an emulator instance, just close the emulator's window. Android Virtual Devices and the Emulator To use the emulator, you first must create one or more AVD configurations. In ea ch configuration, you specify an Android platform to run in the emulator and the set of hardware options and emulator skin you want to use. Then, when you launc h the emulator, you specify the AVD configuration that you want to load. To spec ify the AVD you want to load when starting the emulator, you use the -avd argume nt, as shown in the previous section. Each AVD functions as an independent devic e, with its own private storage for user data, SD card, and so on. When you laun ch the emulator with an AVD configuration, it automatically loads the user data and SD card data from the AVD directory. By default, the emulator stores the use r data, SD card data, and cache in the AVD directory. http://developer.android.com/guide/developing/tools/emulator.html Page 2 of 20

Android Emulator | Android Developers 29.04.09 0:54 AVD directory. By default, the emulator stores the user data, SD card data, and cache in the AVD directory. To create and manage AVDs you use the android tool, a command-line utility included in the SDK. For complete information about how t o set up AVDs, see Android Virtual Devices. Controlling the Emulator You can use emulator startup options and console commands to control the behavio rs and characteristics of the emulated environment itself. When the emulator is running, you can interact with the emulated mobile device just as you would an a ctual mobile device, except that you use your mouse pointer to "touch" the touch screen and your keyboard keys to "press" the simulated device keys. The table be low summarizes the mappings between the emulator keys and and the keys of your k eyboard. Emulated Device Key Home Menu (left softkey) Star (right softkey) Back Call/dial button Hangup/end call button Search Power button Audio volume up butt on Audio volume down button Camera button Switch to previous layout orientation (for example, portrait, landscape) Switch to next layout orientation (for exampl e, portrait, landscape) Toggle cell networking on/off Toggle code profiling Togg le fullscreen mode Toggle trackball mode Enter trackball mode temporarily (while key is pressed) DPad left/up/right/down DPad center click Onion alpha increase/ decrease Keyboard Key HOME F2 or Page-up button Shift-F2 or Page Down ESC F3 F4 F5 F7 KEYPAD_PLUS, Ctrl-5 KEYPAD_MINUS, Ctrl-F6 Ctrl-KEYPAD_5, Ctrl-F3 KEYPAD_7, F11 KEYPAD_9, F12 F8 F9 (only with -trace startup option) Alt-Enter F6 Delete K EYPAD_4/8/6/2 KEYPAD_5 KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/) Note that, to use keypad keys, you must first disable NumLock on your developmen t computer. Emulator Startup Options The emulator supports a variety of options that you can specify when launching t he emulator, to control its appearance or behavior. Here's the command-line usag e for launching the emulator with options: http://developer.android.com/guide/developing/tools/emulator.html Page 3 of 20

Android Emulator | Android Developers 29.04.09 0:54 emulator -avd <avd_name> [-<option> [<value>]] ... [-<qemu args>] The table belo w summarizes the available options. Category Help Option -help -help-all -help-< option> -help-debug-tags -help-disk-images -help-environment -help-keys -help-ke yset-file -help-virtualdevice AVD -avd <avd_name> or @<avd_name> -cache <filepat h> Description Print a list of all emulator options. Print help for all startup options. Print help for a specific startup option. Print a list of all tags for debug <tags>. Print help for using emulator disk images. Print help for emulator environment variables. Print the current mapping of keys. Print help for defini ng a custom key mappings file. Print help for Android Virtual Device usage. Requ ired. Specifies the AVD to load for this emulator instance. Use <filepath> as th e working cache partition image. You must create an AVD configuration before lau nching the emulator. For information, see Android Virtual Devices. Optionally, y ou can specify a path relative to the current working directory. If no cache fil e is specified, the emulator's default behavior is to use a temporary file inste ad. For more information on disk images, use -help-diskimages. Optionally, you c an specify a path relative to the current working directory. If -data is not use d, the emulator looks for a file named "userdata-qemu.img" in the storage area o f the AVD being used (see -avd). Optionally, you can specify a path relative to the current working directory. See also -wipe-data. For more information on disk images, use -help-diskimages. Comments Disk Images -data <filepath> Use <filepath> as the working user-data disk image. When resetting the user-data image (through -wipedata), copy the contents of this file to the new user-data disk image. By default, the emulator copies the <system>/userdata.img. Start the emulator without a cache partition. Use <filepath> as the ramdisk image. initdata <filepath> -nocache -ramdisk <filepath> See also -cache <file>. Default value is <system>/ramdisk.img. Optionally, you c an specify a path relative to the current working directory. For more informatio n on disk images, use -help-disk-images. Default value is <system>/sdcard.img. O ptionally, you can specify a path relative to the current working directory. For more information on disk images, use -help-disk-images. See also -initdata. Page 4 of 20 -sdcard <filepath> Use <file> as the SD card image. -wipe-data Reset the current user-data http://developer.android.com/guide/developing/tools/emulator.html

Android Emulator | Android Developers 29.04.09 0:54 disk image (that is, the file specified by -datadir and -data, or the default fi le). The emulator deletes all data from the user data image file, then copies th e contents of the file at -inidata data to the image file before starting. Debug -debug <tags> Enable/disable debug messages for the specified debug tags. Enabl e/disable debug messages for the specified debug tag. Disable debug messages for the specified debug tag. Enable logcat output with given tags. Create a root sh ell console on the current terminal. Enable the root shell (as in shell and spec ify the QEMU character device to use for communication with the shell. For more information on disk images, use -help-diskimages. <tags> is a space/comma/column-separated list of debug component names. Use -hel p-debug-tags to print a list of debug component names that you can use. Use -hel p-debug-tags to print a list of debug component names that you can use in <tag>. -debug-<tag> -debug-no-<tag> -logcat <logtags> If the environment variable ANDROID_LOG_TAGS is defined and not empty, its value will be used to enable logcat output by default. You can use this command even if the adb daemon in the emulated system is broken. Pressing Ctrl-c from the she ll stops the emulator instead of the shell. <device> must be a QEMU device type. See the documentation for 'serial -dev' at http://www.bellard.org/qemu/qemu-doc .html#SEC10 for a list of device types. Here are some examples: -shell-serial st dio is identical to -shell -shell-serial tcp::4444,server,nowait lets you commun icate with the shell over TCP port 4444 -shell-serial fdpair:3:6 lets a parent p rocess communicate with the shell using fds 3 (in) and 6 (out) -shell-serial fdp air:0:1 uses the normal stdin and stdout fds, except that QEMU won't tty-cook th e data. -shell -shellserial <device> -show-kernel <name> -trace <name> Display kernel messages. Enable code profiling (press F9 to start), written to a specified file. Enable verbose output. Equivalent to -debug-init. You can defin e the default verbose output options used by emulator instances in the Android e nvironment variable ANDROID_VERBOSE. Define the options you want to use in a com ma-delimited list, specifying only the stem of each option: -debug-<tags>. Here' s an example showing ANDROID_VERBOSE defined with the -debug-init and -debug-mod em options: ANDROID_VERBOSE=init,modem For more information about debug tags, us e <-helpdebug-tags>. -verbose Media -audio <backend> -audio-in <backend> Use the specified audio backend. Use the specified audiohttp://developer.android.com/guide/developing/tools/emulator.html

Page 5 of 20

Android Emulator | Android Developers 29.04.09 0:54 input backend. -audio-out <backend> -noaudio -radio <device> Use the specified a udiooutput backend. Disable audio support in the current emulator instance. Redi rect radio modem interface to a host character device. Enable audio support in t he current emulator instance. Use the specified DNS server(s). Make all TCP conn ections through a specified HTTP/HTTPS proxy Enabled by default. The value of <s ervers> must be a comma-separated list of up to 4 DNS server names or IP address es. The value of <proxy> can be one of the following: http://<server>:<port> htt p://<username>:<password>@<server>:<port> The http:// prefix can be omitted. If the -http-proxy <proxy> command is not supplied, the emulator looks up the http_ proxy environment variable and automatically uses any value matching the <proxy> format described above. Default value is none. See the table in Network Delay E mulation for supported <delay> values. -useaudio Network -dns-server <servers> -http-proxy <proxy> -netdelay <delay> -netfast -netspeed <speed> -port <port> Set network latency emulation to <delay>. Shortcut for -netspeed full -netdelay none Set network speed emulation to <speed>. Set the console port number for thi s emulator instance to <port>. Report the assigned console port for this emulato r instance to a remote third party before starting the emulation. Default value is full. See the table in Network Speed Emulation for supported <s peed> values. The console port number must be an even integer between 5554 and 5 584, inclusive. <port>+1 must also be free and will be reserved for ADB. <socket > must use one of these formats: tcp:<port>[,server][,max=<seconds>] unix:<port> [,server][,max=<seconds>] Use -help-report-console to view more information abou t this topic. -report-console <socket> System -cpu-delay <delay> Slow down emulated CPU speed by <delay> Supported values for <delay> are integers between 0 and 1000. Note that the <del ay> does not correlate to clock speed or other absolute metrics it simply repres ents an abstract, relative delay factor applied non-deterministically in the emu lator. Effective performance does not always scale in direct relationship with < delay> values. Use this command to emulate an NMEA-compatible GPS unit connected to an external character device or socket. The format of <device> must be QEMUspecific serial device specification. See the documentation for 'serial -dev' at http://www.bellard.org/qemu/qemu-doc.html#SEC10. -gps <device> Redirect NMEA GPS to character device. -nojni -qemu -qemu -h -radio <device> Disable JNI checks in the Dalvik runtime. Pass arguments to qemu. Display qemu h elp. Redirect radio mode to the specified character device. The format of <devic e> must be QEMU-specific serial device specification. See the documentation for 'serial -dev' at http://www.bellard.org/qemu/qemu-doc.html#SEC10.

http://developer.android.com/guide/developing/tools/emulator.html Page 6 of 20

Android Emulator | Android Developers 29.04.09 0:54 -timezone <timezone> Set the timezone for the emulated device to <timezone>, instead of the host's ti mezone. Display the emulator's version number. Scale the resolution of the emula tor to match the screen size of a physical device. Disable the boot animation du ring emulator startup. Disable the emulator's graphical window display. Scale th e emulator window. <timezone> must be specified in zoneinfo format. For example: "America/Los_Angel es" "Europe/Paris" -version UI -dpi-device <dpi> The default value is 165. See also -scale. -no-boot-anim -no-window -scale <scale> Disabling the boot animation can speed the startup time for the emulator. <scale> is a number between 0.1 and 3 that represents the desired scaling factor . You can also specify scale as a DPI value if you add the suffix "dpi" to the s cale value. A value of "auto" tells the emulator to select the best window size. -raw-keys -noskin -keyset <file> Disable Unicode keyboard reverse-mapping. Don't use any emulator skin. Use the s pecified keyset file instead of the default. Use overlay image over screen. Spec ify onion skin translucency value (as percent). Specify onion skin rotation. Sta rt the emulator with the specified skin. The keyset file defines the list of key bindings between the emulator and the host keyboard. For more information, use -help-keyset to print information about this topic. No support for JPEG. Only PN G is supported. Default is 50. -onion <image> -onion-alpha <percent> -onion-rotation <position> -skin <skinID> <position> must be one of the values 0, 1, 2, 3. The standard Android platforms includes a choice of four skins: HVGA-L (480x320, landscape) HVGA-P (320x480, po rtrait) (default) QVGA-L (320x240, landscape) QVGA-P (240x320, portrait) -skindir <dir> Search for emulator skins in <dir>. Working with Emulator Disk Images The emulator uses mountable disk images stored on your development machine to si mulate flash (or similar) partitions on an actual device. For example, it uses d isk image containing an emulator-specific kernel, the Android system, a ramdisk image, and writeable images for user data and simulated SD card. To run properly , the emulator requires access to a specific set of disk image files. By default , the Emulator always looks for the disk images in the private storage area of t he AVD in use. If no images exist there when the Emulator is launched, it create s the images in the AVD directory based on default versions stored in the SDK. N ote: The default storage location for AVDs is in ~/.android/avd on OS X and Linu x, C:\Documents and Settings\<user>\.android\ on Windows XP, and C:\Users\<user> \.android\ on Windows Vista. To let you use alternate or custom versions of the image files, the emulator provides startup options that override the default loc

ations and filenames of the image files. When you use the options, the emulator searches for the image file http://developer.android.com/guide/developing/tools/emulator.html Page 7 of 20

Android Emulator | Android Developers 29.04.09 0:54 under the image name or location that you specify; if it can not locate the imag e, it reverts to using the default names and location. The emulator uses three t ypes of image files: default image files, runtime image files, and temporary ima ge files. The sections below describe how to override the location/name of each type of file. Default Images When the emulator launches but does not find an existing user data image in the active AVD's storage area, it creates a new one from a default version included in the SDK. The default user data image is read-only. The image files are read-o nly. The emulator provides the -system <dir> startup option to let you override the location under which the emulator looks for the default user data image. The emulator also provides a startup option that lets you override the name of the default user data image, as described in the table below. When you use the optio n, the emulator looks in the default directory, or in a custom location (if you specified -system <dir>). Name userdata.img Description The initial user-data di sk image Comments Override using -initdata <file>. Also see data <file>, below. Runtime Images: User Data and SD Card At runtime, the emulator reads and writes data on two disk images: a user-data i mage and (optionally) an SD card image. This emulates the user-data partition an d removable storage media on actual device. The emulator provides a default user -data disk image. At startup, the emulator creates the default image as a copy o f the system user-data image (user-data.img), described above. The emulator stor es the new image with the files of the active AVD. The emulator provides startup options to let you override the actual names and storage locations of the runti me images to load, as described in the table below. When you use one of these op tions, the emulator looks for the specified file(s) in the current working direc tory, in the AVD directory, or in a custom location (if you specified a path wit h the filename). Name userdataqemu.img Description An image to which the emulato r writes runtime user-data for a unique user. Comments Override using -data <fil epath>, where <filepath> is the path the image, relative to the current working directory. If you supply a filename only, the emulator looks for the file in the current working directory. If the file at <filepath> does not exist, the emulat or creates an image from the default userdata.img, stores it under the name you specified, and persists user data to it at shutdown. Override using -sdcard <fil epath>, where <filepath> is the path the image, relative to the current working directory. If you supply a filename only, the emulator looks for the file in the current working directory. sdcard.img An image representing an SD card inserted into the emulated device. User-Data Image Each emulator instance uses a writeable user-data image to store user- and sessi on-specific data. For example, it uses the image to store a unique user's instal led application data, settings, databases, and files. At startup, the emulator a ttempts to load a user-data image stored during a previous session. It looks for the file in the current working directory, in the AVD directory as described ab ove, and at the custom location/name that you specified at startup. If it finds a user-data image, it mounts the image and makes it available to the system for reading/writing of user data. If it does not find one, it creates an image by co pying the system user-data image (userdata.img), described above. At device powe r-off, the system persists the user data to the image, so that it will be availa ble in the next session. Note that the emulator stores the new disk image at the

location/name that you specify in -data startup option. http://developer.android.com/guide/developing/tools/emulator.html Page 8 of 20

Android Emulator | Android Developers 29.04.09 0:54 option. Note: Because of the AVD configurations used in the emulator, each emula tor instance now gets its own dedicated storage. There is no need to use the -d option to specify an instance-specific storage area. SD Card Optionally, you can create a writeable disk image that the emulator can use to s imulate removeable storage in an actual device. For information about how to cre ate an emulated SD card and load it in the emulator, see SD Card Emulation You c an also use the android tool to automatically create an SD Card image for you, w hen creating an AVD. For more information, see Command-line options for AVDs. Temporary Images The emulator creates two writeable images at startup that it deletes at device p ower-off. The images are: A writable copy of the Android system image The /cache partition image The emulator does not permit renaming the temporary system imag e or persisting it at device power-off. The /cache partition image is initially empty, and is used by the browser to cache downloaded web pages and images. The emulator provides an -cache <file>, which specifies the name of the file at whic h to persist the /cache image at device power-off. If <file> does not exist, the emulator creates it as an empty file. You can also disable the use of the cache partition by specifying the -nocache option at startup. Emulator Networking The emulator provides versatile networking capabilities that you can use to set up complex modeling and testing environments for your application. The sections below introduce the emulator's network architecture and capabilities. Network Address Space Each instance of the emulator runs behind a virtual router/firewall service that isolates it from your development machine's network interfaces and settings and from the internet. An emulated device can not see your development machine or o ther emulator instances on the network. Instead, it sees only that it is connect ed through Ethernet to a router/firewall. The virtual router for each instance m anages the 10.0.2/24 network address space all addresses managed by the router a re in the form of 10.0.2.<xx>, where <xx> is a number. Addresses within this spa ce are pre-allocated by the emulator/router as follows: Network Address 10.0.2.1 10.0.2.2 10.0.2.3 10.0.2.4 / 10.0.2.5 / 10.0.2.6 10.0.2.15 127.0.0.1 Descriptio n Router/gateway address Special alias to your host loopback interface (i.e., 12 7.0.0.1 on your development machine) First DNS server Optional second, third and fourth DNS server (if any) The emulated device's own network/ethernet interface The emulated device's own loopback interface Note that the same address assignments are used by all running emulator instance s. That means that if you have two instances running concurrently on your machin e, each will have its own router and, behind that, each will have an IP address of 10.0.2.15. The instances are isolated by a router and can not see each other on the same network. For information about how to let emulator instances communi cate over TCP/UDP, see Connecting Emulator Instances. Also note that the address 127.0.0.1 on your development machine corresponds to the emulator's own loopbac k interface. If you want to access services running on your development machine' s loopback interface (a.k.a. 127.0.0.1 on your machine), you should use the spec ial address 10.0.2.2 instead. http://developer.android.com/guide/developing/tools/emulator.html Page 9 of 20

Android Emulator | Android Developers 29.04.09 0:54 on your machine), you should use the special address 10.0.2.2 instead. Finally, note that each emulated device's pre-allocated addresses are specific to the And roid emulator and will probably be very different on real devices (which are als o very likely to be NAT-ed, i.e., behind a router/firewall) Local Networking Limitations Each emulator instance runs behind a virtual router, but unlike an actual device connected to a physical router, the emulated device doesn't have access to a ph ysical network. Instead it runs as part of a normal application on your developm ent machine. This means that it is subject to the same networking limitations as other applications on your machine: Communication with the emulated device may be blocked by a firewall program running on your machine. Communication with the emulated device may be blocked by another (physical) firewall/router to which y our machine is connected. The emulator's virtual router should be able to handle all outbound TCP and UDP connections/messages on behalf of the emulated device, provided your development machine's network environment allows it to do so. The re are no builtin limitations on port numbers or ranges except the one imposed b y your host operating system and network. Depending on the environment, the emul ator may not be able to support other protocols (such as ICMP, used for "ping") might not be supported. Currently, the emulator does not support IGMP or multica st. Using Network Redirections To communicate with an emulator instance behind its virtual router, you need to set up network redirections on the virtual router. Clients can then connect to a specified guest port on the router, while the router directs traffic to/from th at port to the emulated device's host port. To set up the network redirections, you create a mapping of host and guest ports/addresses on the the emulator insta nce. There are two ways to set up network redirections: using emulator console c ommands and using the ADB tool, as described below. Setting up Redirections through the Emulator Console Each emulator instance provides a control console the you can connect to, to iss ue commands that are specific to that instance. You can use the redir console co mmand to set up redirections as needed for an emulator instance. First, determin e the console port number for the target emulator instance. For example, the con sole port number for the first emulator instance launched is 5554. Next, connect to the console of the target emulator instance, specifying its console port num ber, as follows: telnet localhost 5554 Once connected, use the redir command to work with redirections. To add a redirection, use:. add <protocol>:<host-port>:< guest-port> where <protocol> is either tcp or udp, and <host-port> and <guest-po rt> sets the mapping between your own machine and the emulated system, respectiv ely. For example, the following command sets up a redirection that will handle a ll incoming TCP connections to your host (development) machine on 127.0.0.1:5000 and will pass them through to the emulated system's 10.0.2.15:6000.: redir add tcp:5000:6000 To delete a redirection, you can use the redir del command. To lis t all redirections for a specific instance, you can use redir list. For more inf ormation about these and other console commands, see Using the Emulator Console. Note that port numbers are restricted by your local environment. this typically means that you cannot use host port numbers under 1024 without special administ rator privileges. Also, you won't be able to set up a redirection for a host por t that is already in use by another process on your machine. In that case, redir generates an error message to that effect. Setting Up Redirections through ADB The Android Debug Bridge (ADB) tool provides port forwarding, an alternate way f

or you to set up network redirections. For more information, see Forwarding Port s in the ADB documentation. http://developer.android.com/guide/developing/tools/emulator.html Page 10 of 20

Android Emulator | Android Developers 29.04.09 0:54 redirections. For more information, see Forwarding Ports in the ADB documentatio n. Note that ADB does not currently offer any way to remove a redirection, excep t by killing the ADB server. Configuring the Emulator's DNS Settings At startup, the emulator reads the list of DNS servers that your system is curre ntly using. It then stores the IP addresses of up to four servers on this list a nd sets up aliases to them on the emulated addresses 10.0.2.3, 10.0.2.4, 10.0.2. 5 and 10.0.2.6 as needed. On Linux and OS X, the emulator obtains the DNS server addresses by parsing the file /etc/resolv.conf. On Windows, the emulator obtain s the addresses by calling the GetNetworkParams() API. Note that this usually me ans that the emulator ignores the content of your "hosts" file (/etc/hosts on Li nux/OS X, %WINDOWS%/system32/HOSTS on Windows). When starting the emulator at th e command line, you can also use the -dns-server <serverList> option to manually specify the addresses of DNS servers to use, where <serverList> is a comma-sepa rated list of server names or IP addresses. You might find this option useful if you encounter DNS resolution problems in the emulated network (for example, an "Unknown Host error" message that appears when using the web browser). Using the Emulator with a Proxy If your emulator must access the Internet through a proxy server, you can use th e -http-proxy <proxy> option when starting the emulator, to set up the appropria te redirection. In this case, you specify proxy information in <proxy> in one of these formats: http://<machineName>:<port> or http://<username>:<password>@<mac hineName>:<port> The -http-proxy option forces the emulator to use the specified HTTP/HTTPS proxy for all outgoing TCP connections. Redirection for UDP is not c urrently supported. Alternatively, you can define the environment variable http_ proxy to the value you want to use for <proxy>. In this case, you do not need to specify a value for <proxy> in the -http-proxy command the emulator checks the value of the http_proxy environment variable at startup and uses its value autom atically, if defined. You can use the -verbose-proxy option to diagnose proxy co nnection problems. Interconnecting Emulator Instances To allow one emulator instance to communicate with another, you must set up the necessary network redirections as illustrated below. Assume that your environmen t is A is you development machine B is your first emulator instance, running on A C is your second emulator instance, running on A too and you want to run a ser ver on B, to which C will connect, here is how you could set it up: 1. Set up th e server on B, listening to 10.0.2.15:<serverPort> 2. On B's console, set up a r edirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort> 3. On C, hav e the client connect to 10.0.2.2:<localPort> For example, if you wanted to run a n HTTP server, you can select <serverPort> as 80 and <localPort> as 8080: B list ens on 10.0.2.15:80 On B's console, issue redir add tcp:8080:80 C connects to 10 .0.2.2:8080 http://developer.android.com/guide/developing/tools/emulator.html Page 11 of 20

Android Emulator | Android Developers 29.04.09 0:54 Sending a Voice Call or SMS to Another Emulator Instance The emulator automatically forwards simulated voice calls and SMS messages from one instance to another. To send a voice call or SMS, you use the dialer applica tion and SMS application (if available) installed on one emulator To initiate a simulated voice call to another emulator instance: 1. Launch the dialer applicat ion on the originating emulator instance. 2. As the number to dial, enter the co nsole port number of the instance you'd like to call. You can determine the cons ole port number of the target instance by checking its window title, where the c onsole port number is reported as "Android Emulator (<port>). 3. Press "Dial". A new inbound call appears in the target emulator instance. To send an SMS messag e to another emulator instance, launch the SMS application (if available). Speci fy the console port number of the target emulator instance as as the SMS address , enter the message text, and send the message. The message is delivered to the target emulator instance. You can also connect to an emulator instance's console to simulate an incoming voice call or SMS. For more information, see Telephony Emulation and SMS Emulation. Using the Emulator Console Each running emulator instance includes a console facility that lets you dynamic ally query and control the simulated device environment. For example, you can us e the console to dynamically manage port redirections and network characteristic s and simulate telephony events. To access the console and enter commands, you u se telnet to connect to the console's port number. To connect to the console of any running emulator instance at any time, use this command: telnet localhost <c onsole-port> An emulator instance occupies a pair of adjacent ports: a console p ort and an adb port. The port numbers differ by 1, with the adb port having the higher port number. The console of the first emulator instance running on a give n machine uses console port 5554 and adb port 5555. Subsequent instances use por t numbers increasing by two for example, 5556/5557, 5558/5559, and so on. Up to 16 concurrent emulator instances can run a console facility. To connect to the e mulator console, you must specify a valid console port. If multiple emulator ins tances are running, you need to determine the console port of the emulator insta nce you want to connect to. You can find the instance's console port listed in t he title of the instance window. For example, here's the window title for an ins tance whose console port is 5554: Android Emulator (5554) Alternatively, you can use the adb devices command, which prints a list of running emulator instances and their console port numbers. For more information, see Querying for Emulator/ Device Instances in the adb documentation. Note: The emulator listens for connec tions on ports 5554-5587 and accepts connections only from localhost. Once you a re connected to the console, you can then enter help [command] to see a list of console commands and learn about specific commands. To exit the console session, use quit or exit. The sections below describe the major functional areas of the console. Port Redirection You can use the console to add and remove port redirections while the emulator i s running. After connecting to the console, you can manage port redirections in this way: redir <list|add|del> The redir command supports the subcommands listed in the table below. Subcommand Description Comments http://developer.android.com/guide/developing/tools/emulator.html Page 12 of 20

Android Emulator | Android Developers 29.04.09 0:54 list add <protocol>:<hostport>:<guest-port> List the current port redirections. Add a new port redirection. <protocol> must be either "tcp" or "udp" <host-port> is the port number to open on the host <gue st-port> is the port number to route data to on the emulator/device del <protocol>:<hostport> Delete a port redirection. See above for meanings of <protocol> and <host-port>. Geo Location Provider Emulation The console provides commands to let you set the geo position used by an emulato r emulated device. You can use the geo command to send a simple GPS fix to the e mulator, without needing to use NMEA 1083 formatting. The usage for the command is: geo <fix|nmea> The geo command supports the subcommands listed in the table below. Subcommand fix <longitude> <latitude> [<altitude>] nmea <sentence> Descri ption Send a simple GPS fix to the emulator instance. Send an NMEA 0183 sentence to the emulated device, as if it were sent from an emulated GPS modem. Comments Specify longitude and latitude in decimal degrees. Specify altitude in meters. <sentence> must begin with '$GP'. Only '$GPGGA' and '$GPRCM' sentences are curre ntly supported. You can issue the geo command to fix the GPS location as soon as an emulator ins tance is running. The emulator creates a mock location provider that sends it to GPS-aware applications as soon as they start and register location listeners. A ny application can query the location manager to obtain the current GPS fix for the emulated device by calling: LocationManager.getLastKnownLocation("gps") For more information about the Location Manager, see LocationManager and its methods . Hardware Events Emulation You can use the event command to send various events to the emulator.The usage f or the command is: event <send|types|codes|text> The event command supports the subcommands listed in the table below. Subcommand send <type>:<code>:<value> [.. .] types Description Send one or more events to the Android kernel. List all <ty pe> string aliases supported by the event subcommands. List all <codes> string a liases supported by the event subcommands for the specified <type>. Simulate key presses to send the specified string of The message must be a UTF-8 string. Unic ode posts will be reversePage 13 of 20 Comments You can use text names or integers for <type> and <value>. codes <type> event text <message> http://developer.android.com/guide/developing/tools/emulator.html

Android Emulator | Android Developers 29.04.09 0:54 characters as a message, mapped according to the current device keyboard. Unsupported characters will be discarded silently. Device Power Characteristics You can use the power command to control the simulated power state of the emulat or instance.The usage for the command is: power <display|ac|status|present|healt h|capactiy> The event command supports the subcommands listed in the table below . Subcommand display ac <on|off> status <unknown|charging|discharging|notchargin g|full> present <true|false> health <unknown|good|overheat|dead|overvoltage|fail ure> power health <percent> Description Display battery and charger state. Set A C charging state to on or off. Change battery status as specified. Set battery p resence state. Set battery health state. Set remaining battery capacity state (0 -100). Comments Network Status You can use the console to check the network status and current delay and speed characteristics. To do so, connect to the console and use the netstatus command. Here's an example of the command and its output. network status Network Delay Emulation The emulator lets you simulate various network latency levels, so that you can t est your applicaton in an environment more typical of the actual conditions in w hich it will run. You can set a latency level or range at emulator startup or yo u can use the console to change the latency dynamically, while the application i s running in the emulator. To set latency at emulator startup, use the -netdelay emulator option with a supported <delay> value, as listed in the table below. H ere are some examples: emulator -netdelay gprs emulator -netdelay 40 100 To make dynamic changes to network delay while the emulator is running, connect to the console and use the netdelay command with a supported <delay> value from the tab le below. network delay gprs The format of network is one of the following (numb ers are milliseconds): Value gprs edge Description GPRS EDGE/EGPRS Comments (min 150, max 550) (min 80, max 400) http://developer.android.com/guide/developing/tools/emulator.html Page 14 of 20

Android Emulator | Android Developers 29.04.09 0:54 umts none <num> <min>:<max> UMTS/3G No latency Emulate an exact latency (milliseconds). Emulate an specified latency range (min, max milliseconds). (min 35, max 200) (min 0, max 0) Network Speed Emulation The emulator also lets you simulate various network transfer rates. You can set a transfer rate or range at emulator startup or you can use the console to chang e the rate dynamically, while the application is running in the emulator. To set the network speed at emulator startup, use the -netspeed emulator option with a supported <speed> value, as listed in the table below. Here are some examples: emulator -netspeed gsm emulator -netspeed 14.4 80 To make dynamic changes to net work speed while the emulator is running, connect to the console and use the net speed command with a supported <speed> value from the table below. network speed 14.4 80 The format of network <speed> is one of the following (numbers are kilo bits/sec): Value gsm hscsd gprs edge umts hsdpa full <num> <up>:<down> Descripti on GSM/CSD HSCSD GPRS EDGE/EGPRS UMTS/3G HSDPA no limit Set an exact rate used f or both upload and download. Set exact rates for upload and download separately. Comments (Up: 14.4, down: 14.4) (Up: 14.4, down: 43.2) (Up: 40.0, down: 80.0) ( Up: 118.4, down: 236.8) (Up: 128.0, down: 1920.0) (Up: 348.0, down: 14400.0) (Up : 0.0, down: 0.0) Telephony Emulation The Android emulator includes its own GSM emulated modem that lets you simulate telephony functions in the emulator. For example, you can simulate inbound phone calls and establish/terminate data connections. The Android system handles simu lated calls exactly as it would actual calls. The emulator does not support call audio in this release. You can use the console to access the emulator's telepho ny functions. After connecting to the console, you can use gsm <call|accept|busy |cancel|data|hold|list|voice|status> to invoke telephony functions. The gsm comm and supports the subcommands listed in the table below. Subcommand call Descript ion Simulate an inbound Page 15 of 20 Comments http://developer.android.com/guide/developing/tools/emulator.html

Android Emulator | Android Developers 29.04.09 0:54 <phonenumber> accept <phonenumber> phone call from <phonenumber>. Accept an inbound call from <phonenumber> and cha nge the call's state "active". Close an outbound call to <phonenumber> and chang e the call's state to "busy". Terminate an inbound or outbound phone call to/fro m <phonenumber>. Change the state of the GPRS data connection to <state>. Suppor ted <state> values are: unregistered -- No network available home -- On local ne twork, non-roaming roaming -- On roaming network searching -- Searching networks denied -- Emergency calls only off -- Same as 'unregistered' on -- same as 'hom e' You can change a call's state to "active" only if its current state is "waiti ng" or "held". busy <phonenumber> You can change a call's state to "busy" only if its current state is "waiting". cancel <phonenumber> data <state> hold list Change the state of a call to "held". List all inbound and outbound calls and th eir states. Change the state of the GPRS voice connection to <state>. You can change a call's state to "held" only if its current state is "active" or "waiting". voice <state> Supported <state> values are: unregistered -- No network available home -- On lo cal network, non-roaming roaming -- On roaming network searching -- Searching ne tworks denied -- Emergency calls only off -- Same as 'unregistered' on -- Same a s 'home' status Report the current GSM voice/data state. Values are those described for the voice and data commands. SMS Emulation The Android emulator console lets you generate an SMS message and direct it to a n emulator instance. Once you connect to an emulator instance, you can generate an emulated incoming SMS using this command: sms send <senderPhoneNumber> <textm essage> where <senderPhoneNumber> contains an arbitrary numeric string. The cons ole forwards the SMS message to the Android framework, which passes it through t o an application that handles that message type. VM State You can use the vm command to control the VM on an emulator instance.The usage f or the command is: vm <start|stop|status> http://developer.android.com/guide/developing/tools/emulator.html Page 16 of 20

Android Emulator | Android Developers 29.04.09 0:54 The vm command supports the subcommands listed in the table below. Subcommand st art stop start Description Start the VM on the instance. Stop the VM on the inst ance. Display the current status of the VM (running or stopped). Comments Emulator Window You can use the window command to manage the emulator window. The usage for the command is: window <scale> The vm command supports the subcommands listed in the table below. Subcommand scale <scale> Description Scale the emulator window. Co mments <scale> must be a number between 0.1 and 3 that describes the desired sca ling factor. You can also specify scale as a DPI value if you add the suffix "dp i" to the scale value. A value of "auto" tells the emulator to select the best w indow size. Terminating an Emulator Instance You can terminate an emulator instance through the console, using the kill comma nd. Using Emulator Skins You can run the emulator with any of four default skins, as described in the tab le below. To specify a skin, use -skin <skinID> when starting the emulator. For example: emulator -skin HVGA-L Note that you must enter the <skinID> in uppercas e letters (if your development computer is case-sensitive). skinID HVGA-L Descri ption 480x320, landscape Skin http://developer.android.com/guide/developing/tools/emulator.html Page 17 of 20

Android Emulator | Android Developers 29.04.09 0:54 HVGA-P 320x480, portrait (default) QVGA-L 320x240, landscape QVGA-P 240x320, portrait Running Through nces of ge area on when Multiple Emulator Instances the AVDs configurations used by the emulator, you can run multiple insta the emulator concurrently, each with its own AVD configuration and stora for user data, SD card, and so on. You no longer need to use the -d opti launching the emulator, to point to an instance-specific storage area.

Installing Applications on the Emulator If you don't have access to Eclipse or the ADT Plugin, you can install your appl ication on the emulator using the adb utility. Before installing the application , you need to package it in a .apk file using the Android Asset Packaging Tool. Once the application is installed, you can start the emulator from the command l ine, as described in this document, using any startup options necessary. When th e emulator is running, you can also connect to the emulator instance's console t o issue commands as needed. As you update your code, you periodically package an d install it on the emulator. The emulator preserves the application and its sta te data across restarts, in a user-data disk partition. To ensure that the appli cation runs properly as you update it, you may need to delete the emulator's use r-data partition. To do so, start the emulator with the wipe-data option. For mo re information about the user-data partition and other emulator storage, see Wor king with Emulator Disk Images. http://developer.android.com/guide/developing/tools/emulator.html Page 18 of 20

Android Emulator | Android Developers 29.04.09 0:54 SD Card Emulation You can create a disk image and then load it to the emulator at startup, to simu late the presence of a user's SD card in the device. To do this, you can use the android tool to create a new SD card image with a new AVD, or you can use the m ksdcard utility included in the SDK. The sections below describe how to create a n SD card disk image, how to copy files to it, and how to load it in the emulato r at startup. Note that you can only load disk image at emulator startup. Simila rly, you can not remove a simulated SD card from a running emulator. However, yo u can browse, send files to, and copy/remove files from a simulated SD card eith er with adb or the emulator. The emulator supports emulated SDHC cards, so you c an create an SD card image of any size up to 128 gigabytes. Creating an SD card image using the android tool The easiest way to create a new SD card is to use the android tool. When creatin g an AVD, you simply specify the -c option, like this: android create avd -n <av d_name> -t <targetID> -c <size>[K|M] You can also use the -c option to specify a path to an SD card image to use in the new AVD. For more information, see Andro id Virtual Devices. Creating an SD card image using mksdcard You can use the mksdcard tool, included in the SDK, to create a FAT32 disk image that you can load in the emulator at startup. You can access mksdcard in the to ols/ directory of the SDK and create a disk image like this: mksdcard <size> <fi le> For example: mksdcard 1024M sdcard1.iso For more information, see Other Tool s. Copying Files to a Disk Image Once you have created the disk image, you can copy files to it prior to loading it in the emulator. To copy files, you can mount the image as a loop device and then copy the files to it, or you can use a utility such as mtools to copy the f iles directly to the image. The mtools package is available for Linux, Mac, and Windows. Loading the Disk Image at Emulator Startup By default, the emulator loads the SD card image that is stored with the active AVD (see the -avd startup option). Alternatively, you ca start the emulator with the -sdcard flag and specify the name and path of your image (relative to the c urrent working directory): emulator -sdcard <filepath> Troubleshooting Emulator Problems The adb utility sees the emulator as an actual physical device. For this reason, you might have to use the -d flag with some common adb commands, such as instal l. The -d flag lets you specify which of several connected devices to use as the target of a command. If you don't specify -d, the emulator will target the firs t device in its list. For more information about adb, see Android Debug Bridge. http://developer.android.com/guide/developing/tools/emulator.html Page 19 of 20

Android Emulator | Android Developers 29.04.09 0:54 For emulators running on Mac OS X, if you see an error "Warning: No DNS servers found" when starting the emulator, check to see whether you have an /etc/resolv. conf file. If not, please run the following line in a command window: ln -s /pri vate/var/run/resolv.conf /etc/resolv.conf See Frequently Asked Questions for mor e troubleshooting information. Emulator Limitations In this release, the limitations of the emulator include: No support for placing or receiving actual phone calls. You can simulate phone calls (placed and recei ved) through the emulator console, however. No support for USB connections No su pport for camera/video capture (input). No support for device-attached headphone s No support for determining connected state No support for determining battery charge level and AC charging state No support for determining SD card insert/eje ct No support for Bluetooth Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/emulator.html Page 20 of 20

Hierarchy Viewer | Android Developers 29.04.09 0:55 Hierarchy Viewer The Hierarchy Viewer application allows you to debug and optimize your user inte rface. It provides a visual representation of the layout's View hierarchy (the L ayout View) and a magnified inspector of the display (the Pixel Perfect View). T o get the Hierarchy Viewer started: 1. Connect your device or launch an emulator . 2. From a terminal, launch hierarchyviewer from your SDK /tools directory. 3. In the window that opens, you'll see a list of Devices. When a device is selecte d, a list of currently active Windows is displayed on the right. The <Focused Wi ndow> is the window currently in the foreground, and also the default window loa ded if you do not select another. 4. Select the window that you'd like to inspec t and click Load View Hierarchy. The Layout View will be loaded. You can then lo ad the Pixel Perfect View by clicking the second icon at the bottom-left of the window. If you've navigated to a different window on the device, press Refresh W indows to refresh the list of available windows on the right. Layout View The Layout View offers a look at the View layout and properties. It has three vi ews: Tree View: a hierarchy diagram of the Views, on the left. Properties View: a list of the selected View's properties, on the top-right. Wire-frame View: a w ire-frame drawing of the layout, on the bottom-right. http://developer.android.com/guide/developing/tools/hierarchy-viewer.html Page 1 of 3

Hierarchy Viewer | Android Developers 29.04.09 0:55 Select a node in the Tree View to display the properties of that element in the Properties View. When a node is selected, the Wire-frame View also indicates the bounds of the element with a red rectangle. Double click a node in the tree (or select it, and click Display View) to open a new window with a rendering of tha t element. The Layout View includes a couple other helpful features for debuggin g your layout: Invalidate and Request Layout. These buttons execute the respecti ve View calls, invalidate() and requestLayout(), on the View element currently s elected in the tree. Calling these methods on any View can be very useful when s imultaneously running a debugger on your application. The Tree View can be resiz ed by adjusting the zoom slider, below the diagram. The number of View elements in the window is also given here. You should look for ways to minimize the numbe r of Views. The fewer View elements there are in a window, the faster it will pe rform. If you interact with the device and change the focused View, the diagram will not automatically refresh. You must reload the Layout View by clicking Load View Hierarchy. Pixel Perfect View The Pixel Perfect View provides a magnified look at the current device window. I t has three views: Explorer View: shows the View hierarchy as a list, on the lef t. Normal View: a normal view of the device window, in the middle. Loupe View: a magnified, pixel-grid view of the device window, on the right. http://developer.android.com/guide/developing/tools/hierarchy-viewer.html Page 2 of 3

Hierarchy Viewer | Android Developers 29.04.09 0:55 Click on an element in the Explorer View and a "layout box" will be drawn in the Normal View to indicate the layout position of that element. The layout box use s multiple rectangles, to indicate the normal bounds, the padding and the margin (as needed). The purple or green rectangle indicates the normal bounds of the e lement (the height and width). The inner white or black rectangle indicates the content bounds, when padding is present. A black or white rectangle outside the normal purple/green rectangle indicates any present margins. (There are two colo rs for each rectangle, in order to provide the best contrast based on the colors currently in the background.) A very handy feature for designing your UI is the ability to overlay an image in the Normal and Loupe Views. For example, you mig ht have a mock-up image of how you'd like to layout your interface. By selecting Load... from the controls in the Normal View, you can choose the image from you r computer and it will be placed atop the preview. Your chosen image will anchor at the bottom left corner of the screen. You can then adjust the opacity of the overlay and begin fine-tuning your layout to match the mock-up. The Normal View and Loupe View refresh at regular intervals (5 seconds by default), but the Exp lorer View does not. If you navigate away and focus on a different View, then yo u should refresh the Explorer's hierarchy by clicking Load View Hierarchy. This is even true when you're working in a window that holds multiple Views that are not always visible. If you do not, although the previews will refresh, clicking a View in the Explorer will not provide the proper layout box in the Normal View , because the hierarchy believes you are still focused on the prior View. Option al controls include: Overlay: Load an overlay image onto the view and adjust its opacity. Refresh Rate: Adjust how often the Normal and Loupe View refresh their display. Zoom: Adjust the zoom level of the Loupe View. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/developing/tools/hierarchy-viewer.html Page 3 of 3

UI/Application Exerciser Monkey | Android Developers 29.04.09 0:55 UI/Application Exerciser Monkey The Monkey is a program that runs on your emulator or device and generates pseud o-random streams of user events such as clicks, touches, or gestures, as well as a number of system-level events. You can use the Monkey to stresstest applicati ons that you are developing, in a random yet repeatable manner. Overview The Monkey is a command-line tool that that you can run on any emulator instance or on a device. It sends a pseudorandom stream of user events into the system, which acts as a stress test on the application software you are developing. The Monkey includes a number of options, but they break down into four primary categ ories: Basic configuration options, such as setting the number of events to atte mpt. Operational constraints, such as restricting the test to a single package. Event types and frequencies. Debugging options. When the Monkey runs, it generat es events and sends them to the system. It also watches the system under test an d looks for three conditions, which it treats specially: If you have constrained the Monkey to run in one or more specific packages, it watches for attempts to navigate to any other packages, and blocks them. If your application crashes or receives any sort of unhandled exception, the Monkey will stop and report the er ror. If your application generates an application not responding error, the Monk ey will stop and report the error. Depending on the verbosity level you have sel ected, you will also see reports on the progress of the Monkey and the events be ing generated. Basic Use of the Monkey You can launch the Monkey using a command line on your development machine or fr om a script. Because the Monkey runs in the emulator/device environment, you mus t launch it from a shell in that environment. You can do this by prefacing adb s hell to each command, or by entering the shell and entering Monkey commands dire ctly. The basic syntax is: $ adb shell monkey [options] <event-count> With no op tions specified, the Monkey will launch in a quiet (non-verbose) mode, and will send events to any (and all) packages installed on your target. Here is a more t ypical command line, which will launch your application and send 500 pseudo-rand om events to it: http://developer.android.com/guide/developing/tools/monkey.html Page 1 of 3

UI/Application Exerciser Monkey | Android Developers 29.04.09 0:55 $ adb shell monkey -p your.package.name -v 500 Command Options Reference The table below lists all options you can include on the Monkey command line. Ca tegory General Option --help -v Description Prints a simple usage guide. Each -v on the command line will increment the verbosity level. Level 0 (the default) p rovides little information beyond startup notification, test completion, and fin al results. Level 1 provides more details about the test as it runs, such as ind ividual events being sent to your activities. Level 2 provides more detailed set up information such as activities selected or not selected for testing. Seed val ue for pseudo-random number generator. If you re-run the Monkey with the same se ed value, it will generate the same sequence of events. Inserts a fixed delay be tween events. You can use this option to slow down the Monkey. If not specified, there is no delay and the events are generated as rapidly as possible. Adjust p ercentage of touch events. (Touch events are a down-up event in a single place o n the screen.) Adjust percentage of motion events. (Motion events consist of a d own event somewhere on the screen, a series of pseudo-random movements, and an u p event.) Adjust percentage of trackball events. (Trackball events consist of on e or more random movements, sometimes followed by a click.) Adjust percentage of "basic" navigation events. (Navigation events consist of up/down/left/right, as input from a directional input device.) Adjust percentage of "major" navigation events. (These are navigation events that will typically cause actions within y our UI, such as the center button in a 5-way pad, the back key, or the menu key. ) Adjust percentage of "system" key events. (These are keys that are generally r eserved for use by the system, such as Home, Back, Start Call, End Call, or Volu me controls.) Adjust percentage of activity launches. At random intervals, the M onkey will issue a startActivity() call, as a way of maximizing coverage of all activities within your package. Adjust percentage of other types of events. This is a catch-all for all other types of events such as keypresses, other less-use d buttons on the device, and so forth. If you specify one or more packages this way, the Monkey will only allow the system to visit activities within those pack ages. If your application requires access to activities in other packages (e.g. to select a contact) you'll need to specify those packages as well. If you don't specify any Page 2 of 3 Events -s <seed> --throttle <milliseconds> --pct-touch <percent> --pct-motion <percent> --pcttrac kball <percent> --pct-nav <percent> --pct-majornav <percent> --pct-syskeys <perc ent> --pctappswitch <percent> --pct-anyevent <percent> Constraints -p <allowedpa ckage-name> http://developer.android.com/guide/developing/tools/monkey.html

UI/Application Exerciser Monkey | Android Developers 29.04.09 0:55 packages, the Monkey will allow the system to launch activities in all packages. To specify multiple packages, use the -p option multiple times one -p option pe r package. -c <maincategory> If you specify one or more categories this way, the Monkey will only allow the system to visit activities that are listed with one of the specified categories. If you don't specify any categories, the Monkey wil l select activities listed with the category Intent.CATEGORY_LAUNCHER or Intent. CATEGORY_MONKEY. To specify multiple categories, use the -c option multiple time s one -c option per category. When specified, the Monkey will perform the initia l launch into a test activity, but will not generate any further events. For bes t results, combine with -v, one or more package constraints, and a non-zero thro ttle to keep the Monkey running for 30 seconds or more. This provides an environ ment in which you can monitor package transitions invoked by your application. I f set, this option will generate profiling reports immediately before and after the Monkey event sequence. This will generate large (~5Mb) files in data/misc, s o use with care. See Traceview for more information on trace files. Normally, th e Monkey will stop when the application crashes or experiences any type of unhan dled exception. If you specify this option, the Monkey will continue to send eve nts to the system, until the count is completed. Normally, the Monkey will stop when the application experiences any type of timeout error such as a "Applicatio n Not Responding" dialog. If you specify this option, the Monkey will continue t o send events to the system, until the count is completed. Normally, the Monkey will stop when the application experiences any type of permissions error, for ex ample if it attempts to launch an activity that requires certain permissions. If you specify this option, the Monkey will continue to send events to the system, until the count is completed. Normally, when the Monkey stops due to an error, the application that failed will be left running. When this option is set, it wi ll signal the system to stop the process in which the error occurred. Note, unde r a normal (successful) completion, the launched process(es) are not stopped, an d the device is simply left in the last state after the final event. Watches for and reports crashes occurring in the Android system native code. If --kill-proc ess-after-error is set, the system will stop. Stops the Monkey from executing un til a debugger is attached to it. ! Go to top Debugging --dbg-noevents --hprof --ignorecrashes --ignoretimeouts --ignoresecurityexceptions --killprocess-aftererror --monitornative-crashes --wait-dbg Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines http://developer.android.com/guide/developing/tools/monkey.html Page 3 of 3

Traceview: A Graphical Log Viewer | Android Developers 29.04.09 0:55 Traceview: A Graphical Log Viewer Traceview is a graphical viewer for execution logs saved by your application. Th e sections below describe how to use the program. Contents Creating Trace Files Copying Trace Files to a Host Machine Viewing Trace Files i n Traceview Timeline Panel Profile Panel Traceview File Format Data File Format Key File Format Traceview Known Issues Using dmtracedump Creating Trace Files To use Traceview, you need to generate log files containing the trace informatio n you want to analyze. To do that, you include the Debug class in your code and call its methods to start and stop logging of trace information to disk. When yo ur application quits, you can then use Traceview to examine the log files for us eful run-time information such as method calls and run times. To create the trac e files, include the Debug class and call one of the startMethodTracing() method s. In the call, you specify a base name for the trace files that the system gene rates. To stop tracing, call stopMethodTracing(). These methods start and stop m ethod tracing across the entire virtual machine. For example, you could call sta rtMethodTracing() in your activity's onCreate() method, and call stopMethodTraci ng() in that activity's onDestroy() method. // start tracing to "/sdcard/calc.tr ace" Debug.startMethodTracing("calc"); // ... // stop tracing Debug.stopMethodTr acing(); When your application calls startMethodTracing(), the system creates a file called <trace-base-name>.trace. This contains the binary method trace data and a mapping table with thread and method names. The system then begins bufferi ng the generated trace data, until your application calls stopMethodTracing(), a t which time it writes the buffered data to the output file. If the system reach es the maximum buffer size before stopMethodTracing() is called, the system stop s tracing and sends a notification to the console. Interpreted code will run mor e slowly when profiling is enabled. Don't try to generate absolute timings from the profiler results (i.e. "function X takes 2.5 seconds to run"). The times are only useful in relation to other profile output, so you can see if changes have made the code faster or slower. When using the Android emulator, you must creat e an SD card image upon which the trace files will be written. For example, from the /tools directory, you can create an SD card image and mount it when launchi ng the emulator like so: $ mksdcard 1024M ./imgcd $ emulator -sdcard ./img For m ore information, read about the mksdcard tool. The format of the trace files is described later in this document. http://developer.android.com/guide/developing/tools/traceview.html Page 1 of 5

Traceview: A Graphical Log Viewer | Android Developers 29.04.09 0:55 Copying Trace Files to a Host Machine After your application has run and the system has created your trace files <trac e-base-name>.trace on a device or emulator, you must copy those files to your de velopment computer. You can use adb pull to copy the files. Here's an example th at shows how to copy an example file, calc.trace, from the default location on t he emulator to the /tmp directory on the emulator host machine: adb pull /sdcard /calc.trace /tmp Viewing Trace Files in Traceview To run traceview and view the trace files, enter traceview <trace-base-name>. Fo r example, to run Traceview on the example files copied in the previous section, you would use: traceview /tmp/calc Traceview loads the log files and displays t heir data in a window that has two panels: A timeline panel -- describes when ea ch thread and method started and stopped A profile panel -- provides a summary o f what happened inside a method The sections below provide addition information about the traceview output panes. Timeline Panel The image below shows a close up of the timeline panel. Each threads execution is shown in its own row, with time increasing to the right. Each method is shown i n another color (colors are reused in a round-robin fashion starting with the me thods that have the most inclusive time). The thin lines underneath the first ro w show the extent (entry to exit) of all the calls to the selected method. The m ethod in this case is LoadListener.nativeFinished() and it was selected in the p rofile view. Profile Panel The image below shows the profile pane. The profile pane shows a summary of all the time spent in a method. The table shows both the inclusive and exclusive tim es (as well as the percentage of the total time). Exclusive time is the time spe nt in the method. Inclusive time is the time spent in the method plus the time s pent in any called functions. We refer to calling methods as "parents" and calle d methods as "children." When a method is selected (by clicking on it), it expan ds to show the parents and children. Parents are shown with a purple background and children with a yellow background. The last column in the table shows the nu mber of calls to this method plus the number of recursive calls. The last column shows the number of calls out of the total number of calls made to that method. In this view, we can see that there were 14 calls to LoadListener.nativeFinishe d(); looking at the timeline panel shows that one of those calls took an unusual ly long time. http://developer.android.com/guide/developing/tools/traceview.html Page 2 of 5

Traceview: A Graphical Log Viewer | Android Developers 29.04.09 0:55 Traceview File Format Tracing creates two distinct pieces of output: a data file, which holds the trac e data, and a key file, which provides a mapping from binary identifiers to thre ad and method names. The files are concatenated when tracing completes, into a s ingle .trace file. Note: The previous version of Traceview did not concatenate t hese files for you. If you have old key and data files that you'd still like to trace, you can concatenate them yourself with cat mytrace.key mytrace.data > myt race.trace. Data File Format The data file is binary, structured as follows (all values are stored in littleendian order): * * * * * * * * * * * * * * * * File format: header record 0 reco rd 1 ... Header format: u4 magic 0x574f4c53 ('SLOW') u2 version u2 offset to dat a u8 start date/time in usec Record format: u1 thread ID u4 method ID | method a ction u4 time delta since start, in usec The application is expected to parse all of the header fields, then seek to "off set to data" from the start of the file. From there it just reads 9-byte records until EOF is reached. http://developer.android.com/guide/developing/tools/traceview.html Page 3 of 5

Traceview: A Graphical Log Viewer | Android Developers 29.04.09 0:55 u8 start date/time in usec is the output from gettimeofday(). It's mainly there so that you can tell if the output was generated yesterday or three months ago. method action sits in the two least-significant bits of the method word. The cur rently defined meanings are: 0 - method entry 1 - method exit 2 - method "exited " when unrolled by exception handling 3 - (reserved) An unsigned 32-bit integer can hold about 70 minutes of time in microseconds. Key File Format The key file is a plain text file divided into three sections. Each section star ts with a keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start of a new section. An example file might look like this : *version 1 clock=global *threads 1 main 6 JDWP Handler 5 Async GC 4 Reference Handler 3 Finalizer 2 Signal Handler *methods 0x080f23f8 java/io/PrintStream wri te ([BII)V 0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V 0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V 0x080da620 java/lang/RuntimeE xception <init> ()V [...] 0x080f630c android/os/Debug startMethodTracing ()V 0x0 80f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String ;I)V *end version section The first line is the file version number, currently 1 . The second line, clock=global, indicates that we use a common clock across all threads. A future version may use per-thread CPU time counters that are indepen dent for every thread. threads section One line per thread. Each line consists o f two parts: the thread ID, followed by a tab, followed by the thread name. Ther e are few restrictions on what a valid thread name is, so include everything to the end of the line. methods section One line per method entry or exit. A line c onsists of four pieces, separated by tab marks: method-ID [TAB] classname [TAB] method-name [TAB] signature . Only the methods that were actually entered or exi ted are included in the list. Note that all three identifiers are required to un iquely identify a method. Neither the threads nor methods sections are sorted. Traceview Known Issues Threads Traceview logging does not handle threads well, resulting in these two p roblems: 1. If a thread exits during profiling, the thread name is not emitted; 2. The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID. Using dmtracedump The Android SDK includes dmtracedump, a tool that gives you an alternate way of generating graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to create the graphical output, so you need to install Gra phviz before running dmtracedump. The dmtracedump tool generates the call stack data as a tree diagram, with each call represented as a node. It shows call flow (from parent node to child nodes) using arrows. The diagram below shows an exam ple of dmtracedump output. http://developer.android.com/guide/developing/tools/traceview.html Page 4 of 5

Traceview: A Graphical Log Viewer | Android Developers 29.04.09 0:55 For each node, dmtracedump shows <ref> callname (<inc-ms>, <exc-ms>,<numcalls>), where <ref> -- Call reference number, as used in trace logs <inc-ms> -- Inclusi ve elapsed time (milliseconds spent in method, including all child methods) <exc -ms> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods) <numcalls> -- Number of calls The usage for dmtracedump is: dmtra cedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> T he tool then loads trace log data from <trace-base-name>.data and <trace-base-na me>.key. The table below lists the options for dmtracedump. Option -d <tracebase -name> g <outfile> -h -o -d <tracebase-name> t <percent> Description Diff with t his trace name Generate output to <outfile> Turn on HTML output Dump the trace f ile instead of profiling URL base to the location of the sortable javascript fil e Minimum threshold for including child nodes in the graph (child's inclusive ti me as a percentage of parent inclusive time). If this option is not used, the de fault threshold is 20%. ! Go to top Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines http://developer.android.com/guide/developing/tools/traceview.html Page 5 of 5

Signing Your Applications | Android Developers 29.04.09 0:57 Signing Your Applications This document provides information about signing your Android applications prior to publishing them for mobile device users. Overview The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer. The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certi ficate is not used to control which applications the user can install. The certi ficate does not need to be signed by a certificate authority: it is perfectly al lowable, and typical, for Android applications to use self-signed certificates. The important points to understand about signing Android applications are: All a pplications must be signed. The system will not install an application that is n ot signed. You can use self-signed certificates to sign your applications. No ce rtificate authority is needed. When you are ready to release your application fo r end-users, you must sign it with a suitable private key. You can not publish a n application that is signed with the debug key generated by the SDK tools. The system tests a signer certificate's expiration date only at install time. If an application's signer certificate expires after the application is installed, the application will continue to function normally. You can use standard tools Keyt ool and Jarsigner to generate keys and sign your application .apk files. The And roid system will not install or run an application that is not signed appropriat ely. This applies wherever the Android system is run, whether on an actual devic e or on the emulator. For this reason, you must set up signing for your applicat ion before you will be able to run or debug it on an emulator or device. The And roid SDK tools assist you in signing your applications when debugging. Both the ADT Plugin for Eclipse and the Ant build tool offer two signing modes debug mode and release mode. While developing and testing, you can compile in debug mode. In debug mode, the build tools use the Keytool utility, included in the JDK, to create a keystore and key with a known alias and password. At each compilation, the tools then use the debug key to sign the application .apk file. Because the password is known, the tools don't need to prompt you for the keystore/key passw ord each time you compile. When your application is ready for release, you must compile in release mode and then sign the .apk with your private key. There are two ways to do this: Using Keytool and Jarsigner in the command-line. In this ap proach, you first compile your application to an unsigned .apk. You must then si gn the .apk manually with your private key using Jarsigner (or similar tool). If you do not have a suitable private key already, you can run Keytool manually to generate your own keystore/key and then sign your application with Jarsigner. U sing the ADT Export Wizard. If you are developing in Eclipse with the ADT plugin , you can use the Export Wizard to compile the application, generate a private k ey (if necessary), and sign the .apk, all in a single process using the Export W izard. http://developer.android.com/guide/publishing/app-signing.html Page 1 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 Signing Strategies Some aspects of application signing may affect how you approach the development of your application, especially if you are planning to release multiple applicat ions. In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so: Application upgrade As you release upgrades to your application, you will want to sign the u pgrades with the same certificate, if you want users to upgrade seamlessly to th e new version. When the system is installing an update to an application, if any of the certificates in the new version match any of the certificates in the old version, then the system allows the update. If you sign the version without usi ng a matching certificate, you will also need to assign a different package name to the application in this case, the user installs the new version as a complet ely new application. Application modularity The Android system allows applicatio ns that are signed by the same certificate to run in the same process, if the ap plications so requests, so that the system treats them as a single application. In this way you can deploy your application in modules, and users can update eac h of the modules independently if needed. Code/data sharing through permissions The Android system provides signature-based permissions enforcement, so that an application can expose functionality to another application that is signed with a specified certificate. By signing multiple applications with the same certific ate and using signature-based permissions checks, your applications can share co de and data in a secure manner. Another important consideration in determining y our signing strategy is how to set the validity period of the key that you will use to sign your applications. If you plan to support upgrades for a single appl ication, you should ensure that your key has a validity period that exceeds the expected lifespan of that application. A validity period of 25 years or more is recommended. When your key's validity period expires, users will no longer be ab le to seamlessly upgrade to new versions of your application. If you will sign m ultiple distinct applications with the same key, you should ensure that your key 's validity period exceeds the expected lifespan of all versions of all of the a pplications, including dependent applications that may be added to the suite in the future. If you plan to publish your application(s) on Android Market, the ke y you use to sign the application(s) must have a validity period ending after 22 October 2033. The Market server enforces this requirement to ensure that users can seamlessly upgrade Market applications when new versions are available. As y ou design your application, keep these points in mind and make sure to use a sui table certificate to sign your applications. Basic Setup for Signing To support the generation of a keystore and debug key, you should first make sur e that Keytool is available to the SDK build tools. In most cases, you can tell the SDK build tools how to find Keytool by making sure that your JAVA_HOME envir onment variable is set and that it references a suitable JDK. Alternatively, you can add the JDK version of Keytool to your PATH variable. If you are developing on a version of Linux that originally came with GNU Compiler for Java, make sur e that the system is using the JDK version of Keytool, rather than the gcj versi on. If Keytool is already in your PATH, it might be pointing to a symlink at /us r/bin/keytool. In this case, check the symlink target to make sure that it point s to the Keytool in the JDK. If you will release your application to the public, you will also need to have the Jarsigner tool available on your machine. Both J arsigner and Keytool are included in the JDK. http://developer.android.com/guide/publishing/app-signing.html Page 2 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 Signing in Debug Mode The Android build tools provide a debug signing mode that makes it easier for yo u to develop and debug your application, while still meeting the Android system requirement for signing your .apk when it is installed in the emulator or a devi ce. When you use debug mode, the SDK tools invoke Keytool to create a debug keys tore and key. The SDK tools create the debug keystore/key with predetermined nam es/passwords; Keystore name "debug.keystore" Keystore password "android" Key ali as "androiddebugkey" Key password "android" CN "CN=Android Debug,O=Android,C=US" If necessary, you can change the location/name of the debug keystore/key or sup ply a custom debug keystore/key to use. In Eclipse/ADT, you can use Windows > Pr efs > Android > Build. However, any custom debug keystore/key must use the same keystore/key names and passwords as the default debug key (as described above). Note: You cannot release your application to the public when signed with the deb ug certificate. Eclipse Users If you are developing in Eclipse/ADT and have set up Keytool as described above, signing in debug mode is enabled by default. When you run or debug your applica tion, ADT signs the .apk with the debug certificate and installs it on the emula tor. No specific action on your part is needed, provided ADT has access to Keyto ol. Ant Users If you use Ant to build your .apk files, debug signing mode is enabled by using the debug option, assuming that you are using a build.xml file generated by the android tool. When you run ant debug to compile your app, the build script gener ates a keystore/key and signs the .apk for you. No other action on your part is needed. Read Developing In Other IDEs: Building in debug mode for more informati on. Expiry of the Debug Certificate The self-signed certificate used to sign your application in debug mode (the def ault on Eclipse/ADT and Ant builds) will have an expiration date of 365 days fro m its creation date. When the certificate expires, you will get a build error. O n Ant builds, the error looks like this: debug: [echo] Packaging bin/samples-deb ug.apk, and signing it with a debug key... [exec] Debug Certificate expired on 8 /4/08 3:43 PM In Eclipse/ADT, you will see a similar error in the Android consol e. To fix this problem, simply delete the debug.keystore file. The default stora ge location for AVDs is in ~/.android/avd on OS X and Linux, in C:\Documents and Settings\\.android\ on Windows XP, and in C:\Users\\.android\ on Windows Vista. The next time you build, the build tools will regenerate a new keystore and deb ug key. Note that, if your development machine is using a non-Gregorian locale, the build tools may erroneously generate an already-expired debug certificate, s o that you get an error when trying to compile your application. For workaround http://developer.android.com/guide/publishing/app-signing.html Page 3 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 already-expired debug certificate, so that you get an error when trying to compi le your application. For workaround information, see the troubleshooting topic I can't compile my app because the build tools generated an expired debug certifi cate. Signing for Public Release When your application is ready for release to other users, you must: 1. Compile the application in release mode 2. Obtain a suitable private key 3. Sign the app lication with your private key The sections below provide information about how to perform these steps. If you use Eclipse with the ADT plugin, you can instead use the Export Wizard to compile and sign an .apk with your private key. The Exp ort Wizard even allows you to generate a new keystore and private key in the pro cess. Skip to Compiling and signing with Eclipse ADT. Compiling for release To prepare your application for release, you must first compile it in release mo de. In release mode, the Android build tools compile your application as usual, but without signing it with the debug key. Note: You can not release your applic ation unsigned, or signed with the debug key. Eclipse users To export an unsigned .apk from Eclipse, right-click the project in the Package Explorer and select Android Tools > Export Unsigned Application Package. Then si mply specify the file location for the unsigned .apk. (Alternatively, open your AndroidManifest.xml file in Eclipse, open the Overview tab, and click Export an unsigned .apk.) You can also combine the compiling and signing steps with the Ex port Wizard. See Compiling and signing with Eclipse ADT. Ant users If you are using Ant, all you need to do is specify the build target "release" i n the Ant command. For example, if you are running Ant from the directory contai ning your build.xml file, the command would look like this: $ ant release The bu ild script compiles the application .apk without signing it. Obtaining a Suitable Private Key In preparation for signing your application, you must first ensure that you have a suitable private key with which to sign. A suitable private key is one that: Is in your possession Represents the personal, corporate, or organizational enti ty to be identified with the application Has a validity period that exceeds the expected lifespan of the application or application suite. A validity period of more than 25 years is recommended. If you plan to publish your application(s) on Android Market, note that a validity period ending after 22 October 2033 is a r equirement. You can not upload an application if it is signed with a key whose v alidity expires before that date. http://developer.android.com/guide/publishing/app-signing.html Page 4 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 that date. Is not the debug key generated by the Android SDK tools. The key may be self-signed. If you do not have a suitable key, you must generate one using K eytool. Make sure that you have Keytool available, as described in Basic Setup. To generate a self-signed key with Keytool, use the keytool command and pass any of the options listed below (and any others, as needed). Note: Before you run K eytool, make sure to read Securing Your Private Key for a discussion of how to k eep your key secure and why doing so is critically important to you and to users . In particular, when you are generating your key, you should select strong pass words for both the keystore and key. Keytool Option -genkey -v keystore <keystor ename>.keystore -storepass <password> Description Generate a key pair (public an d private keys) Enable verbose output. A name for the keystore containing the pr ivate key. A password for the keystore. As a security precaution, do not include this optio n in your command line unless you are working at a secure computer. If not suppl ied, Keytool prompts you to enter the password. In this way, your password is no t stored in your shell history. An alias for the key. The encryption algorithm t o use when generating the key. Both DSA and RSA are supported. A Distinguished N ame that describes who created the key. The value is used as the issuer and subj ect fields in the self-signed certificate. Note that you do not need to specify this option in the command line. If not supplied, Jarsigner prompts you to enter each of the Distinguished Name fields (CN, OU, and so on). -alias <alias_name> -keyalg <alg> -dname <name> -validity <valdays> The validity period for the key, in days. Note: A value of 10000 or greater is r ecommended. -keypass <password> The password for the key. As a security precaution, do not include this option i n your command line unless you are working at a secure computer. If not supplied , Keytool prompts you to enter the password. In this way, your password is not s tored in your shell history. Here's an example of a Keytool command that generates a private key: $ keytool genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -valid ity 10000 http://developer.android.com/guide/publishing/app-signing.html Page 5 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 Running the example command above, Keytool prompts you to provide passwords for the keystore and key, and to provide the Distinguished Name fields for your key. It then generates the keystore as a file called my-releasekey.keystore. The key store and key are protected by the passwords you entered. The keystore contains a single key, valid for 10000 days. The alias is a name that you will use later, to refer to this keystore when signing your application. For more information a bout Keytool, see the documentation at http://java.sun.com/j2se/1.5.0/docs/toold ocs/#security Signing your application When you are ready to actually sign your .apk for release, you can do so using t he Jarsigner tool. Make sure that you have Jarsigner available on your machine, as described in Basic Setup. Also, make sure that the keystore containing your p rivate key is available. To sign your application, you run Jarsigner, referencin g both the application's .apk and the keystore containing the private key with w hich to sign the .apk. The table below shows the options you could use. Jarsigne r Option keystore <keystorename>.keystore -verbose -storepass <password> Descrip tion The name of the keystore containing your private key. Enable verbose output. The password for the keystore. As a security precaution, do not include this option in your command line unless you are working at a secu re computer. If not supplied, Jarsigner prompts you to enter the password. In th is way, your password is not stored in your shell history. The password for the private key. As a security precaution, do not include this option in your comman d line unless you are working at a secure computer. If not supplied, Jarsigner p rompts you to enter the password. In this way, your password is not stored in yo ur shell history. -keypass <password> Here's how you would use Jarsigner to sign an application package called my_appl ication.apk, using the example keystore created above. $ jarsigner -verbose -key store my-release-key.keystore my_application.apk alias_name Running the example command above, Jarsigner prompts you to provide passwords for the keystore and k ey. It then modifies the .apk in-place, meaning the .apk is now signed. Note tha t you can sign an .apk multiple times with different keys. To verify that your . apk is signed, you can use a command like this: $ jarsigner -verify my_signed.ap k If the .apk is signed properly, Jarsigner prints "jar verified". If you want m ore details, you can try one of these commands: $ jarsigner -verify -verbose my_ application.apk http://developer.android.com/guide/publishing/app-signing.html Page 6 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 or $ jarsigner -verify -verbose -certs my_application.apk The command above, wit h the -certs option added, will show you the "CN=" line that describes who creat ed the key. Note: If you see "CN=Android Debug", this means the .apk was signed with the debug key generated by the Android SDK. If you intend to release your a pplication, you must sign it with your private key instead of the debug key. For more information about Jarsigner, see the documentation at http://java.sun.com/ j2se/1.5.0/docs/tooldocs/#security Compiling and signing with Eclipse ADT When using Eclipse with ADT, you can use the Export Wizard to export a signed .a pk (and even create a new keystore, if necessary). The Export Wizard performs al l the interaction with the Keytool and Jarsigner for you, which allows you to pe rform signing via a graphical interface instead of the command-line. Because the Export Wizard uses both Keytool and Jarsigner, you should ensure that they are accessible on your computer, as described above in the Basic Setup for Signing. To create a signed .apk, right-click the project in the Package Explorer and sel ect Android Tools > Export Signed Application Package. (Alternatively, open your AndroidManifest.xml file in Eclipse, open the Overview tab, and click Use the E xport Wizard.) The window that appears will display any errors found while attem pting to export your application. If no errors are found, continue with the Expo rt Wizard, which will guide you through the process of signing your application, including steps for selecting the private key with which to sign the .apk, or c reating a new keystore and private key. When you complete the Export Wizard, you 'll have a signed .apk that's ready for distribution. Securing Your Private Key Maintaining the security of your private key is of critical importance, both to you and to the user. If you allow someone to use your key, or if you leave your keystore and passwords in an unsecured location such that a third-party could fi nd and use them, your authoring identity and the trust of the user are compromis ed. If a third party should manage to take your key without your knowledge or pe rmission, that person could sign and distribute applications that maliciously re place your authentic applications or corrupt them. Such a person could also sign and distribute applications under your identity that attack other applications or the system itself, or corrupt or steal user data. Your reputation as a develo per entity depends on your securing your private key properly, at all times, unt il the key is expired. Here are some tips for keeping your key secure: Select st rong passwords for the keystore and key. When you generate your key with Keytool , do not supply the -storepass and -keypass options at the command line. If you do so, your passwords will be available in your shell history, which any user on your computer could access. Similarly, when signing your applications with Jars igner, do not supply the -storepass and -keypass options at the command line. Do not give or lend anyone your private key, and do not let unauthorized persons k now your keystore and key passwords. http://developer.android.com/guide/publishing/app-signing.html Page 7 of 8

Signing Your Applications | Android Developers 29.04.09 0:57 In general, if you follow common-sense precautions when generating, using, and s toring your key, it will remain secure. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/publishing/app-signing.html Page 8 of 8

Versioning Your Applications | Android Developers 29.04.09 0:57 Versioning Your Applications Versioning is a critical component of your application upgrade/maintenance strat egy. Users need to have specific information about the application version that is installed on their devices and the upgrade versions available for installatio n. Other applications including other applications that you publish as a suite n eed to query the system for your application's version, to determine compatibili ty and identify dependencies. Services through which you will publish your appli cation(s) may also need to query your application for its version, so that they can display the version to users. A publishing service may also need to check th e application version to determine compatibility and establish upgrade/downgrade relationships. The Android system itself does not ever check the application ve rsion information for an application, such as to enforce restrictions on upgrade s, compatibility, and so on. Instead, only users or applications themselves are responsible for enforcing any version restrictions for applications themselves. The Android system does check any system version compatibility expressed by an a pplication in its manifest, in the minSdkVersion attribute. This allows an appli cation to specify the minimum system API with which is compatible. For more info rmation see Specifying Minimum System API Version. Setting Application Version To define the version information for your application, you set attributes in th e application's manifest file. Two attributes are available, and you should alwa ys define values for both of them: android:versionCode An integer value that rep resents the version of the application code, relative to other versions. The val ue is an integer so that other applications can programatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this beha vior, but increasing the value with successive releases is normative. Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:ve rsionCode value does not necessarily have a strong resemblence to the applicatio n release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to us ers. android:versionName A string value that represents the release version of t he application code, as it should be shown to users. The value is a string so th at you can describe the application version as a <major>.<minor>.<point> string, or as any other type of absolute or relative version identifier. As with androi d:versionCode, the system does not use this value for any internal purpose, othe r than to enable applications to display it to users. Publishing services may al so extract the android:versionName value for display to users. You define both o f these version attributes in the <manifest> element of the manifest file. http://developer.android.com/guide/publishing/versioning.html Page 1 of 2

Versioning Your Applications | Android Developers 29.04.09 0:57 Here's an example manifest that shows the android:versionCode and android:versio nName attributes in the <manifest> element. <?xml version="1.0" encoding="utf-8" ?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package= "com.example.package.name" android:versionCode="2" android:versionName="1.1"> <a pplication android:icon="@drawable/icon" android:label="@string/app_name"> ... < /application> </manifest> In this example, note that android:versionCode value i ndicates that the current .apk contains the second release of the application co de, which corresponds to a minor follow-on release, as shown by the android:code Name string. The Android framework provides an API to let applications query the system for version information about your application. To obtain version inform ation, applications use the getPackageInfo(java.lang.String, int) method of Pack ageManager. Specifying Minimum System API Version If your application requires a specific minimum version of the Android platform, you can specify that version as an API Level identifier in the application's ma nifest file. Doing so ensures that your application can only be installed on dev ices that are running a compatible version of the Android system. To specify the minimum system version in the manifest, use this attribute: android:minSdkVersi on An integer value corresponding to the code version of the Android platform. W hen preparing to install an application, the system checks the value of this att ribute and compares it to the system version. If the android:minSdkVersion value is greater than the system version, the system aborts the installation of the a pplication. If you do not specify this attribute in your manifest, the system as sumes that your application is compatible with all platform versions. To specify a minimum platform version for your application, add a <uses-sdk> element as a child of <manifest>, then define the android:minSdkVersion as an attribute. For more information, also see the Android System Image 1.1 Version Notes. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/publishing/versioning.html Page 2 of 2

Preparing to Publish: A Checklist | Android Developers 29.04.09 0:57 Preparing to Publish: A Checklist Publishing an application means testing it, packaging it appropriately, and maki ng it available to users of Androidpowered mobile devices. If you plan to publis h your application for installation on Android-powered devices, there are severa l things you need to do, to get your application ready. This document highlights the significant checkpoints for preparing your application for a successful rel ease. If you will publish your application on Android Market, please also see Pu blishing on Android Market for specific preparation requirements for your applic ation. For general information about the ways that you can publish an applicatio ns, see the Publishing Your Applications document. Before you consider your appl ication ready for release: 1. Test your application extensively on an actual dev ice 2. Consider adding an End User License Agreement in your application 3. Spec ify an icon and label in the application's manifest 4. Turn off logging and debu gging and clean up data/files Before you do the final compile of your applicatio n: 5. Version your application 6. Obtain a suitable cryptographic key 7. Registe r for a Maps API Key, if your application is using MapView elements Compile your application... After compiling your application: 8. Sign your application 9. Te st your compiled application Before you consider your application ready for release 1. Test your application extensively on an actual device It's important to test your application as extensively as possible, in as many a reas as possible. To help you do that, Android provides a variety of testing cla sses and tools. You can use Instrumentation to run JUnit and other test cases, a nd you can use testing tools such as the UI/Application Exerciser Monkey. To ens ure that your application will run properly for users, you should make every eff ort to obtain one or more physical mobile device(s) of the type on which you exp ect the application to run. You should then test your application on the actual device, under realistic network conditions. Testing your application on a physic al device is very important, because it enables you to verify that your user int erface elements are sized correctly (especially for touch-screen UI) and that yo ur application's performance and battery efficiency are acceptable. If you can n ot obtain a mobile device of the type you are targeting for your application, yo u can use emulator options such as -dpi, -device, -scale, -netspeed, -netdelay, -cpu-delay and others to model the emulator's screen, network performance, and o ther attributes to match the target device to the greatest extent possible. You can then test your application's UI and performance. However, we strongly recomm end that you test http://developer.android.com/guide/publishing/preparing.html Page 1 of 4

Preparing to Publish: A Checklist | Android Developers 29.04.09 0:57 possible. You can then test your application's UI and performance. However, we s trongly recommend that you test your application on an actual target device befo re publishing it. If you are targeting the T-Mobile G1 device for your applicati on, make sure that your UI handles screen orientation changes. 2. Consider adding an End User License Agreement in your application To protect your person, organization, and intellectual property, you may want to provide an End User License Agreement (EULA) with your application. 3. Specify an icon and label in the application's manifest The icon and label that you specify in an application's manifest are important b ecause they are displayed to users as your application's icon and name. They are displayed on the device's Home screen, as well as in Manage Applications, My Do wnloads, and elsewhere. Additionally, publishing services may display the icon a nd label to users. To specify an icon and label, you define the attributes andro id:icon and android:label in the <application> element of the manifest. As regar ds the design of your icon, you should try to make it match as much as possible the style used by the built-in Android applications. 4. Turn off logging and debugging and clean up data/files For release, you should make sure that debug facilities are turned off and that debug and other unnecessary data/files are removed from your application project . Remove the android:debuggable="true" attribute from the <application> element of the manifest. Remove log files, backup files, and other unnecessary files fro m the application project. Check for private or proprietary data and remove it a s necessary. Deactivate any calls to Log methods in the source code. Before you do the final compile of your application 5. Version your application Before you compile your application, you must make sure that you have defined a version number for your application, specifying an appropriate value for both th e android:versionCode and android:versionName attributes of the <manifest> eleme nt in the application's manifest file. Carefully consider your version numbering plans in the context of your overall application upgrade strategy. If you have previously released a version of your application, you must make sure to increme nt the version number of the current application. You must increment both the an droid:versionCode and android:versionName attributes of the <manifest> element i n the application's manifest file, using appropriate values. For detailed inform ation about how to define version information for your application, see Versioni ng Your Applications. 6. Obtain a suitable cryptographic key If you have read and followed all of the preparation steps up to this point, you r application is compiled and ready for signing. Inside the .apk, the applicatio n is properly versioned, and you've cleaned out extra files and private data, as described above. http://developer.android.com/guide/publishing/preparing.html Page 2 of 4

Preparing to Publish: A Checklist | Android Developers 29.04.09 0:57 Before you sign your application, you need to make sure that you have a suitable private key. For complete information about how to obtain (or generate) a priva te key, see Obtaining a Suitable Private Key. Once you have obtained (or generat ed) a suitable private key, you will use it to: Register for a Maps API Key (see below), if your application uses MapView elements. Sign your application for re lease, later in the preparation process 7. Register for a Maps API Key, if your application is using MapView elements If your application uses one or more Mapview elements, you will need to register your application with the Google Maps service and obtain a Maps API Key, before your MapView(s) will be able to retrieve data from Google Maps. To do so, you s upply an MD5 fingerprint of your signer certificate to the Maps service. For complete information about getting a Maps API Key, see Obtaining a Maps API Key. During development, you can get a temporary Maps API Key by registering the debu g key generated by the SDK tools. However, before publishing your application, y ou must register for a new Maps API Key that is based on your private key. If yo ur application uses MapView elements, the important points to understand are: 1. You must obtain the Maps API Key before you compile your application for releas e, because you must add the Key to a special attribute in each MapView element a ndroid:apiKey in your application's layout files. If you are instantiating MapVi ew objects directly from code, you must pass the Maps API Key as a parameter in the constructor. 2. The Maps API Key referenced by your application's MapView el ements must be registered (in Google Maps) to the certificate used to sign the a pplication. This is particularly important when publishing your application your MapView elements must reference a Key that is registered to the release certifi cate that you will use to sign your application. 3. If you previously got a temp orary Maps API Key by registering the debug certificate generated by the SDK too ls, you must remember to obtain a new Maps API Key by registering your release c ertificate. You must then remember to change the MapView elements to reference t he new Key, rather than the Key associated with the debug certificate. If you do not do so, your MapView elements will not have permission to download Maps data . 4. If you change the private key that you will use to sign your application, y ou must remember to obtain a new Maps API Key from the Google Maps service. If y ou do not get a new Maps API Key and apply it to all MapView elements, any MapVi ew elements referencing the old Key will not have permission to download Maps da ta. For more information about signing and your private key, see Signing Your Ap plications. Compile your application When you've prepared your application as described in the previous sections, you can compile your application for release. After compiling your application 8. Sign your application Sign your application using your private key. Signing your application correctly is critically important. Please see Signing Your Applications for complete info rmation. http://developer.android.com/guide/publishing/preparing.html Page 3 of 4

Preparing to Publish: A Checklist | Android Developers 29.04.09 0:57 9. Test your compiled and signed application Before you release your compiled application, you should thoroughly test it on t he target mobile device (and target network, if possible). In particular, you sh ould make sure that any MapView elements in your UI are receiving maps data prop erly. If they are not, go back to Register for a Maps API Key and correct the pr oblem. You should also ensure that the application works correctly with any serv er-side services and data that you are providing or are relying on and that the application handles any authentication requirements correctly. After testing, yo u are now ready to publish your application to mobile device users. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/publishing/preparing.html Page 4 of 4

Publishing Your Applications | Android Developers 29.04.09 0:57 Publishing Your Applications Publishing an application means testing it, packaging it appropriately, and maki ng it available to users of Androidpowered mobile devices for download or sidelo ad. If you've followed the steps outlined in Preparing to Publish Your Applicati ons, the result of the process is a compiled .apk that is signed with your relea se private key. Inside the .apk, the application is properly versioned and any M apView elements reference a Maps API Key that you obtained by registering the MD 5 fingerprint of the same certificate used to sign the .apk. Your application is now ready for publishing. The sections below provide information about publishi ng your Android application to mobile device users. Publishing on Android Market Android Market is a hosted service that makes it easy for users to find and down load Android applications to their Android-powered devices, and makes it easy fo r developers to publish their applications to Android users. To publish your app lication on Android Market, you first need to register with the service using yo ur Google account and agree to the terms of service. Once you are registered, yo u can upload your application to the service whenever you want, as many times as you want, and then publish it when you are ready. Once published, users can see your application, download it, and rate it using the Market application install ed on their Android-powered devices. To register as an Android Market developer and get started with publishing, visit the Android Market: http://market.android .com/publish If you plan to publish your application on Android Market, you must make sure that it meets the requirements listed below, which are enforced by th e Market server when you upload the application. Requirements enforced by the An droid Market server: 1. Your application must be signed with a cryptographic pri vate key whose validity period ends after 22 October 2033. 2. Your application m ust define both an android:versionCode and an android:versionName attribute in t he <manifest> element of its manifest. The server uses the android:versionCode a s the basis for identifying the application internally and handling upgrades, an d it displays the android:versionName to users as the application's version. 3. Your application must define both an android:icon and an android:label attribute in the <application> element of its manifest. Publishing Upgrades on Android Market The beta version of Android Market does not support notifying your users when yo u publish a new version of your application. This capability will be added soon, but currently the user must independently initiate download of an upgraded appl ication. When you publish an upgrade, you can assist users by notifying them tha t the upgrade is available and giving them a way to download the upgraded applic ation from Android Market. Here is a suggested way of tracking installed applica tion versions and notifying users that an upgrade is available: http://developer.android.com/guide/publishing/publishing.html Page 1 of 3

Publishing Your Applications | Android Developers 29.04.09 0:57 1. Have your app occasionally check in with a web-service that you're running. T his web service should return two values: the latest available version number fo r the application (corresponding to android:versionCode) and a URI string that y our application can later send in an Intent, to launch Market and search for the upgraded application for the user. The URI that your web service returns should be properly formatted to search Android Market for your upgraded application. S ee Using Intents to Launch the Market Application for more information. The URI should specify the upgraded application's package name as the query parameter, s ince the package name is guaranteed to be unique on Android Market. The URI form at for the package name search is: http://market.android.com/search?q=pname:<pac kage> or market://search?q=pname:<package> 2. Your application can then compare its own version number against that retrieved. If the retrieved value is greater , your application can show a dialog informing the user that a new version is av ailable. The dialog can offer buttons to begin the download or cancel. 3. If the user clicks the button to begin the download, your application can call startAc tivity() using the ACTION_VIEW Intent, passing the URI received from your web se rvice. The Intent launches the Market application on the device and initiates an immediate search on the Android Market site, based on the query parameters in t he URI. When the result is displayed, the user can view the details of the upgra ded application and begin the download. Note that, because the URI string is rec eived from your web service and not hard-coded into your application, you can ea sily change the Market launch behaviors whenever needed, without having to chang e your application. For more information about URIs you can pass to the Market a pplication at launch, see Using Intents to Launch the Market Application, below. Using Intents to Launch the Market Application on a Device Android-powered devices include a preinstalled Market application that gives use rs access to the Android Market site. From Market, users can browse or search av ailable applications, read ratings and reviews, and download/install application s. You can launch the Market application from another Android application by sen ding an Intent to the system. You might want to do this, for example, to help th e user locate and download an upgrade to an installed application, or to let the user know about related applications that are available for download. To launch Market, you send an ACTION_VIEW Intent, passing a Market-handled URI string as the Intent data. In most cases, your application would call startActivity() to s end the ACTION_VIEW Intent with the Market-handled URI. The URI that you supply with the Intent lets the system route the intent properly and also expresses the type of action that you want Market to perform after launch. Currently, you can have Market initiate a search for applications on Android Market, based on quer y parameters that you provide. For example, you can specify URIs to search for a pplications by: Package name Developer name String match across application name , developer name, and description, or Any combination of the above Note that the URI queries return results from the public metadata supplied by developers in t heir Android Market profiles or application publishing information, but not from the developer's private account or from the certificate used to sign the applic ation. The table below provides a list of URIs and actions currently supported b y the Market application. For this Result Pass this URI with the ACTION_VIEW Int ent Comments http://developer.android.com/guide/publishing/publishing.html Page 2 of 3

Publishing Your Applications | Android Developers 29.04.09 0:57 Search for an application by its fully qualified Java package name and display t he result. Search for applications by developer name and display the results. Se arch for applications by substring and display the results. http://market.android.com/search? q=pname:<package> or market://search?q=pname:< package> http://market.android.com/search? q=pub:"<Developer Name>" or market:// search?q=pub:"<Developer Name>" http://market.android.com/search? q=<substring> or market://search?q=<substring> Searches only the Java package name of applications. Returns only exact matches. Searches only the "Developer Name" fields of Market public profiles. Returns ex act matches only. Searches all public fields (application title, developer name, and application description) for all applications. Returns exact and partial ma tches. Returns a list of applications meeting all the supplied parameters. Search using multiple query parameters and display the results. Example: http://market.android.com/search? q=world pname:com.android.hello pub:A ndroid Note that these URIs work only when passed as intent data you ad the URIs in a web browser, either on a desktop machine or on Except as noted, this content is licensed under Apache 2.0. For rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/publishing/publishing.html Page 3 of 3 can't currently lo the device. details and rest 0:19 Site Terms

User Interface Guidelines | Android Developers 29.04.09 0:58 User Interface Guidelines The Android UI team has begun developing guidelines for the interaction and desi gn of Android applications. Look here for articles that describe these visual gu idelines as we release them. Widget Design Guidelines Widgets are a new feature introduced in Cupcake. A widget displays an application's most important or time ly information at a glance, on a user's Home screen. These design guidelines des cribe how to design widgets that fit with others on the Home screen. They includ e links to graphics files and templates that will make your designer's life easi er. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/practices/ui_guidelines/index.html Page 1 of 1

Widget Design Guidelines | Android Developers 29.04.09 0:58 Widget Design Guidelines Widgets are a new feature introduced in Android mobile technology platform 1.5 (" Cupcake"). A widget displays an application's most important or timely informati on at a glance, on a user's Home screen. The Android open source code includes s everal examples of widgets, including widgets for Calendar, Music, and other app lications. Users pick the widgets they want to display on their Home screens by touching & holding an empty area of the Home screen, selecting Widgets from the menu, and then selecting the widget they want. This document describes how to design a widget so it fits graphically with other widgets and with the other elements of the Android Home screen. It also describ es some standards for widget artwork and some widget graphics tips and tricks fr om the Android team. For information about developing widgets, see the AppWidget s section of the Developer's Guide and the AddWidgets blog post. Standard widget anatomy Typical Android widgets have three main components: A bounding box, a frame, and the widget's graphical controls and other elements. Well-designed widgets leave some padding between the edges of the bounding box and the frame, and between t he inner edges of the frame and the widget's controls. Widgets designed to fit v isually with other widgets on the Home screen take cues from the other elements on the Home screen for alignment; they also use standard shading effects. All of these details are described in this document. Standard Widget Sizes in Portrait Orientation http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 1 of 7

Widget Design Guidelines | Android Developers 29.04.09 0:58 Standard Widget Sizes in Landscape Orientation Designing a widget 1. Select a bounding box size for your widget. The most effective widgets displa y your application's most useful or timely data in the smallest widget size. Use rs will weigh the usefulness or your widget against the portion of the Home scre en it covers, so the smaller the better. All widgets must fit within the boundin g 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 use r switches screen orientations. Standard widget sizes illustrates the bounding d imensions of the six widget sizes (three in portrait and three in landscape orie ntation). 2. Select a matching frame. Standard widget frames illustrates the sta ndard 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 stan dard shadow effect to your graphics. Again, you don't have to use this effect, b ut Standard widget shadows shows the Photoshop settings used for standard widget s. http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 2 of 7

Widget Design Guidelines | Android Developers standard widgets. 4. If your widget includes buttons, draw them in three states (default, pressed, and selected). You can download a Photoshop file that contain s the three states of the Play button, taken from the Music widget, to analyze t he Photoshop settings used for the three standard button effects. 29.04.09 0:58 5. Finish drawing your artwork and then scale and align it to fit. Widget alignm ent tips and tricks describes some techniques for aligning your widget's graphic s 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. Standard widget sizes There are six standard widget sizes, based on a Home screen grid of 4 x 4 (portr ait) or 4 x 4 (landscape) cells. These dimensions are the bounding boxes for the six standard widget sizes. The contents of typical widgets don't draw to the ed ge of these dimensions, but fit inside a frame withing the bounding box, as desc ribed in Designing a widget. In portrait orientation, each cell is 80 pixels wid e by 100 pixels tall (the diagram shows a cell in portrait orientation). The thr ee supported widget sizes in portrait orientation are: Cells 4x1 3x3 2x2 Pixels 320 x 100 240 x 300 160 x 200 In landscape orientation, each cell is 106 pixels wide by 74 pixels tall. The th ree supported widget sizes in landscape orientation are: Cells 4x1 3x3 2x2 Pixel s 424 x 74 318 x 222 212 x 148 http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 3 of 7

Widget Design Guidelines | Android Developers 29.04.09 0:58 Standard widget frames For each of the six standard widget sizes there is a standard frame. You can cli ck the images of the frames in this section to download a Photoshop file for tha t frame, which you can use for your own widgets. 4x1_Widget_Frame_Portrait.psd 3x3_Widget_Frame_Portrait.psd 2x2_Widget_Frame_Portrait.psd http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 4 of 7

Widget Design Guidelines | Android Developers 29.04.09 0:58 4x1_Widget_Frame_Landscape.psd 3x3_Widget_Frame_Landscape.psd 2x2_Widget_Frame_Landscape.psd Standard widget shadows You can apply a shadow effect to your widget's artwork, so it matches other stan dard Android widgets, using the following settings in the Photoshop Layer Style dialog box. Widget graphics tips and tricks The Android team has developed a few tricks for aligning widget artwork within s tandard widget bounding boxes and frames, so the widget aligns visually with oth er widgets and the other elements of the Home screen, as well as other technique s for creating widgets. Use a screen shot from the Android SDK emulator to align both the shapes and shadows of your widget controls with the Search widget and with other elements on the Home screen. http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 5 of 7

Widget Design Guidelines | Android Developers 29.04.09 0:58 Cut the widget artwork asset" based on the full size of a cell, including any pa dding you want. (That is, for a 4 x 1 widget, cut the asset at 320 by 100 pixels .) To reduce banding when exporting a widget, apply the following Photoshop Add Noi se setting to your graphic. Apply 9-patch techniques to shrink the graphic and set the padding of the conten t area. (See the detailed guide here.) Note: The current Android widget template s were designed using a custom gradient angle, which means the 9patch techniques can't be used to optimize the size of the asset. However, 9-patch techniques we re used to set the content area padding. In some cases, devices have low pixel d epths that can cause visual banding and dithering issues. To solve this, applica tion developers should pass assets through a "proxy" drawable defined as XML:. T his technique references the original artwork, in this case "background.9.png", and instructs the device to dither it as needed. Widget graphics file format Save your widget artwork using the appropriate bounding box size in PNG-24 forma t on a transparent background and in 8-bit color. http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 6 of 7

Widget Design Guidelines | Android Developers 29.04.09 0:58 Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/practices/ui_guidelines/widget_design.html Page 7 of 7

Designing for Performance | Android Developers 29.04.09 0:58 Designing for Performance An Android application should be fast. Well, it's probably more accurate to say that it should be efficient. That is, it should execute as efficiently as possib le in the mobile device environment, with its limited computing power and data s torage, smaller screen, and constrained battery life. As you develop your applic ation, keep in mind that, while the application may perform well enough in your emulator, running on your dual-core development computer, it will not perform th at well when run a mobile device even the most powerful mobile device can't matc h the capabilities of a typical desktop system. For that reason, you should stri ve to write efficient code, to ensure the best possible performance on a variety of mobile devices. Generally speaking, writing fast or efficient code means kee ping memory allocations to a minimum, writing tight code, and avoiding certain l anguage and programming idioms that can subtly cripple performance. In object-or iented terms, most of this work takes place at the method level, on the order of actual lines of code, loops, and so on. This document covers these topics: Intr oduction Avoid Creating Objects Use Native Methods Prefer Virtual Over Interface Prefer Static Over Virtual Avoid Internal Getters/Setters Cache Field Lookups D eclare Constants Final Use Enhanced For Loop Syntax With Caution Avoid Enums Use Package Scope with Inner Classes Avoid Float Some Sample Performance Numbers Cl osing Notes Introduction There are two basic rules for resource-constrained systems: Don't do work that y ou don't need to do. Don't allocate memory if you can avoid it. All the tips bel ow follow from these two basic tenets. Some would argue that much of the advice on this page amounts to "premature optimization." While it's true that microopti mizations sometimes make it harder to develop efficient data structures and algo rithms, on embedded devices like handsets you often simply have no choice. For i nstance, if you bring your assumptions about VM performance on http://developer.android.com/guide/practices/design/performance.html Page 1 of 8

Designing for Performance | Android Developers 29.04.09 0:58 handsets you often simply have no choice. For instance, if you bring your assump tions about VM performance on desktop machines to Android, you're quite likely t o write code that exhausts system memory. This will bring your application to a crawl let alone what it will do to other programs running on the system! That's why these guidelines are important. Android's success depends on the user experi ence that your applications provide, and that user experience depends in part on whether your code is responsive and snappy, or slow and aggravating. Since all our applications will run on the same devices, we're all in this together, in a way. Think of this document as like the rules of the road you had to learn when you got your driver's license: things run smoothly when everybody follows them, but when you don't, you get your car smashed up. Before we get down to brass tac ks, a brief observation: nearly all issues described below are valid whether or not the VM features a JIT compiler. If I have two methods that accomplish the sa me thing, and the interpreted execution of foo() is faster than bar(), then the compiled version of foo() will probably be as fast or faster than compiled bar() . It is unwise to rely on a compiler to "save" you and make your code fast enoug h. Avoid Creating Objects Object creation is never free. A generational GC with per-thread allocation pool s for temporary objects can make allocation cheaper, but allocating memory is al ways more expensive than not allocating memory. If you allocate objects in a use r interface loop, you will force a periodic garbage collection, creating little "hiccups" in the user experience. Thus, you should avoid creating object instanc es you don't need to. Some examples of things that can help: When extracting str ings from a set of input data, try to return a substring of the original data, i nstead of creating a copy. You will create a new String object, but it will shar e the char[] with the data. If you have a method returning a string, and you kno w that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, inst ead of creating a short-lived temporary object. A somewhat more radical idea is to slice up multidimensional arrays into parallel single one-dimension arrays: A n array of ints is a much better than an array of Integers, but this also genera lizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primit ive types. If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects. (The exception to t his, of course, is when you're designing an API for other code to access; in tho se cases, it's usually better to trade correct API design for a small hit in spe ed. But in your own internal code, you should try and be as efficient as possibl e.) Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience. Use Native Methods When processing strings, don't hesitate to use specialty methods like String.ind exOf(), String.lastIndexOf(), and their cousins. These are typically implemented in C/C++ code that easily runs 10-100x faster than doing the same thing in a Ja va loop. The flip side of that advice is that punching through to a native metho d is more expensive than calling an interpreted method. Don't use native methods for trivial computation, if you can avoid it. http://developer.android.com/guide/practices/design/performance.html Page 2 of 8

Designing for Performance | Android Developers 29.04.09 0:58 Prefer Virtual Over Interface Suppose you have a HashMap object. You can declare it as a HashMap or as a gener ic Map: Map myMap1 = new HashMap(); HashMap myMap2 = new HashMap(); Which is bet ter? Conventional wisdom says that you should prefer Map, because it allows you to change the underlying implementation to anything that implements the Map inte rface. Conventional wisdom is correct for conventional programming, but isn't so great for embedded systems. Calling through an interface reference can take 2x longer than a virtual method call through a concrete reference. If you have chos en a HashMap because it fits what you're doing, there is little value in calling it a Map. Given the availability of IDEs that refactor your code for you, there 's not much value in calling it a Map even if you're not sure where the code is headed. (Again, though, public APIs are an exception: a good API usually trumps small performance concerns.) Prefer Static Over Virtual If you don't need to access an object's fields, make your method static. It can be called faster, because it doesn't require a virtual method table indirection. It's also good practice, because you can tell from the method signature that ca lling the method can't alter the object's state. Avoid Internal Getters/Setters In native languages like C++ it's common practice to use getters (e.g. i = getCo unt()) instead of accessing the field directly (i = mCount). This is an excellen t habit for C++, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time. On Andr oid, this is a bad idea. Virtual method calls are expensive, much more so than i nstance field lookups. It's reasonable to follow common object-oriented programm ing practices and have getters and setters in the public interface, but within a class you should always access fields directly. Cache Field Lookups Accessing object fields is much slower than accessing local variables. Instead f writing: for (int i = 0; i < this.mCount; i++) dumpItem(this.mItems[i]); You hould write: int count = this.mCount; Item[] items = this.mItems; for (int i = ; i < count; i++) dumpItems(items[i]); http://developer.android.com/guide/practices/design/performance.html Page 3 of o s 0 8

Designing for Performance | Android Developers 29.04.09 0:58 (We're using an explicit "this" to make it clear that these are member variables .) A similar guideline is never call a method in the second clause of a "for" st atement. For example, the following code will execute the getCount() method once per iteration, which is a huge waste when you could have simply cached the valu e as an int: for (int i = 0; i < this.getCount(); i++) dumpItems(this.getItem(i) ); It's also usually a good idea to create a local variable if you're going to b e accessing an instance field more than once. For example: protected void drawHo rizontalScrollBar(Canvas canvas, int width, int height) { if (isHorizontalScroll BarEnabled()) { int size = mScrollBar.getSize(false); if (size <= 0) { size = mS crollBarSize; } mScrollBar.setBounds(0, height - size, width, height); mScrollBa r.setParams( computeHorizontalScrollRange(), computeHorizontalScrollOffset(), co mputeHorizontalScrollExtent(), false); mScrollBar.draw(canvas); } } That's four separate lookups of the member field mScrollBar. By caching mScrollBar in a loca l stack variable, the four member field lookups become four stack variable refer ences, which are much more efficient. Incidentally, method arguments have the sa me performance characteristics as local variables. Declare Constants Final Consider the following declaration at the top of a class: static int intVal = 42 ; static String strVal = "Hello, world!"; The compiler generates a class initial izer method, called <clinit>, that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the class file string constant table for strVal. When these values are referenced later on , they are accessed with field lookups. We can improve matters with the "final" keyword: static final int intVal = 42; static final String strVal = "Hello, worl d!"; The class no longer requires a <clinit> method, because the constants go in to classfile static field initializers, which are handled directly by the VM. Co de accessing intVal will use the integer value 42 directly, and accesses to strV al will use a relatively inexpensive "string constant" instruction instead of a field lookup. Declaring a method or class "final" does not confer any immediate performance benefits, but it does allow certain optimizations. For example, if t he compiler knows that a "getter" method can't be overridden by a sub-class, it can inline the method call. http://developer.android.com/guide/practices/design/performance.html Page 4 of 8

Designing for Performance | Android Developers 29.04.09 0:58 You can also declare local variables final. However, this has no definitive perf ormance benefits. For local variables, only use "final" if it makes the code cle arer (or you have to, e.g. for use in an anonymous inner class). Use Enhanced For Loop Syntax With Caution The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface. With these objects, an iterat or is allocated to make interface calls to hasNext() and next(). With an ArrayLi st, you're better off walking through it directly, but for other collections the enhanced for loop syntax will be equivalent to explicit iterator usage. Neverth eless, the following code shows an acceptable use of the enhanced for loop: publ ic class Foo { int mSplat; static Foo mArray[] = new Foo[27]; public static void zero() { int sum = 0; for (int i = 0; i < mArray.length; i++) { sum += mArray[i ].mSplat; } } public static void one() { int sum = 0; Foo[] localArray = mArray; int len = localArray.length; for (int i = 0; i < len; i++) { sum += localArray[ i].mSplat; } } public static void two() { int sum = 0; for (Foo a: mArray) { sum += a.mSplat; } } } zero() retrieves the static field twice and gets the array l ength once for every iteration through the loop. one() pulls everything out into local variables, avoiding the lookups. two() uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language. The code generated b y the compiler takes care of copying the array reference and the array length to local variables, making it a good choice for walking through all elements of an array. It does generate an extra local load/store in the main loop (apparently preserving "a"), making it a teensy bit slower and 4 bytes longer than one(). To summarize all that a bit more clearly: enhanced for loop syntax performs well w ith arrays, but be cautious when using it with Iterable objects since there is a dditional object creation. Avoid Enums Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this: http://developer.android.com/guide/practices/design/performance.html Page 5 of 8

Designing for Performance | Android Developers 29.04.09 0:58 public class Foo { public enum Shrubbery { GROUND, CRAWLING, HANGING } } turns i nto a 900 byte .class file (Foo$Shrubbery.class). On first use, the class initia lizer invokes the <init> method on objects representing each of the enumerated v alues. Each object gets its own static field, and the full set is stored in an a rray (a static field called "$VALUES"). That's a lot of code and data, just for three integers. This: Shrubbery shrub = Shrubbery.GROUND; causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a kn own constant and inline it. The flip side, of course, is that with enums you get nicer APIs and some compile-time value checking. So, the usual trade-off applie s: you should by all means use enums for public APIs, but try to avoid them when performance matters. In some circumstances it can be helpful to get enum intege r values through the ordinal() method. For example, replace: for (int n = 0; n < list.size(); n++) { if (list.items[n].e == MyEnum.VAL_X) // do stuff 1 else if (list.items[n].e == MyEnum.VAL_Y) // do stuff 2 } with: int valX = MyEnum.VAL_X. ordinal(); int valY = MyEnum.VAL_Y.ordinal(); int count = list.size(); MyItem it ems = list.items(); for (int { int n = 0; n < count; n++) valItem = items[n].e.o rdinal(); } In some cases, this will be faster, though this is not guaranteed. if (valItem == valX) // do stuff 1 else if (valItem == valY) // do stuff 2 Use Package Scope with Inner Classes Consider the following class definition: public class Foo { private int mValue; public void run() { Inner in = new Inner(); http://developer.android.com/guide/practices/design/performance.html Page 6 of 8

Designing for Performance | Android Developers 29.04.09 0:58 } private void doStuff(int value) { System.out.println("Value is " + value); } p rivate class Inner { void stuff() { Foo.this.doStuff(Foo.this.mValue); } } Inner in = new Inner(); mValue = 27; in.stuff(); } The key things to note here are that we define an inner class (Foo$Inner) that d irectly accesses a private method and a private instance field in the outer clas s. This is legal, and the code prints "Value is 27" as expected. The problem is that Foo$Inner is technically (behind the scenes) a totally separate class, whic h makes direct access to Foo's private members illegal. To bridge that gap, the compiler generates a couple of synthetic methods: /*package*/ static int Foo.acc ess$100(Foo foo) { return foo.mValue; } /*package*/ static void Foo.access$200(F oo foo, int value) { foo.doStuff(value); } The inner-class code calls these stat ic methods whenever it needs to access the "mValue" field or invoke the "doStuff " method in the outer class. What this means is that the code above really boils down to a case where you're accessing member fields through accessor methods in stead of directly. Earlier we talked about how accessors are slower than direct field accesses, so this is an example of a certain language idiom resulting in a n "invisible" performance hit. We can avoid this problem by declaring fields and methods accessed by inner classes to have package scope, rather than private sc ope. This runs faster and removes the overhead of the generated methods. (Unfort unately it also means the fields could be accessed directly by other classes in the same package, which runs counter to the standard OO practice of making all f ields private. Once again, if you're designing a public API you might want to ca refully consider using this optimization.) Avoid Float Before the release of the Pentium CPU, it was common for game authors to do as m uch as possible with integer math. With the Pentium, the floating point math coprocessor became a built-in feature, and by interleaving integer and floating-po int operations your game would actually go faster than it would with purely inte ger math. The common practice on desktop systems is to use floating point freely . Unfortunately, embedded processors frequently do not have hardware floating po int support, so all operations on "float" and "double" are performed in software . Some basic floating point operations can take on the order of a millisecond to complete. Also, even for integers, some chips have hardware multiply but lack h ardware divide. In such cases, integer division and modulus operations are perfo rmed in software something to think about if you're designing a hash table or do ing lots of math. Some Sample Performance Numbers http://developer.android.com/guide/practices/design/performance.html Page 7 of 8

Designing for Performance | Android Developers 29.04.09 0:58 To illustrate some of our ideas, here is a table listing the approximate run tim es for a few basic actions. Note that these values should NOT be taken as absolu te numbers: they are a combination of CPU and wall clock time, and will change a s improvements are made to the system. However, it is worth noting how these val ues apply relative to each other for example, adding a member variable currently takes about four times as long as adding a local variable. Action Add a local v ariable Add a member variable Call String.length() Call empty static native meth od Call empty static method Call empty virtual method Call empty interface metho d Call Iterator:next() on a HashMap Call put() on a HashMap Inflate 1 View from XML Inflate 1 LinearLayout containing 1 TextView Inflate 1 LinearLayout containi ng 6 View objects Inflate 1 LinearLayout containing 6 TextView objects Launch an empty activity Time 1 4 5 5 12 12.5 15 165 600 22,000 25,000 100,000 135,000 3, 000,000 Closing Notes The best way to write good, efficient code for embedded systems is to understand what the code you write really does. If you really want to allocate an iterator , by all means use enhanced for loop syntax on a List; just make it a deliberate choice, not an inadvertent side effect. Forewarned is forearmed! Know what you' re getting into! Insert your favorite maxim here, but always think carefully abo ut what your code is doing, and be on the lookout for ways to speed it up. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/practices/design/performance.html Page 8 of 8

Designing for Responsiveness | Android Developers 29.04.09 0:58 Designing for Responsiveness It's possible to write code that wins every performance test in the world, but s till sends users in a fiery rage when they try to use the application. These are the applications that aren't responsive enough the ones that feel sluggish, han g or freeze for significant periods, or take too long to process input. In Andro id, the system guards against applications that are insufficiently responsive fo r a period of time by displaying a dialog to the user, called the Application No t Responding (ANR) dialog. The user can choose to let the application continue, but the user won't appreciate having to act on this dialog every time he or she uses your application. So it's important to design responsiveness into your appl ication, so that the system never has cause to display an ANR to the user. Gener ally, the system displays an ANR if an application cannot respond to user input. For example, if an application blocks on some I/O operation (frequently a netwo rk access), then the main application thread won't be able to process incoming u ser input events. After a time, the system concludes that the application has hu ng, and displays the ANR to give the user the option to kill it. Similarly, if y our application spends too much time building an elaborate in-memory structure, or perhaps computing the next move in a game, the system will conclude that your application has hung. It's always important to make sure these computations are efficient using the techniques above, but even the most efficient code still ta kes time to run. In both of these cases, the fix is usually to create a child th read, and do most of your work there. This keeps the main thread (which drives t he user interface event loop) running, and prevents the system from concluding y our code has frozen. Since such threading usually is accomplished at the class l evel, you can think of responsiveness as a class problem. (Compare this with bas ic performance, which was described above as a method-level concern.) This docum ent discusses how the Android system determines whether an application is not re sponding and provides guidelines for ensuring that your application is responsiv e. This document covers these topics: What Triggers ANR? How to Avoid ANR Reinfo rcing Responsiveness What Triggers ANR? In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a partic ular application when it detects one of the following conditions: No response to an input event (e.g. key press, screen touch) within 5 seconds A BroadcastRecei ver hasn't finished executing within 10 seconds An ANR dialog displayed to the user. http://developer.android.com/guide/practices/design/responsiveness.html Page 1 of 2

Designing for Responsiveness | Android Developers 29.04.09 0:58 How to Avoid ANR Given the above definition for ANR, let's examine why this can occur in Android applications and how best to structure your application to avoid ANR. Android ap plications normally run entirely on a single (i.e. main) thread. This means that anything your application is doing in the main thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itse lf a chance to handle the input event or Intent broadcast. Therefore any method that runs in the main thread should do as little work as possible. In particular , Activities should do as little as possible to set up in key life-cycle methods such as onCreate() and onResume(). Potentially long running operations such as network or database operations, or computationally expensive calculations such a s resizing bitmaps should be done in a child thread (or in the case of databases operations, via an asynchronous request). However, this does not mean that your main thread should block while waiting for the child thread to complete nor sho uld you call Thread.wait() or Thread.sleep(). Instead of blocking while waiting for a child thread to complete, your main thread should provide a Handler for ch ild threads to post back to upon completion. Designing your application in this way will allow your main thread to remain responsive to input and thus avoid ANR dialogs caused by the 5 second input event timeout. These same practices should be followed for any other threads that display UI, as they are also subject to the same timeouts. The specific constraint on IntentReciever execution time emph asizes what they were meant to do: small, discrete amounts of work in the backgr ound such as saving a setting or registering a Notification. So as with other me thods called in the main thread, applications should avoid potentially long-runn ing operations or calculations in BroadcastReceivers. But instead of doing inten sive tasks via child threads (as the life of a BroadcastReceiver is short), your application should start a Service if a potentially long running action needs t o be taken in response to an Intent broadcast. As a side note, you should also a void starting an Activity from an Intent Receiver, as it will spawn a new screen that will steal focus from whatever application the user is currently has runni ng. If your application has something to show the user in response to an Intent broadcast, it should do so using the Notification Manager. Reinforcing Responsiveness Generally, 100 to 200ms is the threshold beyond which users will perceive lag (o r lack of "snappiness," if you will) in an application. As such, here are some a dditional tips beyond what you should do to avoid ANR that will help make your a pplication seem responsive to users. If your application is doing work in the ba ckground in response to user input, show that progress is being made (ProgressBa r and ProgressDialog are useful for this). For games specifically, do calculatio ns 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 qui ckly 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 rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/practices/design/responsiveness.html Page 2 of 2

Designing for Seamlessness | Android Developers 29.04.09 0:58 Designing for Seamlessness Even if your application is fast and responsive, certain design decisions can st ill cause problems for users because of unplanned interactions with other applic ations or dialogs, inadvertent loss of data, unintended blocking, and so on. To avoid these problems, it helps to understand the context in which your applicati ons run and the system interactions that can affect your application. In short, you should strive to develop an application that interacts seamlessly with the s ystem and with other applications. A common seamlessness problem is when an appl ication's background process for example, a service or broadcast receiver pops u p a dialog in response to some event. This may seem like harmless behavior, espe cially when you are building and testing your application in isolation, on the e mulator. However, when your application is run on an actual device, your applica tion may not have user focus at the time your background process displays the di alog. So it could end up that your application would display it's dialog behind the active application, or it could take focus from the current application and display the dialog in front of whatever the user was doing (such as dialing a ph one call, for example). That behavior would not work for your application or for the user. To avoid these problems, your application should use the proper syste m facility for notifying the user the Notification classes. Using notifications, your application can signal the user that an event has taken place, by displayi ng an icon in the status bar rather than taking focus and interrupting the user. Another example of a seamlessness problem is when an activity inadvertently los es state or user data because it doesn't correctly implement the onPause() and o ther lifecycle methods. Or, if your application exposes data intended to be used by other applications, you should expose it via a ContentProvider, rather than (for example) doing so through a world-readable raw file or database. What those examples have in common is that they involve cooperating nicely with the system and other applications. The Android system is designed to treat applications as a sort of federation of loosely-coupled components, rather than chunks of black -box code. This allows you as the developer to view the entire system as just an even-larger federation of these components. This benefits you by allowing you t o integrate cleanly and seamlessly with other applications, and so you should de sign your own code to return the favor. This document discusses common seamlessn ess problems and how to avoid them. It covers these topics: Don't Drop Data Don' t Expose Raw Data Don't Interrupt the User Got a Lot to Do? Do it in a Thread Do n't Overload a Single Activity Screen Extend System Themes Design Your UI to Wor k with Multiple Screen Resolutions Assume the Network is Slow Don't Assume Touch screen or Keyboard Do Conserve the Device Battery Don't Drop Data http://developer.android.com/guide/practices/design/seamlessness.html Page 1 of 4

Designing for Seamlessness | Android Developers 29.04.09 0:58 Always keep in mind that Android is a mobile platform. It may seem obvious to sa y it, but it's important to remember that another Activity (such as the "Incomin g Phone Call" app) can pop up over your own Activity at any moment. This will fi re the onSaveInstanceState() and onPause() methods, and will likely result in yo ur application being killed. If the user was editing data in your application wh en 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 fi rst. The "Android Way" is to do just that: Android applications that accept or e dit 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 i s a mail application. If the user was composing an email when another Activity s tarted up, the application should save the in-process email as a draft. Don't Expose Raw Data If you wouldn't walk down the street in your underwear, neither should your data . While it's possible to expose certain kinds of application to the world to rea d, this is usually not the best idea. Exposing raw data requires other applicati ons to understand your data format; if you change that format, you'll break any other applications that aren't similarly updated. The "Android Way" is to create a ContentProvider to expose your data to other applications via a clean, well-t houghtout, and maintainable API. Using a ContentProvider is much like inserting a Java language interface to split up and componentize two tightly-coupled piece s of code. This means you'll be able to modify the internal format of your data without changing the interface exposed by the ContentProvider, and this without affecting other applications. Don't Interrupt the User If the user is running an application (such as the Phone application during a ca ll) it's a pretty safe bet he did it on purpose. That's why you should avoid spa wning activities except in direct response to user input from the current Activi ty. That is, don't call startActivity() from BroadcastReceivers or Services runn ing in the background. Doing so will interrupt whatever application is currently running, and result in an annoyed user. Perhaps even worse, your Activity may b ecome a "keystroke bandit" and receive some of the input the user was in the mid dle of providing to the previous Activity. Depending on what your application do es, this could be bad news. Instead of spawning Activity UIs directly from the b ackground, you should instead use the NotificationManager to set Notifications. These will appear in the status bar, and the user can then click on them at his leisure, to see what your application has to show him. (Note that all this doesn 't apply to cases where your own Activity is already in the foreground: in that case, the user expects to see your next Activity in response to input.) Got a Lot to Do? Do it in a Thread If your application needs to perform some expensive or long-running computation, you should probably move it to a thread. This will prevent the dreaded "Applica tion Not Responding" dialog from being displayed to the user, with the ultimate result being the fiery demise of your application. By default, all code in an Ac tivity as well as all its Views run in the same thread. This is the same thread that also handles UI events. For example, when the user presses a key, a key-dow n event is added to the Activity's main thread's queue. The event handler system needs to dequeue and handle that event quickly; if it doesn't, the system concl udes after a few seconds that the application is hung and offers to kill it for the user. http://developer.android.com/guide/practices/design/seamlessness.html Page 2 of 4

Designing for Seamlessness | Android Developers 29.04.09 0:58 If you have long-running code, running the event handler thread, effectively ay input processing, and result in the putations to a thread. This Design for do that.. it inline in your Activity will run it on blocking the event handler. This will del ANR dialogs. To avoid this, move your com Responsiveness document discusses how to

Don't Overload a Single Activity Screen Any application worth using will probably have several different screens. When d esigning the screens of your UI, be sure to make use of multiple Activity object instances. Depending on your development background, you may interpret an Activ ity as similar to something like a Java Applet, in that it is the entry point fo r your application. However, that's not quite accurate: where an Applet subclass is the single entry point for a Java Applet, an Activity should be thought of a s one of potentially several entry points to your application. The only differen ce between your "main" Activity and any others you might have is that the "main" one just happens to be the only one that expressed an interest in the "android. intent.action.MAIN" action in your AndroidManifest..xml file. So, when designing your application, think of your application as a federation of Activity objects . This will make your code a lot more maintainable in the long run, and as a nic e side effect also plays nicely with Android's application history and "backstac k" model. Extend System Themes When it comes to the look-and-feel of the user interface, it's important to blen d in nicely. Users are jarred by applications which contrast with the user inter face they've come to expect. When designing your UIs, you should try and avoid r olling your own as much as possible. Instead, use a Theme. You can override or e xtend those parts of the theme that you need to, but at least you're starting fr om the same UI base as all the other applications. For all the details, read App lying Styles and Themes. Design Your UI to Work with Multiple Screen Resolutions Different Android-powered devices will support different screen resolutions. Som e will even be able to change resolutions on the fly, such as by switching to la ndscape mode. It's important to make sure your layouts and drawables are flexibl e enough to display properly on a variety of device screens. Fortunately, this i s very easy to do. In brief, what you must do is provide different versions of y our artwork (if you use any) for the key resolutions, and then design your layou t to accommodate various dimensions. (For example, avoid using hard-coded positi ons and instead use relative layouts.) If you do that much, the system handles t he rest, and your application looks great on any device. Assume the Network is Slow Android devices will come with a variety of network-connectivity options. All wi ll have some data-access provision, though some will be faster than others. The lowest common denominator, however, is GPRS, the non-3G data service for GSM net works. Even 3G-capable devices will spend lots of time on non-3G networks, so sl ow networks will remain a reality for quite a long time to come. That's why you should always code your applications to minimize network accesses and bandwidth. You can't assume the network is fast, so you should always plan for it to be sl ow. If your users happen to be on faster networks, then that's great their exper ience will only improve. You want to avoid the inverse case though: applications that are usable some of the time, but frustratingly slow the rest based on wher e the user is at any given moment are likely to be unpopular. http://developer.android.com/guide/practices/design/seamlessness.html Page 3 of 4

Designing for Seamlessness | Android Developers 29.04.09 0:58 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 compute r's network connection. That's almost guaranteed to be much faster than a cell n etwork, so you'll want to change the settings on the emulator that simulate slow er 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 emulat or. Don't Assume Touchscreen or Keyboard Android will support a variety of handset form-factors. That's a fancy way of sa ying that some Android devices will have full "QWERTY" keyboards, while others w ill have 40-key, 12-key, or even other key configurations. Similarly, some devic es will have touch-screens, but many won't. When building your applications, kee p that in mind. Don't make assumptions about specific keyboard layouts -- unless , of course, you're really interested in restricting your application so that it can only be used on those devices. Do Conserve the Device Battery A mobile device isn't very mobile if it's constantly plugged into the wall. Mobi le devices are battery-powered, and the longer we can make that battery last on a charge, the happier everyone is especially the user. Two of the biggest consum ers of battery power are the processor, and the radio; that's why it's important to write your applications to do as little work as possible, and use the networ k as infrequently as possible. Minimizing the amount of processor time your appl ication uses really comes down to writing efficient code. To minimize the power drain from using the radio, be sure to handle error conditions gracefully, and o nly fetch what you need. For example, don't constantly retry a network operation if one failed. If it failed once, it's likely because the user has no reception , so it's probably going to fail again if you try right away; all you'll do is w aste battery power. Users are pretty smart: if your program is power-hungry, you can count on them noticing. The only thing you can be sure of at that point is that your program won't stay installed very long. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/practices/design/seamlessness.html Page 4 of 4

Hello, World | Android Developers 29.04.09 1:00 Hello, World As a developer, you know that the first impression of a development framework is how easy it is to write "Hello, World." Well, on Android, it's pretty easy. It' s particularly easy if you're using Eclipse as your IDE, because we've provided a great plugin that handles your project creation and management to greatly spee d-up your development cycles. If you're not using Eclipse, that's okay. Familiar ize yourself with Developing in Other IDEs. You can then return to this tutorial and ignore anything about Eclipse. Before you start, you should already have th e very latest SDK installed, and if you're using Eclipse, you should have instal led the ADT plugin as well. If you have not installed these, see Installing the Android SDK and return here when you've completed the installation. Create an AVD Note: If you're developing with an Android SDK older than the one provided for A ndroid 1.5, you can skip this step and continue with Create the Project. In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD de fines the system image and device settings used by the emulator. To create an AV D, use the "android" tool provided in the Android SDK. Open a command prompt or terminal, navigate to the tools/ directory in the SDK package and execute: andro id create avd --target 2 --name my_avd The tool now asks if you would like to cr eate a custom hardware profile. For the time being, press Return to skip it ("no " is the default response). That's it. This configures an AVD named "my_avd" tha t uses the Android 1.5 platform. The AVD is now ready for use in the emulator. I n the above command, the --target option is required and specifies the deploymen t target to run on the emulator. The -name option is also required and defines t he name for the new AVD. To learn more about Android Virtual Devices (and targets), refer to the AVD docu ment. Create a New Android Project After you've created an AVD, the next step is to start a new Android project in Eclipse. 1. From Eclipse, select File > New > Project. If the ADT Plugin for Ecl ipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available .) http://developer.android.com/guide/tutorials/hello-world.html Page 1 of 9

Hello, World | Android Developers 29.04.09 1:00 2. Selected "Android Project" and click Next. 3. Fill in the project details wit h the following values: Project name: HelloAndroid Application name: Hello, Andr oid Package name: com.example.helloandroid (or your own private namespace) Creat e Activity: HelloAndroid Min SDK Version: 2 Click Finish. Here is a description of each field: Project Name This is the Eclipse Project na me the name of the directory that will contain the project files. Application Na me This is the human-readable title for your application the name that will appe ar on the Android device. Package Name This is the package namespace (following the same rules as for packages in the Java programming language) that you want a ll your source code to reside under. This also sets the package name under which the stub Activity will be generated. Your package name must be unique across al l packages installed on the Android system; for this reason, it's very important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example doc umentation when you develop your own applications, you should use a namespace th at's appropriate to your organization or entity. http://developer.android.com/guide/tutorials/hello-world.html Page 2 of 9

Hello, World | Android Developers 29.04.09 1:00 Create Activity This is the name for the class stub that will be generated by th e plugin. This will be a subclass of Android's Activity class. An Activity is si mply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application. Min SDK Version This value s pecifies the minimum API Level required by your application. If the API Level en tered here matches the API Level provided by one of the available targets, then that Build Target will be automatically selected (in this case, entering "2" as the API Level will select the Android 1.1 target). With each new version of the Android system image and Android SDK, there have likely been additions or change s made to the APIs. When this occurs, a new API Level is assigned to the system image to regulate which applications are allowed to be run. If an application re quires an API Level that is higher than the level supported by the device, then the application will not be installed. Other fields: The checkbox for "Use defau lt location" allows you to change the location on disk where the project's files will be generated and stored. "Build Target" is the platform target that your a pplication will be compiled against (this should be selected automatically, base d on your Min SDK Version). Notice that the "Build Target" you've selected uses the Android 1.1 platform. This means that your application will be compiled agai nst the Android 1.1 platform library. If you recall, the AVD created above runs on the Android 1.5 platform. These don't have to match; Android applications are forward-compatible, so an application built against the 1.1 platform library wi ll run normally on the 1.5 platform. The reverse is not true. Your Android proje ct is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.hell oandroid). It should look like this: package com.example.helloandroid; import an droid.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public vo id onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); set ContentView(R.layout.main); } } Notice that the class is based on the Activity c lass. An Activity is a single application entity that is used to perform actions . An application may have many separate activities, but the user interacts with them one at a time. The onCreate() method will be called by the Android system w hen your Activity starts it is where you should perform all initialization and U I setup. An activity is not required to have a user interface, but usually will. Now let's modify some code! Construct the UI Take a look at the revised code below and then make the same changes to your Hel loAndroid class. The bold items are lines that have been added. package com.andr oid.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; http://developer.android.com/guide/tutorials/hello-world.html Page 3 of 9

Hello, World | Android Developers 29.04.09 1:00 public class HelloAndroid extends Activity { /** Called when the activity is fir st created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hel lo, Android"); setContentView(tv); } } Tip: An easy way to add import packages t o your project is to press Ctrl-Shift-O (Cmd-Shift-O, on Mac). This is an Eclips e shortcut that identifies missing packages based on your code and adds them for you. An Android user interface is composed of hierarchies of objects called Vie ws. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subcla ss of the View class and the subclass that handles text is TextView. In this cha nge, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is a handle to the system; it provi des services like resolving resources, obtaining access to databases and prefere nces, and so on. The Activity class inherits from Context, and because your Hell oAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView. Next, you define the text conte nt with setText(CharSequence) setText(). Finally, you pass the TextView to setCo ntentView() in order to display it as the content for the Activity UI. If your A ctivity doesn't call this method, then no UI is present and the system will disp lay a blank screen. There it is "Hello, World" in Android! The next step, of cou rse, is to see it running. Run the Application The Eclipse plugin makes it very easy to run your applications: 1. Select Run > Run. 2. Select "Android Application". The Eclipse ADT will automatically create a new run configuration for your project and the Android Emulator will automatic ally launch. Once the emulator is booted up, your application will appear after a moment. You should now see something like this: To learn more about creating and editing run configurations in Eclipse, refer to Developing In Eclipse, with ADT. http://developer.android.com/guide/tutorials/hello-world.html Page 4 of 9

Hello, World | Android Developers 29.04.09 1:00 The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in the res/ values/strings.xml file and referenced by your AndroidManifest.xml file). The te xt below the title is the actual text that you have created in the TextView obje ct. That concludes the basic "Hello World" tutorial, but you should continue rea ding for some more valuable information about developing Android applications. Upgrade the UI to an XML Layout The "Hello, World" example you just completed uses what is called a "programmati c" UI layout. This means that you constructed and built your application's UI di rectly in source code. If you've done much UI programming, you're probably famil iar with how brittle that approach can sometimes be: small changes in layout can result in big source-code headaches. It's also very easy to forget to properly connect Views together, which can result in errors in your layout and wasted tim e debugging your code. That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to sho w an example. Here's an XML layout file that is identical in behavior to the pro grammatically-constructed example: <?xml version="1.0" encoding="utf-8"?> <TextV iew xmlns:android="http://schemas.android.com/apk/res/android" android:layout_wi dth="fill_parent" android:layout_height="fill_parent" android:text="@string/hell o"/> The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, ho wever, is just one View element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you defin e in your own code. This structure makes it very easy to quickly build up UIs, u sing a more simple structure and syntax than you would use in a programmatic lay out. This model is inspired by the web development model, wherein you can separa te the presentation of your application (its UI) from the application logic used to fetch and fill in data. In the above XML example, there's just one View elem ent: the TextView, which has four XML attributes. Here's a summary of what they mean: Attribute xmlns:android Meaning This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must h ave this attribute. Page 5 of 9 http://developer.android.com/guide/tutorials/hello-world.html

Hello, World | Android Developers 29.04.09 1:00 android:layout_width This attribute defines how much of the available width on the screen this View s hould consume. In this case, it's the only View so you want it to take up the en tire screen, which is what a value of "fill_parent" means. This is just like and roid:layout_width, except that it refers to available screen height. This sets t he text that the TextView should display. In this example, you use a string reso urce instead of a hard-coded string value. The hello string is defined in the re s/values/strings.xml file. This is the recommended practice for inserting string s to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file. For more information, see Resources and Internationalization. android:layout_height android:text These XML layout files belong in the res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code asset s that your application requires. In addition to layout files, resources also in clude assets such as images, sounds, and localized strings. The Eclipse plugin a utomatically creates one of these layout files for you: main.xml. In the "Hello World" application you just completed, this file was ignored and you created a l ayout programmatically. This was meant to teach you more about the Android frame work, but you should almost always define your layout in an XML file instead of in your code. The following procedures will instruct you how to change your exis ting application to use an XML layout. Landscape layout XML file inside layout changes. etch the default When you want a different design for landscape, put your layout /res/layout-land. Android will automatically look here when the Without this special landscape layout defined, Android will str layout.

1. In the Eclipse Package Explorer, expand the /res/layout/ folder and open main .xml (once opened, you might need to click the "main.xml" tab at the bottom of t he window to see the XML source). Replace the contents with the following XML: < ?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.an droid.com/apk/res/android" android:layout_width="fill_parent" android:layout_hei ght="fill_parent" android:text="@string/hello"/> Save the file. 2. Inside the re s/values/ folder, open strings.xml. This is where you should save all default te xt strings for your user interface. If you're using Eclipse, then ADT will have started you with two strings, hello and app_name. Revise hello to something else . Perhaps "Hello, Android! I am a string resource!" The entire file should now l ook like this: <?xml version="1.0" encoding="utf-8"?> <resources> <string name=" hello">Hello, Android! I am a string resource!</string> <string name="app_name"> Hello, Android</string> </resources> 3. Now open and modify your HelloAndroid cl ass use the XML layout. Edit the file to look like this: package com.example.hel loandroid; import android.app.Activity; import android.os.Bundle; public class H elloAndroid extends Activity { /** Called when the activity is first created. */ http://developer.android.com/guide/tutorials/hello-world.html Page 6 of 9

Hello, World | Android Developers 29.04.09 1:00 } When you make this change, type it by hand to try the code-completion feature. As you begin typing "R.layout.main" the plugin will offer you suggestions. You' ll find that it helps in a lot of situations. Instead of passing setContentView( ) a View object, you give it a reference to the layout resource. The resource is identified as R.layout.main, which is actually a compiled object representation of the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you when you run Ant to build the application. (More about the R class in a moment.) Now re-run your application because you've created a launch configuration, all you need to do i s click the green arrow icon to run, or select Run > Run History > Android Activ ity. Other than the change to the TextView string, the application looks the sam e. After all, the point was to show that the two different layout approaches pro duce identical results. Tip: Use the shortcut Ctrl-F11 (Cmd-Shift-F11, on Mac) t o run your currently visible application. Continue reading for an introduction t o debugging and a little more information on using other IDEs. When you're ready to learn more, read Application Fundamentals for an introduction to all the ele ments that make Android applications work. Also refer to the Developer's Guide i ntroduction page for an overview of the Dev Guide documentation. /** Called when the activity is first created. */ @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView (R.layout.main); } R class In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folde r). It should look something like this: package com.example.helloandroid; public final class R { public static final class attr { } public static final class dr awable { public static final int icon=0x7f020000; } public static final class la yout { public static final int main=0x7f030000; } public static final class stri ng { public static final int app_name=0x7f040001; public static final int hello= 0x7f040000; } } A project's R.java file is an index into all the resources defin ed in the file. You use this class in your source code as a sort of short-hand w ay to refer to resources you've included in your project. This is particularly p owerful with the code-completion features of IDEs like Eclipse because it lets y ou quickly and interactively locate the specific reference you're looking for. I t's possible yours looks slighly different than this (perhaps the hexadecimal va lues are different). For now, notice the inner class named "layout", and its mem ber field "main". The Eclipse plugin noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (s uch as strings in the res/values/string.xml file or drawables inside the res/dra wable/ direcory) you'll see R.java change to keep up. When not using Eclipse, th is class file will be generated for you at build time (with the Ant tool). You s hould never edit this file by hand. http://developer.android.com/guide/tutorials/hello-world.html Page 7 of 9

Hello, World | Android Developers 29.04.09 1:00 Debug Your Project The Android Plugin for Eclipse also has excellent integration with the Eclipse d ebugger. To demonstrate this, introduce a bug into your code. Change your HelloA ndroid source code to look like this: package com.android.helloandroid; import a ndroid.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public v oid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Ob ject o = null; o.toString(); setContentView(R.layout.main); } } This change simp ly introduces a NullPointerException into your code. If you run your application again, you'll eventually see this: Press "Force Quit" to terminate the application and close the emulator window. T o find out more about the error, set a breakpoint in your source code on the lin e Object o = null; (doubleclick on the marker bar next to the source code line). Then select Run > Debug History > Hello, Android from the menu to enter debug m ode. Your app will restart in the emulator, but this time it will suspend when i t reaches the breakpoint you set. You can then step through the code in Eclipse' s Debug Perspective, just as you would for any other application. http://developer.android.com/guide/tutorials/hello-world.html Page 8 of 9

Hello, World | Android Developers 29.04.09 1:00 Creating the Project without Eclipse If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't wo rry though you don't lose any functionality just because you don't use Eclipse. The Android Plugin for Eclipse is really just a wrapper around a set of tools in cluded with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, a nd others are documented elsewhere.) Thus, it's possible to wrap those tools wit h another tool, such as an 'ant' build file. The Android SDK includes a tool nam ed "android" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatible build.xml file. This allows you t o build your project from the command line, or integrate it with the IDE of your choice. For example, to create a HelloAndroid project similar to the one create d in Eclipse, use this command: android create project \ --package com.android.h elloandroid \ --activity HelloAndroid \ --target 2 \ --path <path-to-your-projec t>/HelloAndroid This creates the required folders and files for the project at t he location defined by the path. For more information on how to use the SDK tool s to create and build projects, please read Developing in Other IDEs. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/tutorials/hello-world.html Page 9 of 9

Hello, Views | Android Developers 29.04.09 1:00 Hello, Views This collection of "Hello World"-style tutorials is designed to get you quickly started with common Android Views and widgets. The aim is to let you copy and pa ste these kinds of boring bits so you can focus on developing the code that make s your Android application rock. Of course, we'll discuss some of the given code so that it all makes sense. Note that a certain amount of knowledge is assumed for these tutorials. If you haven't completed the Hello, World tutorial, please do soit will teach you many things you should know about basic Android developmen t and Eclipse features. More specifically, you should know: How to create a new Android project. The basic structure of an Android project (resource files, layo ut files, etc.). The essential components of an Activity. How to build and run a project. Please, also notice that, in order to make these tutorials simple, som e may not convey the better Android coding practices. In particular, many of the m use hard-coded strings in the layout filesthe better practice is to reference s trings from your strings.xml file. With this knowledge, you're ready to begin, s o take your pick. LinearLayout RelativeLayout TableLayout DatePicker http://developer.android.com/guide/tutorials/views/index.html Page 1 of 4

Hello, Views | Android Developers 29.04.09 1:00 TimePicker Form Stuff Spinner AutoComplete http://developer.android.com/guide/tutorials/views/index.html Page 2 of 4

Hello, Views | Android Developers 29.04.09 1:00 ListView GridView Gallery TabWidget http://developer.android.com/guide/tutorials/views/index.html Page 3 of 4

Hello, Views | Android Developers 29.04.09 1:00 MapView WebView There are plenty more Views and widgets available. See the View class for more o n View layouts, and the widget package for more useful widgets. And for more raw code samples, visit the Api Demos. These can also be found offline, in /<sdk>/s amples/ApiDemos. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/tutorials/views/index.html Page 4 of 4

Notepad Tutorial | Android Developers 29.04.09 1:00 Notepad Tutorial This tutorial on writing a notepad application gives you a "hands-on" introducti on to the Android framework and the tools you use to build applications on it. S tarting from a preconfigured project file, it guides you through the process of developing a simple notepad application and provides concrete examples of how to set up the project, develop the application logic and user interface, and then compile and run the application. The tutorial presents the application developme nt as a set of exercises (see below), each consisting of several steps. You shou ld follow the steps in each exercise to gradually build and refine your applicat ion. The exercises explain each step in detail and provide all the sample code y ou need to complete the application. When you are finished with the tutorial, yo u will have created a functioning Android application and will have learned many of the most important concepts in Android development. If you want to add more complex features to your application, you can examine the code in an alternative implementation of a Note Pad application, in the Sample Code section. Who Should Use this Tutorial This tutorial is designed for experienced developers, especially those with know ledge of the Java programming language. If you haven't written Java applications before, you can still use the tutorial, but you might need to work at a slower pace. Also note that this tutorial uses the Eclipse development environment, wit h the Android plugin installed. If you are not using Eclipse, you can follow the exercises and build the application, but you will need to determine how to acco mplish the Eclipse-specific steps in your environment. Preparing for the Exercises The tutorial assumes that you have some familiarity with basic Android applicati on concepts and terminology. If you are not, you should read Application Fundame ntals before continuing. This tutorial also builds on the introductory informati on provided in the Hello World tutorial, which explains how to set up your Eclip se environment for building Android applications. We recommend you complete the Hello World tutorial before starting this one. To prepare for this lesson: 1. Do wnload the project exercises archive (.zip). 2. Unpack the archive file to a sui table location on your machine. 3. Open the NotepadCodeLab folder. Inside the No tepadCodeLab folder, you should see six project files: Notepadv1, Notepadv2, Not epadv3, Notepadv1Solution, Notepadv2Solution and Notepadv3Solution. The Notepadv # projects are the starting points for each of the exercises, while the Notepadv #Solution projects are the exercise solutions. If you are having trouble with a particular exercise, you can compare your current work against the exercise solu tion. http://developer.android.com/guide/tutorials/notepad/index.html Page 1 of 2

Notepad Tutorial | Android Developers 29.04.09 1:00 Exercises The table below lists the tutorial exercises and describes the development areas that each covers. Each exercise assumes that you have completed any previous ex ercises. Exercise 1 Start here. Construct a simple notes list that lets the user add new notes but not edit them. Demonstrates the basics of ListActivity and cr eating and handling menu options. Uses a SQLite database to store the notes. Add a second Activity to the application. Demonstrates constructing a new Activity, adding it to the Android manifest, passing data between the activities, and usi ng more advanced screen layout. Also shows how to invoke another Activity to ret urn a result, using startActivityForResult(). Add handling of life-cycle events to the application, to let it maintain application state across the life cycle. Demonstrates how to use the Eclipse debugger and how you can use it to view life -cycle events as they are generated. This section is optional but highly recomme nded. Exercise 2 Exercise 3 Extra Credit Other Resources and Further Learning For a lighter but broader introduction to concepts not covered in the tutorial, take a look at Common Android Tasks. The Android SDK includes a variety of fully functioning sample applications that make excellent opportunities for further l earning. You can find the sample applications in the samples/ directory of your downloaded SDK, or browser them here, in the Sample Code section. This tutorial draws from the full Notepad application included in the samples/ directory of th e SDK, though it does not match it exactly. When you are done with the tutorial, it is highly recommended that you take a closer look at this version of the Not epad application, as it demonstrates a variety of interesting additions for your application, such as: Setting up a custom striped list for the list of notes. C reating a custom text edit view that overrides the draw() method to make it look like a lined notepad. Implementing a full ContentProvider for notes. Reverting and discarding edits instead of just automatically saving them. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/tutorials/notepad/index.html Page 2 of 2

Sample Code | Android Developers 29.04.09 1:00 Sample Code Sometimes, the best way to learn how things are done is to just look at some cod e. So here we've provided links to let you browse the source of some some simple Android applications. The source code for these applications is included in the Android SDK, in this location: <sdk>/samples/ You can easily add these applicat ions as projects in your development environment, so that you can modify them an d watch them execute. API Demos A variety of small applications that demonstrate simple views and widgets. Lunar Lander A classic Lunar Lander game. Note Pad An application for saving notes. Similar (but not identical) to the Notepad tutori al. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/samples/index.html Page 1 of 1

Android Supported Media Formats | Android Developers 29.04.09 1:01 Android Supported Media Formats The Core Media Formats table below describes the media format support built into the Android platform. Note that any given mobile device may provide support for additional formats or file types not listed in the table. For your convenience, the table T-Mobile G1 Media Formats describes additional media format details f or the T-Mobile G1 device. Core Media Formats Type Audio Format AAC LC/LTP HE-AACv1 (AAC+) HE-AACv2 (enhanced AAC+) AMR-NB AMR -WB MP3 X Encoder Decoder X X X Details Mono/Stereo content in any combination o f standard bit rates up to 160 kbps and sampling rates from 8 to 48kHz File Type (s) Supported 3GPP (.3gp) and MPEG-4 (.mp4, .m4a). No support for raw AAC (.aac) X X X 4.75 to 12.2 kbps sampled @ 8kHz 9 rates from 6.60 kbit/s to 23.85 kbit/s sample d @ 16kHz Mono/Stereo 8-320Kbps constant (CBR) or variable bitrate (VBR) MIDI Ty pe 0 and 1. DLS Version 1 and 2. XMF and Mobile XMF. Support for ringtone format s RTTTL/RTX, OTA, and iMelody 3GPP (.3gp) 3GPP (.3gp) MP3 (.mp3) MIDI X Type 0 and 1 (.mid, .xmf, .mxmf). Also RTTTL/RTX (.rtttl, .rtx), OTA (.ota), and iMelody (.imy) Ogg (.ogg) Ogg Vorbis PCM/WAVE Image JPEG GIF PNG BMP X X X X X X X 8- and 16-bit linear PCM (rates up to limit of hardware) Base+progre ssive WAVE (.wav) JPEG (.jpg) GIF (.gif) PNG (.png) BMP (.bmp) http://developer.android.com/guide/appendix/media-formats.html Page 1 of 2

Android Supported Media Formats | Android Developers 29.04.09 1:01 Video H.263 H.264 AVC MPEG-4 SP X X X X 3GPP (.3gp) 3GPP (.3gp) and MPEG-4 (.mp4) 3GPP (.3gp) T-Mobile G1 Media Formats In addition to the core media formats supported in the Android platform, the T-M obile G1 also supports the formats listed below. Type Format Encoder Decoder Det ails File Type(s) Supported Windows Media Audio (.wma) Audio WMA X Supports WMA standard L1-L3: L1: 64 kbps - 161 kbps @ 44.1kHz L2: <=161 kbps <=4 8 kHz L3: <385 kbps <=48 kHz Mono and stereo profiles with 16-bits per sample. D ecoder does not support WMA Pro, Lossless, or Speech codecs. Video WMV X Versions 7, 8 and 9. Simple profile only Windows Media Video (.wmv) 3GPP (.3gp) and MPEG-4 (.mp4) H.263 X X H.264 AVC X Limited to baseline profile up to 480x320, and 600 kbps average bitrate for the video stream. 3GPP (.3gp) and MPEG-4 (.mp4) Note that Windows Media codecs are not part of the Android platform and require special licensing from Microsoft or an authorized developer such as Packet Video . Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines

! Go to top http://developer.android.com/guide/appendix/media-formats.html Page 2 of 2

Intents List: Invoking Google Applications on Android Devices | Android Develope rs 29.04.09 1:01 Intents List: Invoking Google Applications on Android Devices The table below lists the intents that your application can send, to invoke Goog le applications on Android devices in certain ways. For each action/uri pair, th e table describes how the receiving Google application handles the intent. Note that this list is not comprehensive. Target Application Browser Intent URI http: //web_address https://web_address "" (empty string) http://web_address https://w eb_address Dialer tel: phone_number Intent Action VIEW WEB_SEARCH Result Open a browser window to the URL specified. Opens the file at the location on the devic e in the browser. Calls the entered phone number. Valid telephone numbers as def ined in the IETF RFC 3966 are accepted. Valid examples include the following: te l:2125551212 tel: (212) 555 1212 The dialer is good at normalizing some kinds of schemes: for example telephone numbers, so the schema described isn't strictly required in the Uri(URI string) factory. However, if you have not tried a schema or are unsure whether it can be handled, use the Uri.fromParts(scheme, ssp, fra gment) factory instead. Note: This requires your application to request the foll owing permission in your manifest: <uses-permission id="android.permission.CALL_ PHONE" /> tel:phone_number voicemail: DIAL Dials (but does not actually initiate the call) the number given (or the stored voicemail on the phone). Telephone nu mber normalization described for CALL applies to DIAL as well. Opens the Maps ap plication to the given location or query. The Geo URI scheme (not fully supporte d) is currently under development. The z field specifies the zoom level. A zoom level of 1 shows the whole Earth, centered at the given lat,lng. A zoom level of 2 shows a quarter of the Earth, and so on. The highest zoom level is 23. A larg er zoom level will be clamped to 23. Opens the Street View application to the gi ven location. The URI scheme is based on the syntax used for Street View panoram a information in Google Maps URLs. The cbll field is required. The cbp and mz fi elds are optional. lat lng yaw http://developer.android.com/guide/appendix/g-app-intents.html For more information about intents, see the Intents and Intent Filters. CALL Google Maps geo:latitude,longitude geo:latitude,longitude?z=zoom geo:0,0?q=my+street+address geo:0,0?q=business+near+city VIEW Google Streetview google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom VIEW latitude longitude Panorama center-of-view Page 1 of 2

Intents List: Invoking Google Applications on Android Devices | Android Develope rs 29.04.09 1:01 in degrees clockwise from North. Note: The two commas after the yaw parameter ar e required. They are present for backwardscompatibility reasons. pitch Panorama center-of-view in degrees from -90 (look straight up) to 90 (look straight down. ) Panorama zoom. 1.0 = normal zoom, 2.0 = zoomed in 2x, 3.0 = zoomed in 4x, and so on. A zoom of 1.0 is 90 degree horizontal FOV for a nominal landscape mode 4 x 3 aspect ratio display Android phones in portrait mode will adjust the zoom so that the vertical FOV is approximately the same as the landscape vertical FOV. This means that the horizontal FOV of an Android phone in portrait mode is much narrower than in landscape mode. This is done to minimize the fisheye lens effec t that would be present if a 90 degree horizontal FOV was used in portrait mode. The map zoom of the map location associated with this panorama. This value is p assed on to the Maps activity when the Street View "Go to Maps" menu item is cho sen. It corresponds to the z paramaeter in the geo: intent. zoom mapZoom Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/g-app-intents.html Page 2 of 2

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 FAQs, Tips, and How-to > Common Tasks and How to Do Them in Android Creating an Android Application using the Eclipse plugin Creating an Android App lication without the Eclipse plugin Adding an External Library (.jar) using Ecli pse Implementing Activity callbacks (Android calls your activity at various key moments in its life cycle. You must know how to handle each of these to draw you r screen, initialize class members, and acquire data.) Opening a new screen List ening for button clicks Configuring general window properties Referring to local host from the emulated environment Storing and retrieving state Storing and retr ieving preferences Storing and retrieving larger or more complex persistent data (files and data) Playing audio, video, still, or other media files Listening fo r and broadcasting global messages and setting alarms Displaying alerts Displayi ng a progress bar Adding items to the screen menu Display a web page Binding to data Getting a Handle to a Screen Element Capture images from the phone camera H andling expensive operations in the UI thread Selecting, highlighting, or stylin g portions of text Utilizing attributes in a Map query List of files for an Andr oid application Print messages to a log file The ApiDemos sample application inc ludes many, many examples of common tasks and UI features. See the code inside < sdk>samples/ApiDemos and the other sample applications under the samples/ folder in the SDK. Creating an Android Application using the Eclipse Plugin Using the Android Eclipse plugin is the fastest and easiest way to start creatin g a new Android application. The plugin automatically generates the correct proj ect structure for your application, and keeps the resources compiled for you aut omatically. It is still a good idea to know what is going on though. Take a look at Application Fundamentals to understand the basics of how an Android applicat ion works. http://developer.android.com/guide/appendix/faq/commontasks.html Page 1 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 basics of how an Android application works. You should also take a look at the A piDemos application and the other sample applications included in the SDK, in th e <sdk>/samples/ folder in the SDK. Finally, a great way to started with Android development in Eclipse is to follow both the Hello, World and Notepad code tuto rials. In particular, the start of the Hello Android tutorial is an excellent in troduction to creating a new Android application in Eclipse. Creating an Android Application without the Eclipse Plugin This topic describes the manual steps in creating an Android application. Before reading this, you should read Application Fundamentals to understand the basics of how an Android application works. You might also want to look at the sample code included with the Android SDK, in the <sdk>/samples/ directory. Here is a l ist of the basic steps in building an application. 1. Create your required resou rce files This includes the AndroidManifest.xml global description file, string files that your application needs, and layout files describing your user interfa ce. A full list of optional and required files and syntax details for each is gi ven in File List for an Android Application. 2. Design your user interface Andro id screen. See User Interface for details on elements of the 3. Implement your Activity (this page) You will create one class/file for each s creen in your application. Screens will inherit from an android.app class, typic ally android.app.Activity for basic screens, android.app.ListActivity for list s creens, or android.app.Dialog for dialog boxes. You will implement the required callbacks that let you draw your screen, query data, and commit changes, and als o perform any required tasks such as opening additional screens or reading data from the device. Common tasks, such as opening a new screen or reading data from the device, are described below. The list of files you'll need for your applica tion are described in List of Files for an Android Application. 4. Build and ins tall your package. The Android SDK has some nice tools for generating projects a nd debugging code. Adding an External Library (.jar) using Eclipse You can use a third party JAR in your application by adding it to your Eclipse p roject as follows: 1. In the Package Explorer panel, right-click on your project and select Properties. 2. Select Java Build Path, then the tab Libraries. 3. Pr ess the Add External JARs... button and select the JAR file. Alternatively, if y ou want to include third party JARs with your package, create a new directory fo r them within your project and select Add Library... instead. It is not necessar y to put external JARs in the assets folder. Implementing Activity Callbacks http://developer.android.com/guide/appendix/faq/commontasks.html Page 2 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 Android calls a number of callbacks to let you draw your screen, store data befo re pausing, and refresh data after closing. You must implement at least some of these methods. See Lifecycles discussion in Application Fundamentals to learn wh en and in what order these methods are called. Here are some of the standard typ es of screen classes that Android provides: android.app.Activity - This is a sta ndard screen, with no specialization. android.app.ListActivity - This is a scree n that is used to display a list of something. It hosts a ListView object, and e xposes methods to let you identify the selected item, receive callbacks when the selected item changes, and perform other list-related actions. android.app.Dial og - This is a small, popup dialog-style window that isn't intended to remain in the history stack. (It is not resizeable or moveable by the user.) Opening a New Screen Your Activity will often need to open another Activity screen as it progresses. This new screen can be part of the same application or part of another applicati on, the new screen can be floating or full screen, it can return a result, and y ou can decide whether to close this screen and remove it from the history stack when you are done with it, or to keep the screen open in history. These next sec tions describe all these options. Floating or full? When you open a new screen you can decide whether to make it transparent or floa ting, or full-screen. The choice of new screen affects the event sequence of eve nts in the old screen (if the new screen obscures the old screen, a different se ries of events is called in the old screen). See Lifecycles discussion in Applic ation Fundamentals for details. Transparent or floating windows are implemented in three standard ways: Create an app.Dialog class Create an app.AlertDialog cla ss Set the Theme_Dialog theme attribute to @android:style/Theme.Dialog in your A ndroidManifest.xml file. For example: <activity class="AddRssItem" android:label ="Add an item" android:theme="@android:style/Theme.Dialog"/> Calling startActivi ty() or startActivityForResult() will open a new screen in whatever way it defin es itself (if it uses a floating theme it will be floating, otherwise it will be full screen). Opening a Screen When you want to open a new screen, you can either explicitly specify the activi ty class to open, or you can let the operating system decide which screen to ope n, based upon the data and various parameters you pass in. A screen is opened by calling startActivity and passing in an Intent object, which specifies the crit eria for the handling screen. To specify a specific screen, call Intent.setClass or setClassName with the exact activity class to open. Otherwise, set a variety of values and data, and let Android decide which screen is appropriate to open. Android will find one or zero http://developer.android.com/guide/appendix/faq/commontasks.html Page 3 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 let Android decide which screen is appropriate to open. Android will find one or zero Activities that match the specified requirements; it will never open multi ple activities for a single request. More information on Intents and how Android resolves them to a specific class is given in the Intent topic. Some Intent examples The following snippet loads the com.android.samples.Animation1 class, and passes it some arbitrary data.: Intent myIntent = new Intent(); myIntent.setClassName( "com.android.samples", "com.android.samples.Animation1"); myIntent.putExtra("com .android.samples.SpecialValue", "Hello, Joe!"); // key/value pair, where key nee ds current package prefix. startActivity(myIntent); The next snippet requests th at a Web page be opened by specifying the VIEW action, and a URI data string sta rting with "http://" schema: Intent myIntent = new Intent(Intent.VIEW_ACTION, Ur i.parse("http://www.google.com")); Here is the intent filter from the AndroidMan ifest.xml file for com.android.browser: <intent-filter> <action android:name="an droid.intent.action.VIEW" /> <category android:name="android.intent.category.DEF AULT" /> <scheme android:name="http" /> <scheme android:name="https" /> <scheme android:name="file" /> </intent-filter> Android defines a number of standard val ues, for instance the action constants defined by Intent. You can define custom values, but both the caller and handler must use them. See the <intent-filter> t ag description in The AndroidManifest.xml File for more information on the manif est syntax for the handling application. Returning a Result from a Screen A window can return a result after it closes. This result will be passed back in to the calling Activity's onActivityResult() method, which can supply an Intent containing arbitrary data, along with the request code passed to startActivityFo rResult(). Note that you must call the startActivityForResult() method that acce pts a request code parameter to get this callback. The following code demonstrat es opening a new screen and retrieving a result. // Open the new screen. public void onClick(View v){ // Start the activity whose result we want to retrieve. Th e // result will come back with request code GET_CODE. Intent intent = new Inten t(this, com.example.app.ChooseYourBoxer.class); startActivityForResult(intent, C HOOSE_FIGHTER); } // Listen for results. protected void onActivityResult(int req uestCode, int resultCode, Intent data){ // See which child activity is calling u s back. switch (resultCode) { case CHOOSE_FIGHTER: http://developer.android.com/guide/appendix/faq/commontasks.html Page 4 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 } } case CHOOSE_FIGHTER: // This is the standard resultCode that is sent back if the // activity crashed or didn't doesn't supply an explicit result. if (resultCode == RESULT_CANCELED){ myMessageboxFunction("Fight cancelled"); } else { myFightF unction(data); } default: break; // Class SentResult // Temporary screen to let the user choose something. privat e OnClickListener mLincolnListener = new OnClickListener(){ public void onClick( View v) { Bundle stats = new Bundle(); stats.putString("height","6\'4\""); stats .putString("weight", "190 lbs"); stats.putString("reach", "74\""); setResult(RES ULT_OK, "Lincoln", stats); finish(); } }; private OnClickListener mWashingtonLis tener = new OnClickListener() { public void onClick(View v){ Bundle stats = new Bundle(); stats.putString("height","6\'2\""); stats.putString("weight", "190 lbs "); stats.putString("reach", "73\""); setResult(RESULT_OK, "Washington", Bundle) ; finish(); } }; Lifetime of the new screen An activity can remove itself from the history stack by calling Activity.finish( ) on itself, or the activity that opened the screen can call Activity.finishActi vity() on any screens that it opens to close them. Listening for Button Clicks Button click and other UI event capturing are covered in Handling UI Events on t he UI Design page. Configuring General Window Properties You can set a number of general window properties, such as whether to display a title, whether the window is floating, and whether it displays an icon, by calli ng methods on the Window member of the underlying View object for the window. Ex amples include calling getWindow().requestFeature() (or the convenience method r equestWindowFeature(some_feature)) to hide the title. Here is an example of hidi ng the title bar: //Hide the title bar requestWindowFeature(Window.FEATURE_NO_TI TLE); http://developer.android.com/guide/appendix/faq/commontasks.html Page 5 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 Referring to localhost from the emulated environment If you need to refer to your emulator client to contact a refer to the host comp uter's localhost (127.0.0.1) refers host computer's localhost, such as when you want the server running on the same host, use the alias 10.0.2.2 to loopback int erface. From the emulator's perspective, to its own loopback interface. Storing and Retrieving State If your application is dumped from memory because of space concerns, it will los e all user interface state information such as checkbox state and text box value s as well as class member values. Android calls Activity.onSaveInstanceState bef ore it pauses the application. This method hands in a Bundle that can be used to store name/value pairs that will persist and be handed back to the application even if it is dropped from memory. Android will pass this Bundle back to you whe n it calls onCreate(). This Bundle only exists while the application is still in the history stack (whether or not it has been removed from memory) and will be lost when the application is finalized. See the topics for onSaveInstanceState(B undle) and onCreate(Bundle) for examples of storing and retrieving state. Read m ore about the lifecycle of an application in Application Fundamentals. Storing and Retrieving Larger or More Complex Persistent Data Your application can store files or complex collection objects, and reserve them for private use by itself or other activities in the application, or it can exp ose its data to all other applications on the device. See Storing, Retrieving, a nd Exposing Data to learn how to store and retrieve private data, how to store a nd retrieve common data from the device, and how to expose your private data to other applications. Playing Media Files Please see the document Audio and Video for more details. Listening For and Broadcasting Global Messages, and Setting Alarms You can create a listening class that can be notified or even instantiated whene ver a specific type of system message is sent. The listening classes, called bro adcast receivers, extend BroadcastReceiver. If you want Android to instantiate t he object whenever an appropriate intent notification is sent, define the receiv er with a <receiver> element in the AndroidManifext.xml file. If the caller is e xpected to instantiate the object in preparation to receive a message, this is n ot required. The receiver will get a call to their BroadcastReceiver.onReceive() method. A receiver can define an <intent-filter> tag that describes the types o f messages it will receive. Just as Android's IntentResolver will look for appro priate Activity matches for a startActivity() call, it will look for any matchin g Receivers (but it will send the message to all matching receivers, not to the "best" match). http://developer.android.com/guide/appendix/faq/commontasks.html Page 6 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 To send a notification, the caller creates an Intent object and calls Context.se ndBroadcast() with that Intent. Multiple recipients can receive the same message . You can broadcast an Intent message to an intent receiver in any application, not only your own. If the receiving class is not registered using <receiver> in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver(). Receivers can include intent filters to specify wha t kinds of intents they are listening for. Alternatively, if you expect a single known caller to contact a single known receiver, the receiver does not specify an intent filter, and the caller specifies the receiver's class name in the Inte nt by calling Intent.setClassName() with the recipient's class name. The recipie nt receives a Context object that refers to its own package, not to the package of the sender. Note: If a receiver or broadcaster enforces permissions, your app lication might need to request permission to send or receive messages from that object. You can request permission by using the <uses-permission> tag in the man ifest. Here is a code snippet of a sender and receiver. This example does not de monstrate registering receivers dynamically. For a full code example, see the Al armService class in the ApiDemos project. Sending the message // We are sending this to a specific recipient, so we will // only specify the r ecipient class name. Intent intent = new Intent(this, AlarmReceiver.class); inte nt.putExtra("message","Wake up."); sendBroadcast(intent); Receiving the message Receiver AndroidManifest.xml (because there is no intent filter child, this clas s will only receive a broadcast when the receiver class is specified by name, as is done in this example): <receiver class=".AlarmReceiver" /> Receiver Java cod e: public class AlarmReceiver extends BroadcastReceiver{ // Display an alert tha t we've received a message. @Override public void onReceive(Context context, Int ent intent){ // Send a text notification to the screen. NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); n m.notifyWithText(R.id.alarm, "Alarm!!!", NotificationManager.LENGTH_SHORT, null) ; } } Other system messages You can listen for other system messages sent by Android as well, such as USB co nnection/removal messages, SMS arrival messages, and timezone changes. See Inten t for a list of broadcast messages to listen for. Messages are marked "Broadcast Action" in http://developer.android.com/guide/appendix/faq/commontasks.html Page 7 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 a list of broadcast messages to listen for. Messages are marked "Broadcast Actio n" in the documentation. Listening for phone events The android.telephony package overview page describes how to register to listen for phone events. Setting Alarms Android provides an AlarmManager service that will let you specify an Intent to send at a designated time. This intent is typically used to start an application at a preset time. (Note: If you want to send a notification to a sleeping or ru nning application, use Handler instead.) Displaying Alerts There are two major kinds of alerts that you may display to the user: (1) Normal alerts are displayed in response to a user action, such as trying to perform an action that is not allowed. (2) Out-of-band alerts, called notifications, are d isplayed as a result of something happening in the background, such as the user receiving new e-mail. Normal Alerts Android provides a number of ways for you to show popup notifications to your us er as they interact with your application. Class app.Dialog app.AlertDialog Desc ription A generic floating dialog box with a layout that you design. A popup ale rt dialog with two buttons (typically OK and Cancel) that take callback handlers . See the section after this table for more details. A dialog box used to indica te progress of an operation with a known progress value or an indeterminate leng th (setProgress(bool)). See Views > Progress Bar in ApiDemos for examples. By se tting the theme of an activity to android:theme="android:style/Theme.Dialog", yo ur activity will take on the appearance of a normal dialog, floating on top of w hatever was underneath it. You usually set the theme through the android:theme a ttribute in your AndroidManifest.xml. The advantage of this over Dialog and Aler tDialog is that Application has a much better managed life cycle than dialogs: i f a dialog goes to the background and is killed, you cannot recapture state, whe reas Application exposes a Bundle of saved values in onCreate() to help you main tain state. ProgressDialog Activity AlertDialog This is a basic warning dialog box that lets you configure a message, button tex t, and callback. You can create one by calling using the AlertDialog.Builder cla ss, as shown here. private Handler mHandler = new Handler() { public void handle Message(Message msg) { http://developer.android.com/guide/appendix/faq/commontasks.html Page 8 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 public void handleMessage(Message msg) { switch (msg.what) { case ACCEPT_CALL: a nswer(msg.obj); break; case BOUNCE_TO_VOICEMAIL: voicemail(msg.obj); break; } } }; private void IncomingMotherInlawCall(Connection c) { String Text; // "Answer" ca llback. Message acceptMsg = Message.obtain(); acceptMsg.target = mHandler; accep tMsg.what = ACCEPT_CALL; acceptMsg.obj = c.getCall(); // "Cancel" callback. fina l Message rejectMsg = Message.obtain(); rejectMsg.target = mHandler; rejectMsg.w hat = BOUNCE_TO_VOICEMAIL; rejectMsg.obj = c.getCall(); new AlertDialog.Builder( this) .setMessage("Phyllis is calling") .setPositiveButton("Answer", acceptMsg) .setOnCanceListener(new OnCancelListener() { public void onCancel(DialogInterfac e dialog) { rejectMsg.sendToTarget(); }}); .show(); } Notifications Out-of-band alerts should always be displayed using the NotificationManager, whi ch allows you to tell the user about something they may be interested in without disrupting what they are currently doing. A notification can be anything from a brief pop-up box informing the user of the new information, through displaying a persistent icon in the status bar, to vibrating, playing sounds, or flashing l ights to get the user's attention. In all cases, the user must explicitly shift their focus to the notification before they can interact with it. The following code demonstrates using NotificationManager to display a basic text popup when a new SMS message arrives in a listening service, and provides the current messag e count. You can see several more examples in the ApiDemos application, under ap p/ (named notification*.java). static void setNewMessageIndicator(Context contex t, int messageCount){ // Get the static global NotificationManager object. Notif icationManager nm = NotificationManager.getDefault(); // // // if If we're being called because a new message has been received, then display an i con and a count. Otherwise, delete the persistent message. (messageCount > 0) { nm.notifyWithText(myApp.NOTIFICATION_GUID, // ID for this notification. Page 9 of 15 http://developer.android.com/guide/appendix/faq/commontasks.html

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 nm.notifyWithText(myApp.NOTIFICATION_GUID, // ID for this notification. messageC ount + " new message" + messageCount > 1 ? "s":"", // Text to display. Notificat ionManager.LENGTH_SHORT); // Show it for a short time only. } } To display a not ification in the status bar and have it launch an intent when the user selects i t (such as the new text message notification does), call NotificationManager.not ify(), and pass in vibration patterns, status bar icons, or Intents to associate with the notification. Displaying a Progress Bar An activity can display a progress bar to notify the user that something is happ ening. To display a progress bar in a screen, call Activity.requestWindowFeature (Window.FEATURE_PROGRESS). To set the value of the progress bar, call Activity.g etWindow().setFeatureInt(Window.FEATURE_PROGRESS, level). Progress bar values ar e from 0 to 9,999, or set the value to 10,000 to make the progress bar invisible . You can also use the ProgressDialog class, which enables a dialog box with an embedded progress bar to send a "I'm working on it" notification to the user. Adding Items to the Screen Menu See Creating Menus. Display a Web Page Use the webkit.WebView object. Binding to Data You can bind a ListView to a set of underlying data by using a shim class called ListAdapter (or a subclass). ListAdapter subclasses bind to a variety of data s ources, and expose a common set of methods such as getItem() and getView(), and uses them to pick View items to display in its list. You can extend ListAdapter and override getView() to create your own custom list items. There are essential ly only two steps you need to perform to bind to data: 1. Create a ListAdapter o bject and specify its data source 2. Give the ListAdapter to your ListView objec t. That's it! Here's an example of binding a ListActivity screen to the results from a cursor query. (Note that the setListAdapter() method shown is a convenien ce method that gets the page's ListView object and calls setAdapter() on it.) // Run a query and get a Cursor pointing to the results. Cursor c = People.query(t his.getContentResolver(), null); http://developer.android.com/guide/appendix/faq/commontasks.html Page 10 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 Cursor c = People.query(this.getContentResolver(), null); startManagingCursor(c) ; // Create the ListAdapter. A SimpleCursorAdapter lets you specify two interest ing things: // an XML template for your list item, and // The column to map to a specific item, by ID, in your template. ListAdapter adapter = new SimpleCursorA dapter(this, android.R.layout.simple_list_item_1, // Use a template that display s a text view c, // Give the cursor to the list adapter new String[] {People.NAM E} , // Map the NAME column in the people database to... new String[] {"text1"}) ; // The "text1" view defined in the XML template setListAdapter(adapter); See v iew/List4 in the ApiDemos project for an example of extending ListAdapter for a new data type. Getting a Handle to a Screen Element You can get a handle to a screen element by calling Activity.findViewById. You c an then use the handle to set or retrieve any values exposed by the object. Capture Images from the Phone Camera You can hook into the device's camera onto your own Canvas object by using the C amera class. See that class's documentation, and the ApiDemos project's Camera P review application (Graphics/Camera Preview) for example code. Handling Expensive Operations in the UI Thread Avoid performing long-running operations (such as network I/O) directly in the U I thread the main thread of an application where the UI is run or your applicati on may be blocked and become unresponsive. Here is a brief summary of the recomm ended approach for handling expensive operations: 1. Create a Handler object in your UI thread 2. Spawn off worker threads to perform any required expensive ope rations 3. Post results from a worker thread back to the UI thread's handler eit her through a Runnable or a Message 4. Update the views on the UI thread as need ed The following outline illustrates a typical implementation: public class MyAc tivity extends Activity { [ . . . ] // Need handler for callbacks to the UI thre ad final Handler mHandler = new Handler(); // Create runnable for posting final Runnable mUpdateResults = new Runnable() { public void run() { updateResultsInUi (); http://developer.android.com/guide/appendix/faq/commontasks.html Page 11 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 updateResultsInUi(); }; @Override protected void onCreate(Bundle savedInstanceSt ate) { super.onCreate(savedInstanceState); } protected void startLongRunningOper ation() { // Fire off a thread to do some work that we shouldn't do directly in the UI thread Thread t = new Thread() { public void run() { mResults = doSomethi ngExpensive(); mHandler.post(mUpdateResults); } }; t.start(); } private void upd ateResultsInUi() { // Back in the UI thread -- update our UI elements based on t he data in mResults [ . . . ] } For further discussions on this topic, see Desig ning for Responsiveness and the Handler documentation. } [ . . . ] } Selecting, Highlighting, or Styling Portions of Text You can highlight or style the formatting of strings or substrings of text in a TextView object. There are two ways to do this: If you use a string resource, yo u can add some simple styling, such as bold or italic using HTML notation. The c urrently supported tags are: B (bold), I (italic), U (underline), TT (monospace) , BIG, SMALL, SUP (superscript), SUB (subscript), and STRIKE (strikethrough). So , for example, in res/values/strings.xml you could declare this: <resource> <str ing>id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</s tring> </resources> To style text on the fly, or to add highlighting or more com plex styling, you must use the Spannable object as described next. To style text on the fly, you must make sure the TextView is using Spannable storage for the text (this will always be true if the TextView is an EditText), retrieve its tex t with getText(), and call setSpan(Object, int, int, int), passing in a new styl e class from the android.text.style package and the selection range. The followi ng code snippet demonstrates creating a string with a highlighted section, itali c section, and bold section, and adding it to an EditText object. // Get our Edi tText object. http://developer.android.com/guide/appendix/faq/commontasks.html Page 12 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 // Get our EditText object. EditText vw = (EditText)findViewById(R.id.text); // Set the EditText's text. vw.setText("Italic, highlighted, bold."); // // // // I f this were just a TextView, we could do: vw.setText("Italic, highlighted, bold. ", TextView.BufferType.SPANNABLE); to force it to use Spannable storage so style s can be attached. Or we could specify that in the XML. // Get the EditText's internal text storage Spannable str = vw.getText(); // Cre ate our span sections, and assign a format to each. str.setSpan(new StyleSpan(an droid.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str. setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXC LUSIVE); str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.leng th() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); Utilizing attributes in a Map query When using a search intent to ask the Maps activity to search for something, the Maps activity responds to the following attributes in the optional context bund le: float "centerLatitude" default 0.0f float "centerLongitude" default 0.0f flo at "latitudeSpan" default 0.0f float "longitudeSpan" default 0.0f int "zoomLevel " default 10 This context information is used to center the search result in a p articular area, and is equivalent to adjusting the Map activity to the described location and zoom level before issuing the query. If the latitudeSpan, longitud eSpan, and zoomLevel attributes are not consistent, then it is undefined which o ne takes precedence. List of Files for an Android Application The following list describes the structure and files of an Android application. Many of these files can be built for you (or stubbed out) by the android tool sh ipped in the tools/ menu of the SDK. MyApp/ AndroidManifest.xml (required) Adver tises the screens that this application provides, where they can be launched (fr om the main program menu or elsewhere), any content providers it implements and what kind of data they handle, where the implementation classes are, and other a pplication-wide information. Syntax details for this file are described in The A ndroidManifest.xml File. (required) This folder holds all the Page 13 of 15 src/ http://developer.android.com/guide/appendix/faq/commontasks.html

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 src/ /myPackagePath/.../MyClass.java (required) This folder holds all the source code files for your application, ins ide the appropriate package subfolders. (required) This folder holds all the res ources for your application. Resources are external data files or description fi les that are compiled into your code at build time. Files in different folders a re compiled differently, so you must put the proper resource into the proper fol der. (See Resources for details.) res/ anim/ animation1.xml ... (optional) Holds any animation XML description files that the application uses. The format of these files is described in Resources. (optional) Zero or more fil es that will be compiled to android.graphics.drawable resources. Files can be im age files (png, gif, or other) or XML files describing other graphics such as bi tmaps, stretchable bitmaps, or gradients. Supported bitmap file formats are PNG (preferred), JPG, and GIF (discouraged), as well as the custom 9-patch stretchab le bitmap format. These formats are described in Resources. (optional) Holds all the XML files describing screens or parts of screens. Although you could create a screen in Java, defining them in XML files is typically easier. A layout file is similar in concept to an HTML file that describes the screen layout and comp onents. See User Interface for more information about designing screens, and Ava ilable Resource Types for the syntax of these files. (optional) XML files descri bing additional resources such as strings, colors, and styles. The naming, quant ity, and number of these files are not enforced--any XML file is compiled, but t hese are the standard names given to these files. However, the syntax of these f iles is prescribed by Android, and described in Resources. (optional) XML files that can be read at run time on the device. (optional) Any files to be copied di rectly to the device. drawable/ some_picture.png some_stretchable.9.png some_background.xml ... layout/ screen_1_layout.xml ... values/ arrays classes.xml colors.xml dimens.xml strings.xml styles.xml values.x ml xml/ raw/ Print Messages to a Log File http://developer.android.com/guide/appendix/faq/commontasks.html Page 14 of 15

Common Tasks and How to Do Them in Android | Android Developers 29.04.09 1:02 To write log messages from your application: 1. Import android.util.Log. 2. Use Log.v(), Log.d(), Log.i(), Log.w(), or Log.e() to log messages. (See the Log cla ss.) E.g., Log.e(this.toString(), "error: " + err.toString()) 3. Launch DDMS fro m a terminal by executing ddms in your Android SDK /tools path. 4. Run your appl ication in the Android emulator. 5. From the DDMS application, select the emulat or (e.g., "emulator-5554") and click Device > Run logcat... to view all the log data. Note: If you are running Eclipse and encounter a warning about the VM debu g port when opening DDMS, you can ignore it if you're only interested in logs. H owever, if you want to further inspect and control your processes from DDMS, the n you should close Eclipse before launching DDMS so that it may use the VM debug ging port. " Back to FAQs, Tips, and How-to ! Go to top Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines http://developer.android.com/guide/appendix/faq/commontasks.html Page 15 of 15

Android Application Framework FAQ | Android Developers 29.04.09 1:02 FAQs, Tips, and How-to > Android Application Framework FAQ Do all the Activities and Services of an application run in a single process? Do all Activities run in the main thread of an application process? How do I pass complicated data structures from one Activity/Service to another? How can I chec k if an Activity is already running before starting it? If an Activity starts a remote service, is there any way for the Service to pass a message back to the A ctivity? How to avoid getting the Application not responding dialog? How does an application know if a package is added or removed? Do all the Activities and Services of an application run in a single process? All Activities and Services in an application run in a single process by default . If needed, you can declare an android:process attribute in your manifest file, to explicitly place a component (Activity/Service) in another process. Do all Activities run in the main thread of an application process? By default, all of the application code in a single process runs in the main UI thread. This is the same thread that also handles UI events. The only exception is the code that handles IPC calls coming in from other processes. The system ma intains a separate pool of transaction threads in each process to dispatch all i ncoming IPC calls. The developer should create separate threads for any long-run ning code, to avoid blocking the main UI thread. How do I pass data between Activities/Services within a single application? It depends on the type of data that you want to share: Primitive Data Types To share primitive data between Activities/Services in an application, use Inten t.putExtras(). For passing primitive data that needs to persist use the Preferen ces storage mechanism. Non-Persistent Objects For sharing complex non-persistent user-defined objects for short duration, the following approaches are recommended: The android.app.Application class The android.app.Application is a base class for those who need to maintain globa l application state. It can be accessed via getApplication() from any Activity o r Service. It has a couple of life-cycle methods and will be instantiated by And roid automatically if your register it in AndroidManifest.xml. A public static field/method http://developer.android.com/guide/appendix/faq/framework.html Page 1 of 3

Android Application Framework FAQ | Android Developers 29.04.09 1:02 An alternate way to make data accessible across Activities/Services is to use pu blic static fields and/or methods. You can access these static fields from any o ther class in your application. To share an object, the activity which creates y our object sets a static field to point to this object and any other activity th at wants to use this object just accesses this static field. A HashMap of WeakReferences to Objects You can also use a HashMap of WeakReferences to Objects with Long keys. When an activity wants to pass an object to another activity, it simply puts the object in the map and sends the key (which is a unique Long based on a counter or time stamp) to the recipient activity via intent extras. The recipient activity retri eves the object using this key. A Singleton class There are advantages to using a static Singleton, such as you can refer to them without casting getApplication() to an application-specific class, or going to t he trouble of hanging an interface on all your Application subclasses so that yo ur various modules can refer to that interface instead. But, the life cycle of a static is not well under your control; so to abide by the life-cycle model, the application class should initiate and tear down these static objects in the onC reate() and onTerminate() methods of the Application Class Persistent Objects Even while an application appears to continue running, the system may choose to kill its process and restart it later. If you have data that you need to persist from one activity invocation to the next, you need to represent that data as st ate that gets saved by an activity when it is informed that it might go away. Fo r sharing complex persistent user-defined objects, the following approaches are recommended: Application Preferences Files contentProviders SQLite DB If the sha red data needs to be retained across points where the application process can be killed, then place that data in persistent storage like Application Preferences , SQLite DB, Files or ContentProviders. Please refer to the Data Storage for fur ther details on how to use these components. How can I check if an Activity is already running before starting it? The general mechanism to start a new activity if its not running or to bring the activity stack to the front if is already running in the background is the to use the NEW_TASK_LAUNCH flag in the startActivity() call. If an Activity starts a remote service, is there any way for the Service to pass a message back to the Activity? The remote service can define a callback interface and register it with the clie nts to callback into the clients. The RemoteCallbackList class provides methods to register and unregister clients with the service, and send and receive messag es. The sample code for remote service callbacks is given in ApiDemos/RemoteServ ice How to avoid getting the Application not responding dialog? http://developer.android.com/guide/appendix/faq/framework.html Page 2 of 3

Android Application Framework FAQ | Android Developers 29.04.09 1:02 Please read the Designing for Responsiveness document. How does an application know if a package is added or removed? Whenever a package is added, an intent with PACKAGE_ADDED action is broadcast by the system. Similarly when a package is removed, an intent with PACKAGE_REMOVED action is broadcast. To receive these intents, you should write something like this: <receiver android:name ="com.android.samples.app.PackageReceiver"> <intent -filter> <action android:name="android.intent.action.PACKAGE_ADDED"/> <action an droid:name="android.intent.action.PACKAGE_REMOVED"/> <data android:scheme="packa ge" /> </intent-filter> </receiver> Here PackageReceiver is a BroadcastReceiver class.Its onReceive() method is invo ked, every time an application package is installed or removed. " Back to FAQs, Tips, and How-to Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/faq/framework.html Page 3 of 3

Troubleshooting | Android Developers 29.04.09 1:02 FAQs, Tips, and How-to > Troubleshooting Here are some tips and tricks for common Android errors. Don't forget to use the ddms logcat capability to get a deeper view when errors occur. See Debugging fo r more debugging tips. ADT Installation Error: "requires plug-in org.eclipse.wst .sse.ui". ADB reports "no device" when an emulator is running My new application /activity isn't showing up in the device application list I updated my app, but the updates don't seem to be showing up on the device I'm getting a "Binary XML file line #2: You must supply a layout_wilih attribute" error when I start an ap plication My request to (make a call, catch an incoming SMS, receive a notificat ion, send an intent to an Android application) is being ignored Help! My project won't build in Eclipse Eclipse isn't talking to the emulator When I go to prefe rences in Eclipse and select "Android", I get the following error message: Unsup ported major.minor version 49.0. I can't install ApiDemos apps in my IDE because of a signing error I can't compile my app because the build tools generated an expired debug certificate ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui". The "Android Editors" feature of the ADT Plugin requires specific Eclipse compon ents, such as WST. If you encounter this error message during ADT installation, you need to install the required Eclipse components and then try the ADT install ation again. Follow the steps below to install the required components for the A ndroid Editors feature, based on the version of Eclipse that you are using. Ecli pse 3.3 (Europa) 1. From the dialog where you select the Update sites to visit, select the checkboxes for both the ADT site, and the Callisto/Europa/Ganymede Di scovery Site (you may want to check Automatically select mirrors at the bottom). 2. Click Finish. 3. In the Next dialog, select the Android Plugins. 4. Now, exp and the tree item of the discovery site. It seems that if you don't do it, it do esn't load the content of the discovery site. 5. On the right, click Select requ ired. This will select all the components that are required to install the Andro id plugin (wst, emf, etc...). 6. Click Next, accept the agreement, click Install All, and restart Eclipse. http://developer.android.com/guide/appendix/faq/troubleshooting.html Page 1 of 5 Eclipse 3.4 (Ganymede) 1. Select Help > Software Updates... 2. Select the Instal led Software tab. 3. Click Update... 4. If an update for ADT is available, selec t it and click Finish.

Troubleshooting | Android Developers 29.04.09 1:02 All, and restart Eclipse. ADB reports "no device" when an emulator is running Try restarting adb by stopping it (adb kill-server) then any other adb command t o restart it. My new application/activity isn't showing up in the applications list You often must restart your device or emulator before a new activity shows up in the applications list. This is particularly true when it is a completely new ap plication with a new AndroidManifest.xml file. If this is for a new activity in an existing AndroidManifest.xml file, did you include an <activity> tag for your app (or a <service> tag for a service, or a <receiver> tag for a receiver, etc. )? Make sure that your AndroidManifest.xml file is valid. Errors in attribute va lues, such as the value attribute in <action value="<something>"> will often not be caught by compilers, but will prevent your application from being displayed because the intent filter will not be matched. Extra spaces or other characters can often sneak into these strings. Did you send your .apk file to the device (a db install)? Run logcat on your device (adb logcat) and then install your .apk f ile. Check the logcat output to see whether the application is being installed a nd recognized properly. Here's sample output from a successful installation: I/F ileObserver( 414): *** onEvent wfd: 3 mask: 8 path: MyRSSReader.apk D/PackageMan ager( 414): Scanning package: /data/app/MyRSSReader.apk D/PackageManager( 414): Adding package com.example.codelab.rssexample D/PackageManager( 414): Registered content provider: my_rss_item, className = com.example.codelab.rssexample.RssCo ntentProvider, isSyncable = false D/PackageManager( 414): Providers: com.example .codelab.rssexample.RssContentProvider D/PackageManager( 414): Activities: com.e xample.codelab.rssexample.MyRssReader com.example.codelab.rssexample.MyRssReader 2 If logcat shows that the package manager is having problems loading the manife st file, force your manifest to be recompiled by adding a space in the file and compiling it. I updated my app, but the updates don't seem to be showing up on the device Did you remember to send your .apk file to the device (adb install)? I'm getting a "Binary XML file line #2: You must supply a layout_wilih attribute " error when I start an application (but I declare a layout_wilih attribute righ t there!!!) Make sure that the SDK you are building with is the same version as the Android OS that you are running on. Make sure that you're calling setContentView() early in your onCreate() method. Calling other methods, such as setListAdapter() befo re calling setContentView() can sometimes create odd errors when Android tries t o access screen elements that haven't been set before. http://developer.android.com/guide/appendix/faq/troubleshooting.html Page 2 of 5

Troubleshooting | Android Developers 29.04.09 1:02 My request to (make a call, catch an incoming SMS, receive a notification, send an intent to an Android application) is being ignored You might not have permission (or might not have requested permission) to call t his activity or receive this intent. Many standard Android activities, such as m aking a call, have a permission assigned to it to prevent arbitrary applications from sending or receiving requests. See Security and Permissions for more infor mation on permissions, and Manifest.permission for a list of standard permission s supported by the Android platform. Help! My project won't build in Eclipse If your project doesn't build, you may notice symptoms such as new resources add ed in the res/ sub-folders not showing up in the R class, the emulator not being started, not being able to run the application, or even seeming to run an old v ersion of the application. To troubleshoot these types of problems, first try: 1 . Switch to the DDMS view in Eclipse (if you don't already have it open): a. Fro m the menu select Window > Open Perspective > Other b. Select DDMS from the list and hit OK 2. In the Devices panel (top right panel by default), click on the d own triangle to bring up the panel menu 3. Select Reset ADB from the menu, and t hen try running the application again If the above still doesn't work, you can t ry these steps: 1. Check the console and problems tabs at the bottom of the Ecli pse UI 2. If there are problems listed in either place, they should give you a c lue what is wrong 3. If you aren't sure if the problems are fresh or stale, clea r the console with a right click > Clear, then clean the project 4. To clean the project (a good idea with any kind of build error), select Project > Clean from the eclipse main menu, then select the project you are working on (or clean all ) Eclipse isn't talking to the emulator When communication doesn't seem to be happening between Eclipse and the emulator , symptoms can include: nothing happening when you press run, the emulator hangi ng waiting for a debugger to connect, or errors that Eclipse reports about not b eing able to find the emulator or shell. By far the most common symptom is that when you press run, the emulator starts (or is already running), but the applica tion doesn't start. You may find any of these steps will fix the problem and wit h practice you probably can figure out which one you need to do for your particu lar issue, but to start with, the safest option is to run through all of them in order: 1. Quit the emulator if it is running 2. Check that any emulator process es are killed (sometimes they can hang, use ps on unix or mac, or task manager i n the process view on windows). 3. Quit Eclipse 4. From the command line, type: http://developer.android.com/guide/appendix/faq/troubleshooting.html Page 3 of 5

Troubleshooting | Android Developers 29.04.09 1:02 adb kill-server 5. Start Eclipse and try again When I go to preferences in Eclipse and select "Android", I get the following er ror message: Unsupported major.minor version 49.0. This error is displayed if you are using an older version of the JDK. Please mak e sure you are using JDK version 5 or 6. I can't install ApiDemos apps in my IDE because of a signing error The Android system requires that all applications be signed, as described in Sig ning Your Applications. The ApiDemos applications included with the SDK are prei nstalled on the emulator and for that reason have been compiled and signed with a private key. If you want to modify or run one of the ApiDemos apps from Eclips e/ADT or other IDE, you can do so so only after you uninstall the preinstalled v ersion of the app from the emulator. If you try to run an ApiDemos apps from you r IDE without removing the preinstalled version first, you will get errors simil ar to: [2008-08-13 15:14:15 - ApiDemos] Re-installation failed due to different application signatures. [2008-08-13 15:14:15 - ApiDemos] You must perform a full uninstall of the application. WARNING: ...This will remove the application data ! [2008-08-13 15:14:15 - ApiDemos] Please execute 'adb uninstall com.android.sam ples' in a shell. The error occurs because, in this case, you are attempting to install another copy of ApiDemos onto the emulator, a copy that is signed with a different certificate (the Android IDE tools will have signed the app with a de bug certificate, where the existing version was already signed with a private ce rtificate). The system does not allow this type of reinstallation. To resolve th e issue, you need to fully uninstall the preinstalled and then reinstall it usin g the adb tool. Here's how to do that: 1. In a terminal, change to the tools dir ectory of the SDK. 2. If no emulator instance is running, start an emulator usin g using the command emulator &. 3. Uninstall the preinstalled app using the comm and adb uninstall com.android.samples. 4. Reinstall the app using the command ad b install <path to the ApiDemos.apk>. If you are working in Eclipse/ADT, you can just compile and run the app in the normal way. Note that if multiple emulator instances are running, you need to direct your uninstall/install commands to the emulator instance that you are targeting. To do that you can add the -s <serial Number> to the command, for example: adb -s emulator-5556 install For more infor mation about adb, see the Android Debug Bridge documentation. I can't compile my app because the build tools generated an expired debug certif icate http://developer.android.com/guide/appendix/faq/troubleshooting.html Page 4 of 5

Troubleshooting | Android Developers 29.04.09 1:02 certificate If your development machine uses a locale that has a non-Gregorian calendar, you may encounter problems when first trying to compile and run your application. S pecifically, you may find that the Android build tools won't compile your applic ation because the debug key is expired. The problem occurs because the Keytool u tility included in the JDK and used by the Android build tools fails to properly handle non-Gregorian locales and may create validity dates that are in the past . That is, it may generate a debug key that is already expired, which results in the compile error. If you encounter this problem, follow these steps to work ar ound it: 1. First, delete the debug keystore/key already generated by the Androi d build tools. Specifically, delete the debug.keystore file. On Linux/Mac OSX, t he file is stored in ~/.android. On Windows XP, the file is stored in C:\Documen ts and Settings\<user>\.android. On Windows Vista, the file is stored in C:\User s\<user>\.android 2. Next, you can either Temporarily change your development ma chine's locale (date and time) to one that uses a Gregorian calendar, for exampl e, United States. Once the locale is changed, use the Android build tools to com pile and install your app. The build tools will regenerate a new keystore and de bug key with valid dates. Once the new debug key is generated, you can reset you r development machine to the original locale. Alternatively, if you do not want to change your machine's locale settings, you can generate the keystore/key on a ny machine using the Gregorian calendar, then copy the debug.keystore file from that computer to the proper location on your development machine. This problem h as been verified on Windows and may apply to other platforms. For general inform ation about signing Android applications, see Signing Your Applications. " Back to FAQs, Tips, and How-to Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/faq/troubleshooting.html Page 5 of 5

Android Open Source Licensing FAQ | Android Developers 29.04.09 1:03 FAQs, Tips, and How-to > Android Open Source Licensing FAQ Where can I find the open source components of Android? When will we see more co de released under open source licenses? Why are you releasing the code under the Apache License instead of GPLv2? Where can I find the open source components of Android? The source code for the full Android stack is available from the Android Open So urce Project site. Other mirrored GPL and LGPL'd components are available at htt p://code.google.com/p/android/downloads/list. Notices for other licenses can be found within the SDK. Why are you releasing the code under the Apache License instead of GPLv2? One of the best explanations for the reasoning behind releasing code under Apach e2 can be found in a ArsTechnica article by Ryan Paul. " Back to FAQs, Tips, and How-to Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/faq/licensingandoss.html Page 1 of 1

Android Security FAQ | Android Developers 29.04.09 1:03 FAQs, Tips, and How-to > Android Security FAQ Is Android Secure? I think I found a security flaw. How do I report it? How can I stay informed of Android security announcements? How do I securely use my Andr oid phone? I think I found malicious software being distributed for Android. How can I help? How will Android-powered devices receive security fixes? Can I get a fix directly from the Android Platform Project? Is Android secure? The security and privacy of our users' data is of primary importance to the Andr oid Open Source Project. We are dedicated to building and maintaining one of the most secure mobile platforms available while still fulfilling our goal of openi ng the mobile device space to innovation and competition. The Android Platform p rovides a rich security model that allows developers to request the capabilities , or access, needed by their application and to define new capabilities that oth er applications can request. The Android user can choose to grant or deny an app lication's request for certain capabilities on the handset. We have made great e fforts to secure the Android platform, but it is inevitable that security bugs w ill be found in any system of this complexity. Therefore, the Android team works hard to find new bugs internally and responds quickly and professionally to vul nerability reports from external researchers. I think I found a security flaw. How do I report it? You can reach the Android security team at security@android.com. If you like, yo u can protect your message using our PGP key. We appreciate researchers practici ng responsible disclosure by emailing us with a detailed summary of the issue an d keeping the issue confidential while users are at risk. In return, we will mak e sure to keep the researcher informed of our progress in issuing a fix and will properly credit the reporter(s) when we announce the patch. We will always move swiftly to mitigate or fix an externally-reported flaw and will publicly announ ce the fix once patches are available to users. How can I stay informed of Android security announcements? An important part of sustainably securing a platform, such as, Android is keepin g the user and security community informed of bugs and fixes. We will publicly a nnounce security bugs when the fixes are available via postings to the android-s ecurity-announce group on Google Groups. You can subscribe to this group as you would a mailing list and view the archives here. http://developer.android.com/guide/appendix/faq/security.html Page 1 of 3

Android Security FAQ | Android Developers 29.04.09 1:03 For more general discussion of Android platform security, or how to use security features in your Android application, please subscribe to android-security-disc uss. How do I securely use my Android phone? As an open platform, Android allows users to load software from any developer on to a device. As with a home PC, the user must be aware of who is providing the s oftware they are downloading and must decide whether they want to grant the appl ication the capabilities it requests. This decision can be informed by the user' s judgment of the software developer's trustworthiness, and where the software c ame from. Despite the security protections in Android, it is important for users to only download and install software from developers they trust. More details on how Android users can make smart security decisions will be released when con sumer devices become available. I think I found malicious software being distributed for Android. How can I help ? Like any other open platform, it will be possible for unethical developers to cr eate malicious software, known as malware, for Android. If you think somebody is trying to spread malware, please let us know at security@android.com. Please in clude as much detail about the application as possible, with the location it is being distributed from and why you suspect it of being malicious software. The t erm malicious software is subjective, and we cannot make an exhaustive definitio n. Some examples of what the Android Security Team believes to be malicious soft ware is any application that: drains the device's battery very quickly; shows th e user unsolicited messages (especially messages urging the user to buy somethin g); resists (or attempts to resist) the user's effort to uninstall it; attempts to automatically spread itself to other devices; hides its files and/or processe s; discloses the user's private information to a third party, without the user's knowledge and consent; destroys the user's data (or the device itself) without the user's knowledge and consent; impersonates the user (such as by sending emai l or buying things from a web store) without the user's knowledge and consent; o r otherwise degrades the user's experience with the device. How will Android-powered devices receive security fixes? The manufacturer of each device is responsible for distributing software upgrade s for it, including security fixes. Many devices will update themselves automati cally with software downloaded "over the air", while some devices require the us er to upgrade them manually. When Android-powered devices are publicly available , this FAQ will provide links how Open Handset Alliance members release updates. Can I get a fix directly from the Android Platform Project? http://developer.android.com/guide/appendix/faq/security.html Page 2 of 3

Android Security FAQ | Android Developers 29.04.09 1:03 Android is a mobile platform that will be released as open source and available for free use by anybody. This means that there will be many Android-based produc ts available to consumers, and most of them will be created without the knowledg e or participation of the Android Open Source Project. Like the maintainers of o ther open source projects, we cannot build and release patches for the entire ec osystem of products using Android. Instead, we will work diligently to find and fix flaws as quickly as possible and to distribute those fixes to the manufactur ers of the products. In addition, We will add security fixes to the open source distribution of Android and publicly announce the changes on android-security-an nounce. If you are making an Android-powered device and would like to know how y ou can properly support your customers by keeping abreast of software updates, p lease contact us at info@openhandsetalliance.com. " Back to FAQs, Tips, and Howto Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/faq/security.html Page 3 of 3

Glossary | Android Developers 29.04.09 1:01 Glossary The list below defines some of the basic terminology of the Android platform. .a pk file Android application package file. Each Android application is compiled a nd packaged in a single file that includes all of the application's code (.dex f iles), resources, assets, and manifest file. The application package file can ha ve any name but must use the .apk extension. For example: myExampleAppname.apk. For convenience, an application package file is often referred to as an ".apk". Related: Application. .dex file Compiled Android application code file. Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zip ped into a single .apk file on the device. .dex files can be created by automati cally translating compiled applications written in the Java programming language . Action A description of something that an Intent sender wants done. An action is a string value assigned to an Intent. Action strings can be defined by Androi d or by a third-party developer. For example, android.intent.action.VIEW for a W eb URL, or com.example.rumbler.SHAKE_PHONE for a custom application to vibrate t he phone. Related: Intent. Activity A single screen in an application, with supp orting Java code, derived from the Activity class. Most commonly, an activity is visibly represented by a full screen window that can receive and handle UI even ts and perform complex tasks, because of the Window it uses to render its window . Though an Activity is typically full screen, it can also be floating or transp arent. adb Android Debug Bridge, a command-line debugging application included w ith the SDK. It provides tools to browse the device, copy tools on the device, a nd forward ports for debugging. If you are developing in Eclipse using the ADT P lugin, adb is integrated into your development environment. See Android Debug Br idge for more information. Application From a component perspective, an Android application consists of one or more activities, services, listeners, and intent receivers. From a source file perspective, an Android application consists of co de, resources, assets, and a single manifest. During compilation, these files ar e packaged in a single file called an application package file (.apk). Related: .apk, Activity Canvas A drawing surface that handles compositing of the actual b its against a Bitmap or Surface object. It has methods for standard computer dra wing of bitmaps, lines, circles, rectangles, text, and so on, and is bound to a Bitmap or Surface. Canvas is the simplest, easiest way to draw 2D objects on the screen. However, it does not support hardware acceleration, as OpenGL ES does. The base class is Canvas. http://developer.android.com/guide/appendix/glossary.html Page 1 of 4

Glossary | Android Developers 29.04.09 1:01 Related: Drawable, OpenGL ES. Content Provider A data-abstraction layer that you can use to safely expose your application's data to other applications. A conte nt provider is built on the ContentProvider class, which handles content query s trings of a specific format to return data in a specific format. See Content Pro viders topic for more information. Related: URI Usage in Android Dalvik The Andr oid platform's virtual machine. The Dalvik VM is an interpreter-only virtual mac hine that executes files in the Dalvik Executable (.dex) format, a format that i s optimized for efficient storage and memory-mappable execution. The virtual mac hine is register-based, and it can run classes compiled by a Java language compi ler that have been transformed into its native format using the included "dx" to ol. The VM runs on top of Posixcompliant operating systems, which it relies on f or underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development bas e for those used to programming with Java Standard Edition, but it is geared spe cifically to the needs of a small mobile device. DDMS Dalvik Debug Monitor Servi ce, a GUI debugging application included with the SDK. It provides screen captur e, log dump, and process examination capabilities. If you are developing in Ecli pse using the ADT Plugin, DDMS is integrated into your development environment. See Dalvik Debug Monitor Server to learn more about the program. Dialog A floati ng window that that acts as a lightweight form. A dialog can have button control s only and is intended to perform a simple action (such as button choice) and pe rhaps return a value. A dialog is not intended to persist in the history stack, contain complex layout, or perform complex actions. Android provides a default s imple dialog for you with optional buttons, though you can define your own dialo g layout. The base class for dialogs is Dialog. Related: Activity. Drawable A co mpiled visual resource that can be used as a background, title, or other part of the screen. A drawable is typically loaded into another UI element, for example as a background image. A drawable is not able to receive events, but does assig n various other properties such as "state" and scheduling, to enable subclasses such as animation objects or image libraries. Many drawable objects are loaded f rom drawable resource files xml or bitmap files that describe the image. Drawabl e resources are compiled into subclasses of android.graphics.drawable. For more information about drawables and other resources, see Resources. Related: Resourc es, Canvas Intent An message object that you can use to launch or communicate wi th other applications/activities asynchronously. An Intent object is an instance of Intent. It includes several criteria fields that you can supply, to determin e what application/activity receives the Intent and what the receiver does when handling the Intent. Available criteria include include the desired action, a ca tegory, a data string, the MIME type of the data, a handling class, and others. An application sends an Intent to the Android system, rather than sending it dir ectly to another application/activity. The application can send the Intent to a single target application or it can send it as a broadcast, which can in turn be handled by multiple applications sequentially. The Android system is responsibl e for resolving the best-available receiver for each Intent, based on the criter ia supplied in the Intent and the Intent Filters defined by other applications. For more information, see Intents and Intent Filters. Related: Intent Filter, Br oadcast Receiver. Intent Filter A filter object that an application declares in its manifest file, to tell the system what types of Intents each of its componen ts is willing to accept and with what criteria. Through an intent filter, an app lication can express interest in specific data types, Intent actions, URI format s, and so on. When resolving an Intent, the system evaluates all of the availabl e intent filters in all applications and passes the Intent to the application/ac tivity that best matches http://developer.android.com/guide/appendix/glossary.html Page 2 of 4

Glossary | Android Developers 29.04.09 1:01 of the available intent filters in all applications and passes the Intent to the application/activity that best matches the Intent and criteria. For more inform ation, see Intents and Intent Filters. Related: Intent, Broadcast Receiver. Broa dcast Receiver An application class that listens for Intents that are broadcast, rather than being sent to a single target application/activity. The system deli vers a broadcast Intent to all interested broadcast receivers, which handle the Intent sequentially. Related: Intent, Intent Filter. Layout Resource An XML file that describes the layout of an Activity screen. Related: Resources Manifest Fi le An XML file that each application must define, to describe the application's package name, version, components (activities, intent filters, services), import ed libraries, and describes the various activies, and so on. See The AndroidMani fest.xml File for complete information. Nine-patch / 9-patch / Ninepatch image A resizeable bitmap resource that can be used for backgrounds or other images on the device. See Nine-Patch Stretchable Image for more information. Related: Reso urces. OpenGL ES Android provides OpenGL ES libraries that you can use for fast, complex 3D images. It is harder to use than a Canvas object, but better for 3D objects. The android.opengl and javax.microedition.khronos.opengles packages exp ose OpenGL ES functionality. Related: Canvas, Surface Resources Nonprogrammatic application components that are external to the compiled application code, but w hich can be loaded from application code using a well-known reference format. An droid supports a variety of resource types, but a typical application's resource s would consist of UI strings, UI layout components, graphics or other media fil es, and so on. An application uses resources to efficiently support localization and varied device profiles and states. For example, an application would includ e a separate set of resources for each supported local or device type, and it co uld include layout resources that are specific to the current screen orientation (landscape or portrait). For more information about resources, see Resources an d Assets. The resources of an application are always stored in the res/* subfold ers of the project. Service An object of class Service that runs in the backgrou nd (without any UI presence) to perform various persistent actions, such as play ing music or monitoring network activity. Related: Activity Surface An object of type Surface representing a block of memory that gets composited to the screen. A Surface holds a Canvas object for drawing, and provides various helper method s to draw layers and resize the surface. You should not use this class directly; use SurfaceView instead. Related: Canvas SurfaceView A View object that wraps a Surface for drawing, and exposes methods to specify its size and format dynamic ally. A SurfaceView provides a way to draw independently of the UI thread for re source-intensive operations (such as http://developer.android.com/guide/appendix/glossary.html Page 3 of 4

Glossary | Android Developers 29.04.09 1:01 A SurfaceView provides a way to draw independently of the UI thread for resource -intensive operations (such as games or camera previews), but it uses extra memo ry as a result. SurfaceView supports both Canvas and OpenGL ES graphics. The bas e class is SurfaceView. Related: Surface Theme A set of properties (text size, b ackground color, and so on) bundled together to define various default display s ettings. Android provides a few standard themes, listed in R.style (starting wit h "Theme_"). URIs in Android Android uses URI strings as the basis for requestin g data in a content provider (such as to retrieve a list of contacts) and for re questing actions in an Intent (such as opening a Web page in a browser). The URI scheme and format is specialized according to the type of use, and an applicati on can handle specific URI schemes and strings in any way it wants. Some URI sch emes are reserved by system components. For example, requests for data from a co ntent provider must use the content://. In an Intent, a URI using an http:// sch eme will be handled by the browser. View An object that draws to a rectangular a rea on the screen and handles click, keystroke, and other interaction events. A View is a base class for most layout components of an Activity or Dialog screen (text boxes, windows, and so on). It receives calls from its parent object (see viewgroup, below)to draw itself, and informs its parent object about where and h ow big it would like to be (which may or may not be respected by the parent). Fo r more information, see View. Related: Viewgroup, Widget Viewgroup A container o bject that groups a set of child Views. The viewgroup is responsible for decidin g where child views are positioned and how large they can be, as well as for cal ling each to draw itself when appropriate. Some viewgroups are invisible and are for layout only, while others have an intrinsic UI (for instance, a scrolling l ist box). Viewgroups are all in the widget package, but extend ViewGroup. Relate d: View Widget One of a set of fully implemented View subclasses that render for m elements and other UI components, such as a text box or popup menu. Because a widget is fully implemented, it handles measuring and drawing itself and respond ing to screen events. Widgets are all in the android.widget package. Window In a n Android application, an object derived from the abstract class Window that spe cifies the elements of a generic window, such as the look and feel (title bar te xt, location and content of menus, and so on). Dialog and Activity use an implem entation of this class to render a window. You do not need to implement this cla ss or use windows in your application. Except as noted, this content is licensed under Apache 2.0. For details and rest rictions, see the Content License. Android 1.5 r1 - 27 Apr 2009 0:19 Site Terms of Service - Privacy Policy - Brand Guidelines ! Go to top http://developer.android.com/guide/appendix/glossary.html Page 4 of 4

You might also like