Σχόλια 0

Το κείμενο του εγγράφου

ApplicationsAndroid will ship with a set of core applications including an email client, SMS program, calendar, maps, browser,contacts, and others. All applications are written using the Java programming language.Application FrameworkBy providing an open development platform, Android offers developers the ability to build extremely rich and innovativeapplications. Developers are free to take advantage of the device hardware, access location information, run backgroundservices, set alarms, add notifications to the status bar, and much, much more.Developers have full access to the same framework APIs used by the core applications. The application architecture isdesigned to simplify the reuse of components; any application can publish its capabilities and any other application maythen make use of those capabilities (subject to security constraints enforced by the framework). This same mechanismallows components to be replaced by the user.Underlying all applications is a set of services and systems, including:Page2of4What is Android? | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\basics\what-is-android.htmlA rich and extensible set ofViewsthat can be used to build an application, including lists, grids, text boxes, buttons,and even an embeddable web browser•Content Providersthat enable applications to access data from other applications (such as Contacts), or to sharetheir own data•AResource Manager, providing access to non-code resources such as localized strings, graphics, and layout files•ANotification Managerthat enables all applications to display custom alerts in the status bar•AnActivity Managerthat manages the lifecycle of applications and provides a common navigation backstack•For more details and a walkthrough of an application, see theNotepad Tutorial.LibrariesAndroid includes a set of C/C++ libraries used by various components of the Android system. These capabilities areexposed to developers through the Android application framework. Some of the core libraries are listed below:System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices•Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of manypopular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, andPNG•Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layersfrom multiple applications•LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view•SGL - the underlying 2D graphics engine•3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration(where available) or the included, highly optimized 3D software rasterizer•FreeType - bitmap and vector font rendering•SQLite - a powerful and lightweight relational database engine available to all applications•Android RuntimeAndroid includes a set of core libraries that provides most of the functionality available in the core libraries of the Javaprogramming language.Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has beenwritten so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex)format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Javalanguage compiler that have been transformed into the .dex format by the included "dx" tool.The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memorymanagement.Page3of4What is Android? | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\basics\what-is-android.html↑ Go to topLinux KernelAndroid relies on Linux version 2.6 for core system services such as security, memory management, processmanagement, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware andthe rest of the software stack.Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 14 May 2010 15:20Site Terms of Service-Privacy Policy-Brand Guidelines

Page4of4What is Android? | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\basics\what-is-android.htmlActivitiesAn activity presents a visual user interface for one focused endeavor the user can undertake. For example, anactivity might present a list of menu items users can choose from or it might display photographs along with theircaptions. A text messaging application might have one activity that shows a list of contacts to send messages to, asecond activity to write the message to the chosen contact, and other activities to review old messages or changesettings. Though they work together to form a cohesive user interface, each activity is independent of the others.Each one is implemented as a subclass of theActivitybase class.An application might consist of just one activity or, like the text messaging application just mentioned, it may containseveral. What the activities are, and how many there are depends, of course, on the application and its design.Typically, one of the activities is marked as the first one that should be presented to the user when the application islaunched. Moving from one activity to another is accomplished by having the current activity start the next one.Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller thanthe screen and float on top of other windows. An activity can also make use of additional windows — fo r example, apop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vitalinformation when they select a particular item on-screen.The visual content of the window is provided by a hierarchy of views — objects derived from the baseViewclass.Each view controls a particular rectangular space within the window. Parent views contain and organize the layout oftheir children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond touser actions directed at that space. Thus, views are where the activity's interaction with the user takes place. Forexample, a view might display a small image and initiate an action when the user taps that image. Android has anumber of ready-made views that you can use — inclu ding buttons, text fields, scroll bars, menu items, check boxes,and more.A view hierarchy is placed within an activity's window by theActivity.setContentView()method. The contentview is the View object at the root of the hierarchy. (See the separateUser Interfacedocument for more informationon views and the hierarchy.)ServicesA service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. Forexample, a service might play background music as the user attends to other matters, or it might fetch data over thenetwork or calculate something and provide the result to activities that need it. Each service extends theService

base class.A prime example is a media player playing songs from a play list. The player application would probably have one ormore activities that allow the user to choose songs and start playing them. However, the music playback itself wouldnot be handled by an activity because users will expect the music to keep playing even after they leave the playerand begin something different. To keep the music going, the media player activity could start a service to run in thebackground. The system would then keep the music playback service running even after the activity that started itleaves the screen.It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). Whileconnected, you can communicate with the service through an interface that the service exposes. For the musicservice, this interface might allow users to pause, rewind, stop, and restart the playback.Like activities and the other components, services run in the main thread of the application process. So that theywon't block other components or the user interface, they often spawn another thread for time-consuming tasks (likemusic playback). SeeProcesses and Threads, later.Broadcast receiversA broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Manybroadcasts originate in system code — for example, announcements that the timezone has changed, that the batteryis low, that a picture has been taken, or that the user changed a language preference. Applications can also initiatebroadcasts — for example, to let other applications know that some data has been downloaded to the device and isavailable for them to use.Page2of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlAn application can have any number of broadcast receivers to respond to any announcements it considers important.All receivers extend theBroadcastReceiverbase class.Broadcast receivers do not display a user interface. However, they may start an activity in response to theinformation they receive, or they may use theNotificationManagerto alert the user. Notifications can get theuser's attention in various ways — flashing the bac klight, vibrating the device, playing a sound, and so on. Theytypically place a persistent icon in the status bar, which users can open to get the message.Content providersA content provider makes a specific set of the application's data available to other applications. The data can bestored in the file system, in an SQLite database, or in any other manner that makes sense. The content providerextends theContentProviderbase class to implement a standard set of methods that enable other applications toretrieve and store data of the type it controls. However, applications do not call these methods directly. Rather theyuse aContentResolverobject and call its methods instead. A ContentResolver can talk to any content provider; itcooperates with the provider to manage any interprocess communication that's involved.See the separateContent Providersdocument for more information on using content providers.Whenever there's a request that should be handled by a particular component, Android makes sure that the applicationprocess of the component is running, starting it if necessary, and that an appropriate instance of the component isavailable, creating the instance if necessary.Activating components: intentsContent providers are activated when they're targeted by a request from a ContentResolver. The other three components— activities, services, and broadcast receivers — a re activated by asynchronous messages called intents. An intent is anIntentobject that holds the content of the message. For activities and services, it names the action being requestedand specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity topresent an image to the user or let the user edit some text. For broadcast receivers, the Intent object names the actionbeing announced. For example, it might announce to interested parties that the camera button has been pressed.There are separate methods for activating each type of component:An activity is launched (or given something new to do) by passing an Intent object toContext.startActivity()

orActivity.startActivityForResult(). The responding activity can look at the initial intent that caused it tobe launched by calling itsgetIntent()method. Android calls the activity'sonNewIntent()method to pass it anysubsequent intents.•One activity often starts the next one. If it expects a result back from the activity it's starting, it callsstartActivityForResult()instead ofstartActivity(). For example, if it starts an activity that lets the userpick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object that's passedto the calling activity'sonActivityResult()method.A service is started (or new instructions are given to an ongoing service) by passing an Intent object toContext.startService(). Android calls the service'sonStart()method and passes it the Intent object.•Similarly, an intent can be passed toContext.bindService()to establish an ongoing connection between thecalling component and a target service. The service receives the Intent object in anonBind()call. (If the service isnot already running,bindService()can optionally start it.) For example, an activity might establish a connectionwith the music playback service mentioned earlier so that it can provide the

user with the means (a user interface) forcontrolling the playback. The activity would callbindService()to set up that connection, and then call methodsdefined by the service 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 passing an Intent object to methods likeContext.sendBroadcast(),Context.sendOrderedBroadcast(), andContext.sendStickyBroadcast()in any of their variations.Android delivers the intent to all interested broadcast receivers by calling theironReceive()methods.•Page3of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlFor more on intent messages, see the separate article,Intents and Intent Filters.Shutting down componentsA content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver isactive 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-running conversation with the user and mayremain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for along time. So Android has methods to shut down activities and services in an orderly way:An activity can be shut down by calling itsfinish()method. One activity can shut down another activity (one itstarted withstartActivityForResult()) by callingfinishActivity().•A service can be stopped by calling itsstopSelf()method, or by callingContext.stopService().•Components might also be shut down by the system when they are no longer being used or when Android must reclaimmemory for more active components. A later section,Component Lifecycles, discusses this possibility and itsramifications in more detail.The manifest fileBefore Android can start an application component, it must learn that the component exists. Therefore, applicationsdeclare their components in a manifest file that's bundled into the Android package, the.apkfile that also holds theapplication's code, files, and resources.The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It does a number ofthings in addition to declaring the application's components, such as naming any libraries the application needs to belinked 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 application's components. For example, an activitymight be declared as follows:<?xml version="1.0" encoding="utf-8"?><manifest . . . ><application . . . ><activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel". . . ></activity>. . .</application></manifest>Thenameattribute of the<activity>element names theActivitysubclass that implements the activity. Theicon

andlabelattributes point to resource files containing an icon and label that can be displayed to users to represent theactivity.The other components are declared in a similar way —<service>elements for services,<receiver>elements forbroadcast receivers, and<provider>elements for content providers. Activities, services, and content providers that arenot declared in the manifest are not visible to the system and are consequently never run. However, broadcast receiverscan either be declared in the manifest, or they can be created dynamically in code (asBroadcastReceiverobjects)and registered with the system by callingContext.registerReceiver().For more on how to structure a manifest file for your application, seeThe AndroidManifest.xml File.Page4of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlIntent filtersAn Intent object can explicitly name a target component. If it does, Android finds that component (based on thedeclarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the bestcomponent to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. Acomponent's intent filters inform Android of the kinds of intents the component is able to handle. Like other essentialinformation about the component, they're declared in the manifest file. Here's an extension of the previous example thatadds two intent filters to the activity:<?xml version="1.0" encoding="utf-8"?><manifest . . . ><application . . . ><activity android:name="com.example.project.FreneticActivity"android:icon="@drawable/small_pic.png"android:label="@string/freneticLabel". . . ><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" /><data android:mimeType="image/jpeg" /><category android:name="android.intent.category.DEFAULT" /></intent-filter></activity>. . .</application></manifest>The first filter in the example — the combination o f the action "android.intent.action.MAIN" and the category"android.intent.category.LAUNCHER" — is a common one. It marks theactivity as one that should be representedin the application launcher, the screen listing applications users can launch on the device. In other words, the activity isthe entry point for the application, the initial one users would see when they choose the application in the launcher.The second filter declares an action that the activity can perform on a particular type of data.A component can have any number of intent filters, each one declaring adifferent set of capabilities. If it doesn't have anyfilters, it can be activated only by intents that explicitly name the component as the target.For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as anIntentFilterobject. All other filters are set up in the manifest.For more on intent filters, see a separate document,Intents and Intent Filters.Activities and TasksAs noted earlier, one activity can start another, including one defined in a differentapplication. Suppose, for example, thatyou'd like to let users display a street map of some location. There's already an activity that can do that, so all youractivity needs to do is put together an Intent object with the required information and pass it tostartActivity(). Themap 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 inanother application and runs in that application's process. Android maintains this user experience by keeping bothactivities in the same task. Simply put, a task is what the user experiences as an "application." It's a group of relatedactivities, arranged in a stack. The root activity in the stack is the one that began the task — typic ally, it's an activity thePage5of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmluser selected in the application launcher. The activity at the top of the stack is one that's currently running — the one thatis the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes therunning activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity ispopped 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 mapviewers, for example — the stack has a separate ent ry for each instance. Activities in the stack are never rearranged,only pushed and popped.A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a taskindependently of its activities. Values for the task as a whole are set in the root activity. For example, the next section willtalk about the "affinity of a task"; that value is read from the affinity set for the task's root activity.All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to theforeground or sent to the background. Suppose, for instance, that the current task has four activities in its stack — threeunder the current activity. The user presses the HOME key, goes to the application launcher, and selects a newapplication (actually, a new task). The current task goes into the background and the root activity for the new task isdisplayed. 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 thetop of the stack is removed and the previous activity in the same task is displayed.The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost allaspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by theinteraction between flags set in the Intent object that started the activity and attributes set in the 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

finishOnTaskLaunchThe following sections describe what some of these flags and attributes do, how they interact, and what considerationsshould govern their use.Affinities and new

tasksBy default, all the activities in an application have an affinity for each other — that is, there's a preference for them all tobelong to the same task. However, an individual affinity can be set for each activity with thetaskAffinityattribute ofthe<activity>element. Activities defined in different applications can share an affinity, or activities defined in thesame application can be assigned different affinities. The affinity comes into play in two circumstances: When the Intentobject that launches an activity contains theFLAG_ACTIVITY_NEW_TASKflag, and when an activity has itsallowTaskReparentingattribute set to "true".TheFLAG_ACTIVITY_NEW_TASKflagAs described earlier, a new activity is, by default, launched into the task of the activity that calledstartActivity(). It's pushed onto the same stack as the caller. However, if the Intent object passed tostartActivity()

Page6of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlcontains theFLAG_ACTIVITY_NEW_TASKflag, the system looks for a different task to house the new activity. Often,as the name of the flag implies, it's a new task. However, it doesn't have to be. If there's already an existing task withthe same affinity as the new activity, the activity is launched into that task. If not, it begins a new task.TheallowTaskReparentingattributeIf an activity has itsallowTaskReparentingattribute set to "true", it can move from the task it starts in to thetask it has an affinity for when that task comes to the fore. For example, suppose that an activity that reports weatherconditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in thesame application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so itinitially belongs to the same task as your activity. However, when the travel application next comes forward, theweather reporter will be reassigned to and displayed with that task.If an.apkfile contains more than one "application" from the user's point of view, you will probably want to assigndifferent affinities to the activities associated with each of them.Launch modesThere are four different launch modes that can be assigned to an<activity>element'slaunchModeattribute:"standard" (the default mode)"singleTop""singleTask""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'sthe task that originated the intent (and calledstartActivity()) — unless the Intent object contains theFLAG_ACTIVITY_NEW_TASKflag. In that case, a different task is chosen as described in the previous section,Affinities and new tasks.•In contrast, the "singleTask" and "singleInstance" modes mark activities that are always at the root of a task.They define a task; they're never launched into another task.Whether there can be multiple instances of the activity. A "standard" or "singleTop" activity can beinstantiated many times. They can belong to multiple tasks, and a given task can have multiple instances of the sameactivity.•In contrast, "singleTask" and "singleInstance" activities are limited to just one instance. Since these activitiesare at the root of a task, this limitation means that there is never more than a single instance of the task on the deviceat one time.Whether the instance can have other activities in its task. A "singleInstance" activity stands alone as theonly activity in its task. If it starts another activity, that activity will be launched into a different task regardless of itslaunch mode — as ifFLAG_ACTIVITY_NEW_TASKwas in the intent. In all other respects, the "singleInstance"mode is identical to "singleTask".•The other three modes permit multiple activities to belong to the task. A "singleTask" activity will always be theroot activity of the task, but it can start other activities that will be assigned to its task. Instances of "standard" and"singleTop" activities can appear anywhere in a stack.Whether a new instance of the class will be launched to handle a new intent. For the default "standard" mode,a new instance is created to respond to every new intent. Each instance handles just one intent. For the"singleTop" mode, an existing instance of the class is re-used to handle a new intent if it resides at the top of theactivity stack of the target task. If it does not reside at the top, it is not re-used. Instead, a new instance is created forthe new intent and pushed on the stack.•For example, suppose a task's activity stack consists of root activity A with activities B, C, and D on top in that order,so the stack is A-B-C-D. An intent arrives for an activity of type D. If D has the default "standard" launch mode, anew instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode isPage7of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.html"singleTop", the existing instance is expected to handle the new intent (since it's at the top of the stack) and thestack remains A-B-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 matterwhether B's mode is "standard" or "singleTop" (since B is not at the top of the stack), so the resulting stackwould be A-B-C-D-B.As noted above, there's never more than one instance of a "singleTask" or "singleInstance" activity, so thatinstance is expected to handle all new intents. A "singleInstance" activity is always at the top of the stack (sinceit is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask" activitymay or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and theintent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to theforeground, where it would remain.)When an existing activity is asked to handle a new intent, the Intent object is passed to the activity in anonNewIntent()

call. (The intent object that originally started the activity can be retrieved by callinggetIntent().)Note that when a new instance of an Activity is created to handle a new intent, the user can always press the BACK keyto return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent,the user cannot press the BACK key to return to what that instance was doing before the new intent arrived.For more on launch modes, see the description of the<activity>element.Clearing the stackIf the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the userreturns 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 before and are returning to the task to begin something new.That's the default. There are some activity attributes that can be used to control this behavior and modify it:ThealwaysRetainTaskStateattributeIf this attribute is set to "true" in the root activity of a task, the default behavior just described does not happen. Thetask retains all activities in its stack even after a long period.TheclearTaskOnLaunchattributeIf this attribute is set to "true" in the root activity of a task, the stack is cleared down to the root activity whenever theuser leaves the task and returns to it. In other words, it's the polar opposite ofalwaysRetainTaskState. The useralways returns to the task in its initial state, even after a momentary absence.ThefinishOnTaskLaunchattributeThis attribute is likeclearTaskOnLaunch, but it operates on a single activity, not an entire task. And it can causeany activity to go away, including the root activity. When it's set to "true", the activity remains part of the task onlyfor the current session. If the user leaves and then returns to the task, it no longer is present.There's another way to force activities to be removed from the stack. If an Intent object includes theFLAG_ACTIVITY_CLEAR_TOPflag, and the target task already has an instance of the type of activity that should handlethe intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and canrespond to the intent. If the launch mode of the designated activity is "standard", it too will be removed from the stack,and a new instance will be launched to handle the incoming intent. That's because a new instance is always created for anew intent when the launch mode is "standard".FLAG_ACTIVITY_CLEAR_TOPis most often used in conjunction withFLAG_ACTIVITY_NEW_TASK. When usedtogether, these flags are a way of locating an existing activity in another task and putting it in a position where it canrespond to the intent.Page8of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlStarting tasksAn activity is set up as the entry point for a task by giving it an intent filter with "android.intent.action.MAIN" as thespecified action and "android.intent.category.LAUNCHER" as the specified category. (There's an example of thistype of filter in the earlierIntent Filterssection.) A filter of this kind causes an icon and label for the activity to be displayedin the application launcher, giving users a way both to launch the task and to return to it at any time after it has beenlaunched.This second ability is important: Users must be able to leave a task and then come back to it later. For this reason, thetwo launch modes that mark activities as always initiating a task, "singleTask" and "singleInstance", should beused only when the activity has aMAINandLAUNCHERfilter. Imagine, for example, what could happen if the filter ismissing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in thattask. 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 the application launcher, the user has no way to return to it.A similar difficulty attends theFLAG_ACTIVITY_NEW_TASKflag. If this flag causes an activity to begin a new task and theuser 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 notification manager) always start activities in an external task, never as part of their own, so they always putFLAG_ACTIVITY_NEW_TASKin the intents they pass tostartActivity(). If you have an activity that can be invokedby an external entity that might use this flag, take care that the user has a independent way to get back to the task that'sstarted.For those cases where you don't want the user to be able to return to an activity, set the<activity>element'sfinishOnTaskLaunchto "true". SeeClearing the stack, earlier.Processes and ThreadsWhen the first of an application's components needs to be run, Android starts a Linux process for it with a single thread ofexecution. By default, all components of the application run in that process and thread.However, you can arrange for components to run in other processes, and you can spawn additional threads for anyprocess.ProcessesThe process where a component runs is controlled by the manifest file. The component elements —<activity>,<service>,<receiver>, and<provider>— each have aprocessattribute that can specify a process where thatcomponent should run. These attributes can be set so that each component runs in its own process, or so that somecomponents share a process while others do not. They can also be set so that components of different applications run inthe same process — provided that the applications s hare the same Linux user ID and are signed by the same authorities.The<application>element also has aprocessattribute, for setting a default value that applies to all components.All components are instantiated in the main thread of the specified process, and system calls to the component aredispatched from that thread. Separate threads are not created for each instance. Consequently, methods that respond tothose calls — methods likeView.onKeyDown()that report user actions and the lifecycle notifications discussed later intheComponent Lifecyclessection — always run in the main thread of the pro cess. This means that no component shouldperform long or blocking operations (such as networking operations or computation loops) when called by the system,since this will block any other components also in the process. You can spawn separate threads for long operations, asdiscussed underThreads, next.Android may decide to shut down a process at some point, when memory is low and required by other processes that aremore immediately serving the user. Application components running in the process are consequently destroyed. Aprocess is restarted for those components when there's again work for them to do.Page9of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlWhen deciding which processes to terminate, Android weighs their relative importance to the user. For example, it morereadily shuts down a process with activities that are no longer visible on screen than a process with visible activities. Thedecision whether to terminate a process, therefore, depends on the state of the components running in that process.Those states are the subject of a later section,Component Lifecycles.ThreadsEven though you may confine your application to a single process, there will likely be times when you will need to spawna thread to do some background work. Since the user interface must always be quick to respond to user actions, thethread that hosts an activity should not also host time-consuming operations like network downloads. Anything that maynot be completed quickly should be assigned to a different thread.Threads are created in code using standard JavaThreadobjects. Android provides a number of convenience classes formanaging threads —Looperfor running a message loop within a thread,Handlerfor processing messages, andHandlerThreadfor setting up a thread with a message loop.Remote procedure callsAndroid has a lightweight mechanism for remote procedure calls (RPCs) — where a method is called local ly, butexecuted remotely (in another process), with any result returned back to the caller. This entails decomposing the methodcall and all its attendant data to a level the operating system can understand, transmitting it from the local process andaddress space to the remote process and address space, and reassembling and reenacting the call there. Return valueshave to be transmitted in the opposite direction. Android provides all the code to do that work, so that you canconcentrate on defining and implementing the RPC interface itself.An RPC interface can include only methods. By default, all methods are executed synchronously (the local method blocksuntil the remote method finishes), even if there is no return value.In brief, the mechanism works as follows: You'd begin by declaring the RPC interface you want to implement using asimple IDL (interface definition language). From that declaration, theaidltool generates a Java interface definition thatmust be made available to both the local and the remote process. It contains two inner class, as shown in the followingdiagram:

Page10of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlThe inner classes have all the code needed to administer remote procedure calls for the interface you declared with theIDL. Both inner classes implement theIBinderinterface. One of them is used locally and internally by the system; thecode you write can ignore it. The other, called Stub, extends theBinderclass. In addition to internal code foreffectuating the IPC calls, it contains declarations for the methods in the RPC interface you declared. You would subclassStub to implement those methods, as indicated in the diagram.Typically, the remote process would be managed by a service (because a service can inform the system about theprocess and its connections to other processes). It would have both the interface file generated by theaidltool and theStub subclass implementing the RPC methods. Clients of the service would have only the interface file generated by theaidltool.Here's how a connection between a service and its clients is set up:Clients of the service (on the local side) would implementonServiceConnected()andonServiceDisconnected()methods so they can be notified when a successful connection to the remote serviceis established, and when it goes away. They would then callbindService()to set up the connection.•The service'sonBind()method would be implemented to either accept or reject the connection, depending on theintent it receives (the intent passed tobindService()). If the connection is accepted, it returns an instance of theStub subclass.•If the service accepts the connection, Android calls the client'sonServiceConnected()method and passes it anIBinder object, a proxy for the Stub subclass managed by the service. Through the proxy, the client can make callson the remote service.•This brief description omits some details of the RPC mechanism. For more information, seeDesigning a RemoteInterface Using AIDLand theIBinderclass description.Thread-safe methodsIn a few contexts, the methods you implement may be called from more than one thread, and therefore must be written tobe thread-safe.This is primarily true for methods that can be called remotely — as in the RPC mechanism discussed in the previoussection. When a call on a method implemented in an IBinder object originates in the same process as the IBinder, themethod is executed in the caller's thread. However, when the call originates in another process, the method is executed ina thread chosen from a pool of threads that Android maintains in the same process as the IBinder; it's not executed in themain thread of the process. For example, whereas a service'sonBind()method would be called from the main thread ofthe service's process, methods implemented in the object thatonBind()returns (for example, a Stub subclass thatimplements RPC methods) would be called from threads in the pool. Since services can have more than one client, morethan one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, beimplemented to be thread-safe.Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolverand ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvidermethods that respond to those requests — the method squery(),insert(),delete(),update(), andgetType()

— are called from a pool of threads in the content provider's process, not the main thread of the process. Since thesemethods may be called from any number of threads at the same time, they too must be implemented to be thread-safe.Component LifecyclesApplication components have a lifecycle — a beginni ng when Android instantiates them to respond to intents through toan end when the instances are destroyed. In between, they may sometimes be active or inactive,or, in the case ofactivities, visible to the user or invisible. This section discusses the lifecycles of activities, services, and broadcastreceivers — including the states that they can be i n during their lifetimes, the methods that notify you of transitionsPage11of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlCalling into the superclassAn implementation of any activity lifecycle methodshould always first call the superclass version. Forexample:protected void onPause() {super.onPause();. . . }between states, and the effect of those states on the possibility that the process hosting them might be terminated andthe instances destroyed.Activity lifecycleAn 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 task).This is the activity that is the focus for the user's actions.•It is paused if it has lost focus but is still visible to the user. That is, another activity lies on top of it and that activityeither is transparent or doesn't cover the full screen, so some of the paused activity can show through. A pausedactivity is completely alive (it maintains all state and member information and remains attached to the windowmanager), but can be killed by the system in extreme low memory situations.•It is stopped if it is completely obscured by another activity. 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 system when memory isneeded elsewhere.•If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish()

method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restoredto its previous state.As an activity transitions from state to state, it is notified of the change by calls to the following protected methods:void onCreate(Bundle savedInstanceState)

void onStart()

void onRestart()

void onResume()

void onPause()

void onStop()

void onDestroy()All of these methods are hooks that you can override to do appropriate work when the state changes. All activities mustimplementonCreate()to do the initial setup when the object is first instantiated. Many will also implementonPause()

to commit data changes and otherwise prepare to stop interacting with the user.Taken together, these seven methods define the entirelifecycle of an activity. There are three nested loops that youcan monitor by implementing them:The entire lifetime of an activity happens between thefirst call toonCreate()through to a single final call toonDestroy(). An activity does all its initial setup of"global" state inonCreate(), and releases allremaining resources inonDestroy(). For example, if ithas a thread running in the background to download datafrom the network, it may create that thread inonCreate()and then stop the thread inonDestroy().•The visible lifetime of an activity happens between a call toonStart()until a corresponding call toonStop().During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting withthe user. Between these two methods, you can maintain resources that are needed to show the activity to the user.For example, you can register aBroadcastReceiverinonStart()to monitor for changes that impact your UI,and unregister it inonStop()when the user can no longer see what you are displaying. TheonStart()andonStop()methods can be called multiple times, as the activity alternates between being visible and hidden to theuser.•Page12of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlMethod Description Killable?NextonCreate()Called when the activity is first created.This is where you should do all of yournormal static set up — create views,bind data to lists, and so on. Thismethod is passed a Bundle objectcontaining the activity's previous state,if that state was captured (seeSavingActivity State, later).Always followed byonStart().NoonStart()

onRestart()Called after the activity has beenstopped, just prior to it being startedagain.Always followed byonStart()NoonStart()onStart()Called just before the activity becomesvisible to the user.Followed byonResume()if the activitycomes to the foreground, oronStop()

if it becomes hidden.NoonResume()

oronStop()

onResume()Called just before the activity startsinteracting with the user. At this pointthe activity is at the top of the activitystack, with user input going to it.Always followed byonPause().NoonPause()onPause()Called when the system is about tostart resuming another activity. Thismethod is typically used to commitunsaved changes to persistent data,stop animations and other things thatmay be consuming CPU, and so on. Itshould do whatever it does veryquickly, because the next activity willnot be resumed until it returns.Followed either byonResume()if theactivity returns back to the front, or byonStop()if it becomes invisible to theuser.YesonResume()

oronStop()onStop()Called when the activity is no longervisible to the user. This may happenbecause it is being destroyed, orbecause another activity (either anexisting one or a new one) has beenresumed and is covering it.Followed either byonRestart()if theactivity is coming back to interact withthe user, or byonDestroy()if thisactivity is going away.YesonRestart()

oronDestroy()Page14of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlMethod Description Killable?NextonDestroy()Called before the activity is destroyed.This is the final call that the activity willreceive. It could be called eitherbecause the activity is finishing(someone calledfinish()on it), orbecause the system is temporarilydestroying this instance of the activityto save space. You can distinguishbetween these two scenarios with theisFinishing()method.YesnothingNote the Killable column in the table above. It indicates whether or not thesystem can kill the process hosting the activityat any time after the method returns, without executing another line of the activity's code. Three methods (onPause(),onStop(), andonDestroy()) are marked "Yes." BecauseonPause()is the first of the three, it's the only one that'sguaranteed to be called before the process is killed —onStop()andonDestroy()may not be. Therefore, you shoulduseonPause()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 themoment they are called. Thus an activity is in a killable state, for example, from the timeonPause()returns to the timeonResume()is called. It will not again be killable untilonPause()again returns.As noted in a later section,Processes and lifecycle, an activity that's not technically "killable" by this definition might stillbe killed by the system — but that would happen onl y in extreme and dire circumstances when there is no otherrecourse.Saving activity stateWhen the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to theactivity and find it in its previous state.To capture that state before the activity is killed, you can implement anonSaveInstanceState()method for theactivity. Android calls this method before making the activity vulnerable to being destroyed — that is, beforeonPause()

is called. It passes the method aBundleobject where you can record the dynamic state of the activity as name-valuepairs. When the activity is again started, the Bundle is passed both toonCreate()and to a method that's called afteronStart(),onRestoreInstanceState(), so that either or both of them can recreate the captured state.UnlikeonPause()and the other methods discussed earlier,onSaveInstanceState()andonRestoreInstanceState()are not lifecycle methods. They are not always called. For example, Android callsonSaveInstanceState()before the activity becomes vulnerable to being destroyed by the system, but does notbother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In thatcase, the user won't expect to return to the activity, so there's no reason to save its state.BecauseonSaveInstanceState()is not always called, you should use it only to record the transient state of theactivity, not to store persistent data. UseonPause()for that purpose instead.Coordinating activitiesWhen one activity starts another, they both experience lifecycle transitions. One pauses and may stop, while the otherstarts up. On occasion, you may need to coordinate these activities, one with the other.The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process:The current activity'sonPause()method is called.1.Next, the starting activity'sonCreate(),onStart(), andonResume()methods are called in sequence.2.Then, if the starting activity is no longer visible on screen, itsonStop()method is called.3.Page15of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlService lifecycleA service can be used in two ways:It can be started and allowed to run until someone stops it or it stops itself. In this mode, it's started by callingContext.startService()and stopped by callingContext.stopService(). It can stop itself by callingService.stopSelf()orService.stopSelfResult(). Only onestopService()call is needed to stop theservice, no matter how many timesstartService()was called.•It can be operated programmatically using an interface that it defines and exports. Clients establish a connection tothe Service object and use that connection to call into the service. The connection is established by callingContext.bindService(), and is closed by callingContext.unbindService(). Multiple clients can bind to thesame service. If the service has not already been launched,bindService()can optionally launch it.•The two modes are not entirely separate. You can bind to a service that was started withstartService(). Forexample, a background music service could be started by callingstartService()with an Intent object that identifiesthe music to play. Only later, possibly when the user wants to exercise some control over the player or get informationabout the current song, would an activity establish a connection to the service by callingbindService(). In cases likethis,stopService()will not actually stop the service until the last binding is closed.Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewerthan the activity methods — only three — and they a re public, not protected:void onCreate()

void onStart(Intent intent)

void onDestroy()By implementing these methods, you can monitor two nested loops of the service's lifecycle:The entire lifetime of a service happens between the timeonCreate()is called and the timeonDestroy()

returns. Like an activity, a service does its initial setup inonCreate(), and releases all remaining resources inonDestroy(). For example, a music playback service could create the thread where the music will be played inonCreate(), and then stop the thread inonDestroy().•The active lifetime of a service begins with a call toonStart(). This method is handed the Intent object that waspassed tostartService(). The music service would open the Intent to discover which music to play, and beginthe playback.•There's no equivalent callback for when the service stops — noonStop()method.TheonCreate()andonDestroy()methods are called for all services, whether they're started byContext.startService()orContext.bindService(). However,onStart()is called only for services started bystartService().If a service permits others to bind to it, there are additional callback methods for it to implement:IBinder onBind(Intent intent)

boolean onUnbind(Intent intent)

void onRebind(Intent intent)TheonBind()callback is passed the Intent object that was passed tobindServiceandonUnbind()is handed theintent that was passed tounbindService(). If the service permits the binding,onBind()returns the communicationschannel that clients use to interact with the service. TheonUnbind()method can ask foronRebind()to be called if anew client connects to the service.The following diagram illustrates the callback methods for a service. Although, it separates services that are created viastartServicefrom those created bybindService(), keep in mind that any service, no matter how it's started, canpotentially allow clients to bind to it, so any service may receiveonBind()andonUnbind()calls.Page16of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlProcesses and lifecyclesThe Android system tries to maintain an application process for as long as possible, but eventually it will need to removeold processes when memory runs low. To determine which processes to keep and which to kill, Android places eachprocess into an "importance hierarchy" based on the components running in it and the state of those components.Processes with the lowest importance are eliminated first, then those with the next lowest, and so on. There are fivelevels in the hierarchy. The following list presents them in order of importance:A foreground process is one that is required for what the user is currently doing. A process is considered to be inthe foreground if any of the following conditions hold:1.It is running an activity that the user is interacting with (the Activity object'sonResume()method has beencalled).◦It hosts a service that's bound to the activity that the user is interacting with.◦It has aServiceobject that's executing one of its lifecycle callbacks (onCreate(),onStart(), oronDestroy()).◦It has aBroadcastReceiverobject that's executing itsonReceive()method.◦Only a few foreground processes will exist at any given time. They are killed only as a last resort — if memory is solow that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, sokilling some foreground processes is required to keep the user interface responsive.A visible process is one that doesn't have any foreground components, but still can affect what the user sees onscreen. A process is considered to be visible if either of the following conditions holds:2.It hosts an activity that is not in the foreground, but is still visible to the user (itsonPause()method has beencalled). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to beseen behind it.◦It hosts a service that's bound to a visible activity.◦A visible process is considered extremely important and will not be killed unless doing so is required to keep allforeground processes running.A service process is one that is running a service that has been started with thestartService()method andthat does not fall into either of the two higher categories. Although service processes are not directly tied to anythingthe user sees, they are generally doing things that the user cares about (such as playing an mp3 in the backgroundor downloading data on the network), so the system keeps them running unless there's not enough memory to retainthem along with all foreground and visible processes.3.A background process is one holding an activity that's not currently visible to the user (the Activity object'sonStop()method has been called). These processes have no direct impact on the user experience, and can be killed atany time to reclaim memory for a foreground, visible, or service process. Usually there are many backgroundprocesses running, so they are kept in an LRU (least recently used) list to ensure that the process with the activitythat was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methodscorrectly, and captures its current state, killing its process will not have a deleterious effect on the user experience.4.An empty process is one that doesn't hold any active application components. The only reason to keep such aprocess around is as a cache to improve startup time the next time a component needs to run in it. The system oftenkills these processes in order to balance overall system resources between process caches and the underlyingkernel caches.5.Android ranks a process at the highest level it can, based upon the importance of the components currently active in theprocess. 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.Page18of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.html↑ Go to topIn addition, a process's ranking may be increased because other processes are dependent on it. A process that is servinganother process can never be ranked lower than the process it is serving. For example, if a content provider in process Ais serving a client in process B, or if a service in process A is bound to a component in process B, process A will alwaysbe considered at least as important as process B.Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if theoperation will likely outlast the activity. Examples of this are playing music in the background and uploading a picturetaken by the camera to a web site. Using a service guarantees that the operation will have at least "service process"priority, regardless of what happens to the activity. As noted in theBroadcast receiver lifecyclesection earlier, this is thesame reason that broadcast receivers should employ services rather than simply put time-consuming operations in athread.Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 14 May 2010 15:20Site Terms of Service-Privacy Policy-Brand Guidelines

Page19of19Application Fundamentals | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\fundamentals.htmlTip: You can also draw View and ViewGroups objectsin Java code, using theaddView(View)methods todynamically insert new View and ViewGroup objects.Views and adding them to their parent(s). Because these are drawn in-order, if there are elements 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 hierarchies are measured and drawn, readHow Android Draws Views.LayoutThe most common way to define your layout and express the view hierarchy is with an XML layout file. XML offers ahuman-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object (ordescendant thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree (see the ViewHierarchy figure above).The name of an XML element is respective to the Java class that it represents. So a<TextView>element creates aTextViewin your UI, and a<LinearLayout>element creates aLinearLayoutview group. When you load a layoutresource, the Android system initializes these run-time objects, corresponding to the elements in your layout.For example, a simple vertical layout with a text view and a button looks like this:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextView android:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="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 both the TextView and the Button. You can nest another LinearLayout (orother type of view group) inside here, to lengthen the view hierarchy and create a more complex layout.For more on building a UI layout, readDeclaring Layout.There are a variety of ways in which you can layout yourviews. Using more and different kinds of view groups, youcan structure child views and view groups in an infinitenumber of ways. Some pre-defined view groups offered byAndroid (called layouts) include LinearLayout,RelativeLayout, TableLayout, GridLayout and others. Eachoffers a unique set of layout parameters that are used to define the positions of child views and layout structure.To learn about some of the different kinds of view groups used for a layout, readCommon Layout Objects.WidgetsA widget is a View object that serves as an interface for interaction with the user. Android provides a set of fullyimplemented widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI. Some widgetsprovided by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kindsPage2of4User Interface | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\index.htmlof widgets provided by the Android platform. If you'd like to do something more customized and create your ownactionable elements, you can, by defining your own View object or by extending and combining existing widgets.Read more inBuilding Custom Components.For a list of the widgets provided by Android, see theandroid.widgetpackage.UI EventsOnce you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, soyou can perform actions. To be informed of UI events, you need to do one of two things:Define an event listener and register it with the View. More often than not, this is how you'll listen for events. TheView class contains a collection of nested interfaces named On<something>Listener, each with a callback methodcalledOn<something>(). For example,View.OnClickListener(for handling "clicks" on a View),View.OnTouchListener(for handling touch screen events in a View), andView.OnKeyListener(for handlingdevice key presses within a View). So if you want your View to be notified when it is "clicked" (such as when a buttonis selected), implement OnClickListener and define itsonClick()callback method (where you perform the actionupon click), and register it to the View withsetOnClickListener().•Override an existing callback method for the View. This is what you should do when you've implemented yourown View class and want to listen for specific events that occur within it. Example events you can handle includewhen the screen is touched (onTouchEvent()), when the trackball is moved (onTrackballEvent()), or when akey on the device is pressed (onKeyDown()). This allows you to define the default behavior for each event insideyour custom View and determine whether the event should be passed on to some other child View. Again, these arecallbacks to the View class, so your only chance to define them is when youbuild a custom component.•Continue reading about handling user interaction with Views in theHandling UI Eventsdocument.MenusApplication menus are another important part of an application's UI. Menus offers a reliable interface that revealsapplication functions and settings. The most common application menu is revealed by pressing the MENU key on thedevice. However, you can also add Context Menus, which may be revealed when the user presses and holds down on anitem.Menus are also structured using a View hierarchy, but you don't define this structure yourself. Instead, you define theonCreateOptionsMenu()oronCreateContextMenu()callback methods for your Activity and declare the items thatyou want to include in your menu. At the appropriate time, Android will automatically create the necessary View hierarchyfor the menu and draw 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 anitem in your menu is selected, theonOptionsItemSelected()oronContextItemSelected()method will be calledby the framework.And just like your application layout, you have the option to declare the items for you menu in an XML file.ReadCreating Menusto learn more.Page3of4User Interface | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\index.html↑ Go to topAdvanced TopicsOnce you've grappled the fundamentals of creating a user interface, you can explore some advanced features forcreating a more complex application interface.AdaptersSometimes you'll want to populate a view group with some information that can't be hard-coded, instead, you want to bindyour view to an external source of data. To do this, you use an AdapterView as your view group and each child View isinitialized and populated with data from the Adapter.The AdapterView object is an implementation of ViewGroup that determines its child views based on a given Adapterobject. The Adapter acts like a courier between your data source (perhaps an array of external strings) and theAdapterView, which displays it. There are several implementations of the Adapter class, for specific tasks, such as theCursorAdapter 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, readBinding to Data with AdapterView.Styles and ThemesPerhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some of your ownstyles and themes.A style is a set of one or 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 Viewelements.•A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in an application, orjust a single activity. For example, you could define a theme that sets specific colors for the window frame and thepanel background, and sets text sizes and colors for menus. This theme can then be applied to specific activities orthe entire application.•Styles and themes are resources. Android provides some default style and theme resources that you can use, or you candeclare your own custom style and theme resources.Learn more about using styles and themes in theApplying Styles and Themesdocument.Except as noted, this content is licensed under Apache 2.0. For details and restrictions, see the Content License.Android 2.2 r1 - 14 May 2010 15:20Site Terms of Service-Privacy Policy-Brand Guidelines

Page4of4User Interface | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\index.htmlFor your convenience, the API referencedocumentation for UI related classes lists the availableXML attributes that correspond to the class methods,including inherited attributes.To learn more about the available XML elements andattributes, as well as the format of the XML file, seeLayout Resources.Write the XMLUsing Android's XML vocabulary, you can quickly design UIlayouts and the screen elements they contain, in the sameway you create web pages in HTML — with a series ofnested elements.Each layout file must contain exactly one root element, whichmust be a View or ViewGroup object. Once you've definedthe root element, you can add additional layout objects orwidgets as child elements to gradually build a View hierarchythat defines your layout. For example, here's an XML layoutthat uses a verticalLinearLayoutto hold aTextViewand aButton:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextView android:id="@+id/text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="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>After you've declared your layout in XML, save the file with the.xmlextension, in your Android project'sres/layout/

directory, so it will properly compile.We'll discuss each of the attributes shown here a little later.Load the XML ResourceWhen you compile your application, each XML layout file is compiled into aViewresource. You should load the layoutresource from your application code, in yourActivity.onCreate()callback implementation. Do so by callingsetContentView(), passing it the reference to your layout resource in the form of:R.layout.layout_file_name

For example, if your XML layout is saved asmain_layout.xml, you would load it for your Activity like so:public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView.(R.layout.main_layout);}TheonCreate()callback method in your Activity is calledby the Android framework when your Activity is launched (seethe discussion on Lifecycles, in theApplication Fundamentals, for more on this).Page2of5Declaring Layout | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\declaring-layout.htmlAttributesEvery View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a Viewobject (for example, TextView supports thetextSizeattribute), but these attributes are also inherited by any Viewobjects that may extend this class. Some are common to all View objects, because they are inherited from the root Viewclass (like theidattribute). And, other attributes are considered "layout parameters," which are attributes that describecertain layout orientations of the View object, as defined by that object's parent ViewGroup object.IDAny View object may have an integer ID associated with it, to uniquely identify the View within the tree. When theapplication is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as astring, in theidattribute. This is an XML attribute common to all View objects (defined by theViewclass) and you willuse it very often. The syntax for an ID, inside an XML tag is:android:id="@+id/my_button"The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the IDstring and identify it as an ID resource. The plus-symbol (+) means that this is a new resource name that must be createdand added to our resources (in theR.javafile). There are a number of other ID resources that are offered by theAndroid framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add theandroidpackage namespace, like so:android:id="@android:id/empty"With theandroidpackage namespace in place, we're now referencing an ID from theandroid.Rresources class,rather than the local resources class.In order to create views and reference them from the application, a common pattern is to:Define a view/widget in the layout file and assign it a unique ID: 1.<Button android:id="@+id/my_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/my_button_text"/>Then create an instance of the view object and capture it from the layout (typically in theonCreate()method):2.Button myButton = (Button) findViewById(R.id.my_button);Defining IDs for view objects is important when creating aRelativeLayout. In a relative layout, sibling views can definetheir layout relative to another sibling view, which is referenced by the unique ID.An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching(which may often be the entire tree, so it's best to be completely unique when possible).Layout ParametersXML layout attributes namedlayout_somethingdefine layout parameters for the View that are appropriate for theViewGroup in which it resides.Page3of5Declaring Layout | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\declaring-layout.html↑ Go to topSize, Padding and MarginsThe size of a view is expressed with a width and a height. A view actually possess two pairs of width and height values.The first pair is known as measured width and measured height. These dimensions define how big a view wants to bewithin its parent. The measured dimensions can be obtained bycallinggetMeasuredWidth()andgetMeasuredHeight().The second pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions

define the actual size of the view on screen, at drawing time and after layout. These values may, but do not have to, bedifferent from the measured width and height. The width and height can be obtained by callinggetWidth()andgetHeight().To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top,right and bottom 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 view's content by 2 pixels to the right of the left edge. Padding can be setusing thesetPadding(int, int, int, int)method and queried by callinggetPaddingLeft(),getPaddingTop(),getPaddingRight()andgetPaddingBottom().Even though a view can define a padding, it does not provide any support for margins. However, view groups providesuch a support. Refer toViewGroupandViewGroup.MarginLayoutParamsfor further information.For more information about dimensions, seeDimension Values.← Back to User InterfaceExcept as noted, this content is licensed underApache 2.0. For details

Page5of5Declaring Layout | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\declaring-layout.htmladds aMenuItem, and returns the newly created object to you. You can use thereturned MenuItem to set additional properties like an icon, a keyboard shortcut, anintent, and other settings for the item.There are multipleadd()methods. Usually, you'll want to use one that accepts anitemIdargument. This is a unique integer that allows you to identify the item during acallback.When a menu item is selected from the Options Menu, you will receive a callback totheonOptionsItemSelected()method of your Activity. This callback passesyou theMenuItemthat has been selected. You can identify the item by requestingtheitemId, withgetItemId(), which returns the integer that was assigned with theadd()method. Once you identify the menu item, you can take the appropriateaction.Here's an example of this procedure, inside an Activity, wherein we create anOptions 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(MenuItem item) {switch (item.getItemId()) {case MENU_NEW_GAME:newGame();return true;case MENU_QUIT:quit();return true;}return false;}Theadd()method used in this sample takes four arguments:groupId,itemId,order, andtitle. ThegroupIdallows you toassociate this menu item with a group of other items (more aboutMenu groups, below) — in this example, we ignore it.itemIdis a unique integer that we give the MenuItem so that can identify it in the next callback.orderallows us to definethe display order of the item — by default, they ar e displayed by the order in which we add them.titleis, of course, thename that goes on the menu item (this can also be astring resource, and we recommend you do it that way for easierlocalization).Tip: If you have several menu items that can be grouped together with a title, consider organizing them into aSubmenu.Adding iconsIcons can also be added to items that appears in the Icon Menu withsetIcon(). For example:menu.add(0, MENU_QUIT, 0, "Quit")

.setIcon(R.drawable.menu_quit_icon);Page2of8Creating Menus | Android Developers9/7/2010file://V:\android-sdk-windows\docs\guide\topics\ui\menus.htmlModifying the menuIf you want to sometimes re-write the Options Menu as it is opened, override the