Android the Developers Guide

Embed Size (px)

Citation preview

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: . . . The name attribute of the 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 elements for services, elements for broadcast receivers, and 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: < 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 . . . > . . . 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 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 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 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 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 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 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 , , , and 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 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 element creat es a TextView in your UI, and a 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: 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 OnLis tener, each with a callback method called On(). 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: 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: 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