1page.title=Application Fundamentals 2@jd:body 3 4<div id="qv-wrapper"> 5<div id="qv"> 6 7<h2>In this document</h2> 8<ol> 9<li><a href="#appcomp">Application Components</a> 10 <ol> 11 <li><a href="#actcomp">Activating components: intents</a></li> 12 <li><a href="#endcomp">Shutting down components</a></li> 13 <li><a href="#manfile">The manifest file</a></li> 14 <li><a href="#ifilters">Intent filters</a></li> 15 </ol></li> 16<li><a href="#acttask">Activities and Tasks</a> 17 <ol> 18 <li><a href="#afftask">Affinities and new tasks</a></li> 19 <li><a href="#lmodes">Launch modes</a></li> 20 <li><a href="#clearstack">Clearing the stack</a></li> 21 <li><a href="#starttask">Starting tasks</a></li> 22 </ol></li> 23<li><a href="#procthread">Processes and Threads</a> 24 <ol> 25 <li><a href="#procs">Processes</a></li> 26 <li><a href="#threads">Threads</a></li> 27 <li><a href="#rpc">Remote procedure calls</a></li> 28 <li><a href="#tsafe">Thread-safe methods</a></li> 29 </ol></li> 30<li><a href="#lcycles">Component Lifecycles</a> 31 <ol> 32 <li><a href="#actlife">Activity lifecycle</a></li> 33 <li><a href="#servlife">Service lifecycle</a></li> 34 <li><a href="#broadlife">Broadcast receiver lifecycle</a></li> 35 <li><a href="#proclife">Processes and lifecycles</a></li> 36 </ol></li> 37</ol> 38 39<h2>Key classes</h2> 40<ol> 41<li>{@link android.app.Activity}</li> 42<li>{@link android.app.Service}</li> 43<li>{@link android.content.BroadcastReceiver}</li> 44<li>{@link android.content.ContentProvider}</li> 45<li>{@link android.content.Intent}</li> 46</ol> 47 48</div> 49</div> 50 51<p> 52Android applications are written in the Java programming language. 53The compiled Java code — along with any data and resource 54files required by the application — is bundled by the 55<a href="{@docRoot}guide/developing/tools/aapt.html"><code>aapt</code> 56tool</a> into an <i>Android package</i>, an archive file 57marked by an {@code .apk} suffix. This file is the vehicle 58for distributing the application and installing it on mobile devices; 59it's the file users download to their devices. All the code in a 60single {@code .apk} file is considered to be one <i>application</i>. 61</p> 62 63<p> 64In many ways, each Android application lives in its own world: 65</p> 66 67<ul> 68<li>By default, every application runs in its own Linux process. 69Android starts the process when any of the application's code needs to be 70executed, and shuts down the process when it's no longer needed and system 71resources are required by other applications.</li> 72 73<li>Each process has its own virtual machine (VM), so application code 74runs in isolation from the code of all other applications.</li> 75 76<li>By default, each application is assigned a unique Linux user ID. 77Permissions are set so that the application's files are visible only to 78that user and only to the application itself — although there are ways 79to export them to other applications as well.</li> 80</ul> 81 82<p> 83It's possible to arrange for two applications to share the same user ID, 84in which case they will be able to see each other's files. To conserve 85system resources, applications with the same ID can also arrange to run 86in the same Linux process, sharing the same VM. 87</p> 88 89 90<h2 id="appcomp">Application Components</h2> 91 92<p> 93A central feature of Android is that one application can make use of elements 94of other applications (provided those applications permit it). For example, 95if your application needs to display a scrolling list of images and another 96application has developed a suitable scroller and made it available to others, 97you can call upon that scroller to do the work, rather than develop your own. 98Your application doesn't incorporate the code of the other application or 99link to it. Rather, it simply starts up that piece of the other application 100when the need arises. 101</p> 102 103<p> 104For this to work, the system must be able to start an application process 105when any part of it is needed, and instantiate the Java objects for that part. 106Therefore, unlike applications on most other systems, Android applications don't 107have a single entry point for everything in the application (no {@code main()} 108function, for example). Rather, they have essential <i>components</i> that 109the system can instantiate and run as needed. There are four types of components: 110</p> 111 112<dl> 113 114<dt><b>Activities</b></dt> 115<dd>An <i>activity</i> presents a visual user interface for one focused endeavor 116the user can undertake. For example, an activity might present a list of 117menu items users can choose from or it might display photographs along 118with their captions. A text messaging application might have one activity 119that shows a list of contacts to send messages to, a second activity to write 120the message to the chosen contact, and other activities to review old messages 121or change settings. Though they work together to form a cohesive user interface, 122each activity is independent of the others. 123Each one is implemented as a subclass of the {@link android.app.Activity} base class. 124 125<p> 126An application might consist of just one activity or, like the text messaging 127application just mentioned, it may contain several. 128What the activities are, and how many there are depends, of course, on the 129application and its design. Typically, one of the activities is marked 130as the first one that should be presented to the user when the application is 131launched. Moving from one activity to another is accomplished by having the 132current activity start the next one. 133</p> 134 135<p> 136Each activity is given a default window to draw in. Typically, the window 137fills the screen, but it might be smaller than the screen and float on top 138of other windows. An activity can also make use of additional windows — 139for example, a pop-up dialog that calls for a user response in the midst of 140the activity, or a window that presents users with vital information when they 141select a particular item on-screen. 142</p> 143 144<p> 145The visual content of the window is provided by a hierarchy of views — 146objects derived from the base {@link android.view.View} class. Each view 147controls a particular rectangular space within the window. Parent views 148contain and organize the layout of their children. Leaf views (those at the 149bottom of the hierarchy) draw in the rectangles they control and respond to 150user actions directed at that space. Thus, views are where the activity's 151interaction with the user takes place. For example, a view might display 152a small image and initiate an action when the user taps that image. Android 153has a number of ready-made views that you can use — including buttons, 154text fields, scroll bars, menu items, check boxes, and more. 155</p> 156 157<p> 158A view hierarchy is placed within an activity's window by the 159<code>{@link android.app.Activity#setContentView Activity.setContentView()}</code> 160method. The <i>content view</i> is the View object at the root of the hierarchy. 161(See the separate <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> 162document for more information on views and the hierarchy.) 163</p> 164 165<p><dt><b>Services</b></dt> 166<dd>A <i>service</i> doesn't have a visual user interface, but rather runs in 167the background for an indefinite period of time. For example, a service might 168play background music as the user attends to other matters, or it might fetch 169data over the network or calculate something and provide the result to activities 170that need it. Each service extends the {@link android.app.Service} base class. 171 172<p> 173A prime example is a media player playing songs from a play list. The player 174application would probably have one or more activities that allow the user to 175choose songs and start playing them. However, the music playback itself would 176not be handled by an activity because users will expect the music to keep 177playing even after they leave the player and begin something different. 178To keep the music going, the media player activity could start a service to run 179in the background. The system would then keep the music playback service running 180even after the activity that started it leaves the screen. 181</p> 182 183<p> 184It's possible to connect to (bind to) an ongoing service (and start the service 185if it's not already running). While connected, you can communicate with the 186service through an interface that the service exposes. For the music service, 187this interface might allow users to pause, rewind, stop, and restart the playback. 188</p> 189 190<p> 191Like activities and the other components, services run in the main thread of 192the application process. So that they won't block other components or the 193user interface, they often spawn another thread for time-consuming tasks 194(like music playback). See <a href="#procthread">Processes and Threads</a>, later. 195</p></dd> 196 197<dt><b>Broadcast receivers</b></dt> 198<dd>A <i>broadcast receiver</i> is a component that does nothing but 199receive and react to broadcast announcements. Many broadcasts originate in 200system code — for example, announcements that the timezone has changed, 201that the battery is low, that a picture has been taken, or that the user 202changed a language preference. Applications can also initiate broadcasts 203— for example, to let other applications know that some data has been 204downloaded to the device and is available for them to use. 205 206<p> 207An application can have any number of broadcast receivers to respond to any 208announcements it considers important. All receivers extend the {@link 209android.content.BroadcastReceiver} base class. 210</p> 211 212<p> 213Broadcast receivers do not display a user interface. However, they may start 214an activity in response to the information they receive, or they may use 215the {@link android.app.NotificationManager} to alert the user. Notifications 216can get the user's attention in various ways — flashing 217the backlight, vibrating the device, playing a sound, and so on. They 218typically place a persistent icon in the status bar, which users can open to 219get the message. 220</p></dd> 221 222<dt><b>Content providers</b></dt> 223<dd>A <i>content provider</i> makes a specific set of the application's data 224available to other applications. The data can be stored in the file system, 225in an SQLite database, or in any other manner that makes sense. 226The content provider extends the {@link android.content.ContentProvider} base 227class to implement a standard set of methods that enable other applications 228to retrieve and store data of the type it controls. However, applications 229do not call these methods directly. Rather they use a {@link 230android.content.ContentResolver} object and call its methods instead. 231A ContentResolver can talk to any content provider; it cooperates with the 232provider to manage any interprocess communication that's involved. 233 234<p> 235See the separate 236<a href="{@docRoot}guide/topics/providers/content-providers.html">Content 237Providers</a> document for more information on using content providers. 238</p></dd> 239 240</dl> 241 242<p> 243Whenever there's a request that should be handled by a particular component, 244Android makes sure that the application process of the component is running, 245starting it if necessary, and that an appropriate instance of the component 246is available, creating the instance if necessary. 247</p> 248 249 250<h3 id="actcomp">Activating components: intents</h3> 251 252<p> 253Content providers are activated when they're targeted by a request from a 254ContentResolver. The other three components — activities, services, 255and broadcast receivers — are activated by asynchronous messages 256called <i>intents</i>. An intent is an {@link android.content.Intent} 257object that holds the content of the message. For activities and services, 258it names the action being requested and specifies the URI of the data to 259act on, among other things. For example, it might convey a request for 260an activity to present an image to the user or let the user edit some 261text. For broadcast receivers, the Intent object names the action being 262announced. For example, it might announce to interested parties that the 263camera button has been pressed. 264</p> 265 266<p> 267There are separate methods for activating each type of component: 268</p> 269 270<ul> 271 272<li>An activity is launched (or given something new to do) by passing an 273Intent object to <code>{@link android.content.Context#startActivity 274Context.startActivity()}</code> or <code>{@link 275android.app.Activity#startActivityForResult 276Activity.startActivityForResult()}</code>. The responding activity can 277look at the initial intent that caused it to be launched by calling its 278<code>{@link android.app.Activity#getIntent getIntent()}</code> method. 279Android calls the activity's <code>{@link 280android.app.Activity#onNewIntent onNewIntent()}</code> method to pass 281it any subsequent intents. 282 283<p> 284One activity often starts the next one. If it expects a result back from 285the activity it's starting, it calls {@code startActivityForResult()} 286instead of {@code startActivity()}. For example, if it starts an activity 287that lets the user pick a photo, it might expect to be returned the chosen 288photo. The result is returned in an Intent object that's passed to the 289calling activity's <code>{@link android.app.Activity#onActivityResult 290onActivityResult()}</code> method. 291</p> 292</li> 293 294<li><p>A service is started (or new instructions are given to an ongoing 295service) by passing an Intent object to <code>{@link 296android.content.Context#startService Context.startService()}</code>. 297Android calls the service's <code>{@link android.app.Service#onStart 298onStart()}</code> method and passes it the Intent object.</p> 299 300<p> 301Similarly, an intent can be passed to <code>{@link 302android.content.Context#bindService Context.bindService()}</code> to 303establish an ongoing connection between the calling component and a 304target service. The service receives the Intent object in 305an <code>{@link android.app.Service#onBind onBind()}</code> call. 306(If the service is not already running, {@code bindService()} can 307optionally start it.) For example, an activity might establish a connection 308with the music playback service mentioned earlier so that it can provide 309the user with the means (a user interface) for controlling the playback. 310The activity would call {@code bindService()} to set up that connection, 311and then call methods defined by the service to affect the playback. 312</p> 313 314<p> 315A later section, <a href="#rpc">Remote procedure calls</a>, has more details 316about binding to a service. 317</p> 318</li> 319 320<li><p>An application can initiate a broadcast by passing an Intent object to 321methods like <code>{@link 322android.content.Context#sendBroadcast(Intent) Context.sendBroadcast()}</code>, 323<code>{@link android.content.Context#sendOrderedBroadcast(Intent, String) 324Context.sendOrderedBroadcast()}</code>, and <code>{@link 325android.content.Context#sendStickyBroadcast Context.sendStickyBroadcast()}</code> 326in any of their variations. Android delivers the intent to all interested 327broadcast receivers by calling their <code>{@link 328android.content.BroadcastReceiver#onReceive onReceive()}</code> methods.</p></li> 329 330</ul> 331 332<p> 333For more on intent messages, see the separate article, 334<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents 335and Intent Filters</a>. 336</p> 337 338 339<h3 id="endcomp">Shutting down components</h3> 340 341<p> 342A content provider is active only while it's responding to a request from 343a ContentResolver. And a broadcast receiver is active only while it's 344responding to a broadcast message. So there's no need to explicitly shut 345down these components. 346</p> 347 348<p> 349Activities, on the other hand, provide the user interface. They're 350in a long-running conversation with the user and may remain active, 351even when idle, as long as the conversation continues. Similarly, services 352may also remain running for a long time. So Android has methods to shut 353down activities and services in an orderly way: 354</p> 355 356<ul> 357<li>An activity can be shut down by calling its 358<code>{@link android.app.Activity#finish finish()}</code> method. One activity can 359shut down another activity (one it started with {@code startActivityForResult()}) by 360calling <code>{@link android.app.Activity#finishActivity finishActivity()}</code>.</li> 361 362<li>A service can be stopped by calling its 363<code>{@link android.app.Service#stopSelf stopSelf()}</code> method, or by calling 364<code>{@link android.content.Context#stopService Context.stopService()}</code>.</li> 365</ul> 366 367<p> 368Components might also be shut down by the system when they are no longer being 369used or when Android must reclaim memory for more active components. A later 370section, <a href="#lcycles">Component Lifecycles</a>, discusses this 371possibility and its ramifications in more detail. 372</p> 373 374 375<h3 id="manfile">The manifest file</h3> 376 377<p> 378Before Android can start an application component, it must learn that 379the component exists. Therefore, applications declare their components 380in a manifest file that's bundled into the Android package, the {@code .apk} 381file that also holds the application's code, files, and resources. 382</p> 383 384<p> 385The manifest is a structured XML file and is always named AndroidManifest.xml 386for all applications. It does a number of things in addition to declaring the 387application's components, such as naming any libraries the application needs 388to be linked against (besides the default Android library) and identifying 389any permissions the application expects to be granted. 390</p> 391 392<p> 393But the principal task of the manifest is to inform Android about the application's 394components. For example, an activity might be declared as follows: 395</p> 396 397<pre><?xml version="1.0" encoding="utf-8"?> 398<manifest . . . > 399 <application . . . > 400 <activity android:name="com.example.project.FreneticActivity" 401 android:icon="@drawable/small_pic.png" 402 android:label="@string/freneticLabel" 403 . . . > 404 </activity> 405 . . . 406 </application> 407</manifest></pre> 408 409<p> 410The {@code name} attribute of the 411<code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> 412element names the {@link android.app.Activity} subclass that implements the 413activity. The {@code icon} and {@code label} attributes point to 414resource files containing an icon and label that can be displayed 415to users to represent the activity. 416</p> 417 418<p> 419The other components are declared in a similar way — 420<code><a href="{@docRoot}guide/topics/manifest/service-element.html"><service></a></code> 421elements for services, 422<code><a href="{@docRoot}guide/topics/manifest/receiver-element.html"><receiver></a></code> 423elements for broadcast receivers, and 424<code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code> 425elements for content providers. Activities, services, and content providers 426that are not declared in the manifest are not visible to the system and are 427consequently never run. However, broadcast receivers can either be 428declared in the manifest, or they can be created dynamically in code 429(as {@link android.content.BroadcastReceiver} objects) 430and registered with the system by calling 431<code>{@link android.content.Context#registerReceiver Context.registerReceiver()}</code>. 432</p> 433 434<p> 435For more on how to structure a manifest file for your application, see 436<a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The 437AndroidManifest.xml File</a>. 438</p> 439 440 441<h3 id="ifilters">Intent filters</h3> 442 443<p> 444An Intent object can explicitly name a target component. If it does, 445Android finds that component (based on the declarations in the manifest 446file) and activates it. But if a target is not explicitly named, 447Android must locate the best component to respond to the intent. 448It does so by comparing the Intent object to the <i>intent filters</i> 449of potential targets. A component's intent filters inform Android of 450the kinds of intents the component is able to handle. Like other 451essential information about the component, they're declared in the 452manifest file. Here's an extension of the previous example that adds 453two intent filters to the activity: 454</p> 455 456<pre><?xml version="1.0" encoding="utf-8"?> 457<manifest . . . > 458 <application . . . > 459 <activity android:name="com.example.project.FreneticActivity" 460 android:icon="@drawable/small_pic.png" 461 android:label="@string/freneticLabel" 462 . . . > 463 <intent-filter . . . > 464 <action android:name="android.intent.action.MAIN" /> 465 <category android:name="android.intent.category.LAUNCHER" /> 466 </intent-filter> 467 <intent-filter . . . > 468 <action android:name="com.example.project.BOUNCE" /> 469 <data android:mimeType="image/jpeg" /> 470 <category android:name="android.intent.category.DEFAULT" /> 471 </intent-filter> 472 </activity> 473 . . . 474 </application> 475</manifest></pre> 476 477<p> 478The first filter in the example — the combination of the action 479"{@code android.intent.action.MAIN}" and the category 480"{@code android.intent.category.LAUNCHER}" — is a common one. 481It marks the activity as one that should be represented in the 482application launcher, the screen listing applications users can launch 483on the device. In other words, the activity is the entry point for 484the application, the initial one users would see when they choose 485the application in the launcher. 486</p> 487 488<p> 489The second filter declares an action that the activity can perform on 490a particular type of data. 491</p> 492 493<p> 494A component can have any number of intent filters, each one declaring a 495different set of capabilities. If it doesn't have any filters, it can 496be activated only by intents that explicitly name the component as the 497target. 498</p> 499 500<p> 501For a broadcast receiver that's created and registered in code, the 502intent filter is instantiated directly as an {@link android.content.IntentFilter} 503object. All other filters are set up in the manifest. 504</p> 505 506<p> 507For more on intent filters, see a separate document, 508<a href="{@docRoot}guide/topics/intents/intents-filters.html">Intents 509and Intent Filters</a>. 510</p> 511 512 513<h2 id="acttask">Activities and Tasks</h2> 514 515<p> 516As noted earlier, one activity can start another, including one defined 517in a different application. Suppose, for example, that you'd like 518to let users display a street map of some location. There's already an 519activity that can do that, so all your activity needs to do is put together 520an Intent object with the required information and pass it to 521{@code startActivity()}. The map viewer will display the map. When the user 522hits the BACK key, your activity will reappear on screen. 523</p> 524 525<p> 526To the user, it will seem as if the map viewer is part of the same application 527as your activity, even though it's defined in another application and runs in 528that application's process. Android maintains this user experience by keeping 529both activities in the same <i>task</i>. Simply put, a task is what the user 530experiences as an "application." It's a group of related activities, arranged 531in a stack. The root activity in the stack is the one that began the task 532— typically, it's an activity the user selected in the application launcher. 533The activity at the top of the stack is one that's currently running — 534the one that is the focus for user actions. When one activity starts another, 535the new activity is pushed on the stack; it becomes the running activity. 536The previous activity remains in the stack. When the user presses the BACK key, 537the current activity is popped from the stack, and the previous one resumes as 538the running activity. 539</p> 540 541<p> 542The stack contains objects, so if a task has more than one instance of the same 543Activity subclass open — multiple map viewers, for example — the 544stack has a separate entry for each instance. Activities in the stack are never 545rearranged, only pushed and popped. 546</p> 547 548<p> 549A task is a stack of activities, not a class or an element in the manifest file. 550So there's no way to set values for a task independently of its activities. 551Values for the task as a whole are set in the root activity. For example, the 552next section will talk about the "affinity of a task"; that value is read from 553the affinity set for the task's root activity. 554</p> 555 556<p> 557All the activities in a task move together as a unit. The entire task (the entire 558activity stack) can be brought to the foreground or sent to the background. 559Suppose, for instance, that the current task has four activities in its stack 560— three under the current activity. The user presses the HOME key, goes 561to the application launcher, and selects a new application (actually, a new <i>task</i>). 562The current task goes into the background and the root activity for the new task is displayed. 563Then, after a short period, the user goes back to the home screen and again selects 564the previous application (the previous task). That task, with all four 565activities in the stack, comes forward. When the user presses the BACK 566key, the screen does not display the activity the user just left (the root 567activity of the previous task). Rather, the activity on the top of the stack 568is removed and the previous activity in the same task is displayed. 569</p> 570 571<p> 572The behavior just described is the default behavior for activities and tasks. 573But there are ways to modify almost all aspects of it. The association of 574activities with tasks, and the behavior of an activity within a task, is 575controlled by the interaction between flags set in the Intent object that 576started the activity and attributes set in the activity's 577<code><a href="{@docRoot}guide/topics/manifest/activity-element.html"><activity></a></code> 578element in the manifest. Both requester and respondent have a say in what happens. 579</p> 580 581<p> 582In this regard, the principal Intent flags are: 583 584<p style="margin-left: 2em">{@code FLAG_ACTIVITY_NEW_TASK} 585<br/>{@code FLAG_ACTIVITY_CLEAR_TOP} 586<br/>{@code FLAG_ACTIVITY_RESET_TASK_IF_NEEDED} 587<br/>{@code FLAG_ACTIVITY_SINGLE_TOP}</p> 588 589<p> 590The principal {@code <activity>} attributes are: 591 592<p style="margin-left: 2em">{@code taskAffinity} 593<br/>{@code launchMode} 594<br/>{@code allowTaskReparenting} 595<br/>{@code clearTaskOnLaunch} 596<br/>{@code alwaysRetainTaskState} 597<br/>{@code finishOnTaskLaunch}</p> 598 599<p> 600The following sections describe what some of these flags and attributes do, 601how they interact, and what considerations should govern their use. 602</p> 603 604 605<h3 id="afftask">Affinities and new tasks</h3> 606 607<p> 608By default, all the activities in an application have an <i>affinity</i> for each 609other — that is, there's a preference for them all to belong to the 610same task. However, an individual affinity can be set for each activity 611with the {@code taskAffinity} attribute of the {@code <activity>} element. 612Activities defined in different applications can share an affinity, or activities 613defined in the same application can be assigned different affinities. 614The affinity comes into play in two circumstances: When the Intent object 615that launches an activity contains the {@code FLAG_ACTIVITY_NEW_TASK} flag, 616and when an activity has its {@code allowTaskReparenting} attribute set 617to "{@code true}". 618</p> 619 620<dl> 621<dt>The <code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag</dt> 622<dd>As described earlier, a new activity is, by default, launched into 623the task of the activity that called {@code startActivity()}. It's pushed 624 onto the same stack as the caller. However, if the Intent object passed 625to {@code startActivity()} contains the {@code FLAG_ACTIVITY_NEW_TASK} 626flag, the system looks for a different task to house the new activity. 627Often, as the name of the flag implies, it's a new task. However, it 628doesn't have to be. If there's already an existing task with the same 629affinity as the new activity, the activity is launched into that task. If 630not, it begins a new task.</dd> 631 632<dt>The <code><a 633href="{@docRoot}guide/topics/manifest/activity-element.html#reparent">allowTaskReparenting</a></code> 634attribute</dt> 635<dd>If an activity has its {@code allowTaskReparenting} attribute set 636to "{@code true}", it can move from the task it starts in to the task 637it has an affinity for when that task comes to the fore. For example, 638suppose that an activity that reports weather conditions in selected 639cities is defined as part of a travel application. It has the same 640affinity as other activities in the same application (the default 641affinity) and it allows reparenting. One of your activities 642starts the weather reporter, so it initially belongs to the same task as 643your activity. However, when the travel application next comes forward, 644the weather reporter will be reassigned to and displayed with that task.</dd> 645</dl> 646 647<p> 648If an {@code .apk} file contains more than one "application" 649from the user's point of view, you will probably want to assign different 650affinities to the activities associated with each of them. 651</p> 652 653 654<h3 id="lmodes">Launch modes</h3> 655 656<p> 657There are four different launch modes that can be assigned to an {@code 658<activity>} element's 659<code><a href="{@docRoot}guide/topics/manifest/activity-element.html#lmode">launchMode</a></code> 660attribute: 661</p> 662 663<p style="margin-left: 2em">"{@code standard}" (the default mode) 664<br>"{@code singleTop}" 665<br>"{@code singleTask}" 666<br>"{@code singleInstance}"</p> 667 668<p> 669The modes differ from each other on these four points: 670</p> 671 672<ul> 673 674<li><b>Which task will hold the activity that responds to the intent</b>. 675For the "{@code standard}" and "{@code singleTop}" modes, it's the task that 676originated the intent (and called 677<code>{@link android.content.Context#startActivity startActivity()}</code>) 678— unless the Intent object contains the 679<code>{@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK}</code> flag. 680In that case, a different task is chosen as described in the previous 681section, <a href="#afftask">Affinities and new tasks</a>. 682 683<p> 684In contrast, the "{@code singleTask}" and "{@code singleInstance}" modes mark 685activities that are always at the root of a task. They define a task; they're 686never launched into another task. 687</p> 688 689<li><p><b>Whether there can be multiple instances of the activity</b>. 690A "{@code standard}" or "{@code singleTop}" activity can be instantiated 691many times. They can belong to multiple tasks, and a given task can have 692multiple instances of the same activity. 693</p> 694 695<p> 696In contrast, "{@code singleTask}" and "{@code singleInstance}" activities 697are limited to just one instance. Since these activities are at the root 698of a task, this limitation means that there is never more than a single 699instance of the task on the device at one time. 700</p> 701 702<li><p><b>Whether the instance can have other activities in its task</b>. 703A "{@code singleInstance}" activity stands alone as the only activity in its 704task. If it starts another activity, that activity will be launched into a 705different task regardless of its launch mode — as if {@code 706FLAG_ACTIVITY_NEW_TASK} was in the intent. In all other respects, the 707"{@code singleInstance}" mode is identical to "{@code singleTask}".</p> 708 709<p> 710The other three modes permit multiple activities to belong to the task. 711A "{@code singleTask}" activity will always be the root activity of the task, 712but it can start other activities that will be assigned to its 713task. Instances of "{@code standard}" and "{@code singleTop}" 714activities can appear anywhere in a stack. 715</p></li> 716 717<li><b>Whether a new instance of the class will be launched 718to handle a new intent</b>. For the default "{@code standard}" mode, a 719new instance is created to respond to every new intent. Each instance 720handles just one intent. For the "{@code singleTop}" mode, an existing 721instance of the class is re-used to handle a new intent if it resides 722at the top of the activity stack of the target task. If it does not 723reside at the top, it is not re-used. Instead, a new instance 724is created for the new intent and pushed on the stack. 725 726<p> 727For example, suppose a task's activity stack consists of root activity A with 728activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent 729arrives for an activity of type D. If D has the default "{@code standard}" launch 730mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. 731However, if D's launch mode is "{@code singleTop}", the existing instance is 732expected to handle the new intent (since it's at the top of the stack) and the 733stack remains A-B-C-D. 734</p> 735 736<p> 737If, on the other hand, the arriving intent is for an activity of type B, a new 738instance of B would be launched no matter whether B's mode is "{@code standard}" 739or "{@code singleTop}" (since B is not at the top of the stack), so the resulting 740stack would be A-B-C-D-B. 741</p> 742 743<p> 744As noted above, there's never more than one instance of a "{@code singleTask}" 745or "{@code singleInstance}" activity, so that instance is expected to handle 746all new intents. A "{@code singleInstance}" activity is always at the top of 747the stack (since it is the only activity in the task), so it is always in 748position to handle the intent. However, a "{@code singleTask}" activity may 749or may not have other activities above it in the stack. If it does, it is not 750in position to handle the intent, and the intent is dropped. (Even though the 751intent is dropped, its arrival would have caused the task to come to the 752foreground, where it would remain.) 753</p> 754</li> 755 756</ul> 757 758<p> 759When an existing activity is asked to handle a new intent, the Intent 760object is passed to the activity in an 761<code>{@link android.app.Activity#onNewIntent onNewIntent()}</code> call. 762(The intent object that originally started the activity can be retrieved by 763calling <code>{@link android.app.Activity#getIntent getIntent()}</code>.) 764</p> 765 766<p> 767Note that when a new instance of an Activity is created to handle a new 768intent, the user can always press the BACK key to return to the previous state 769(to the previous activity). But when an existing instance of an 770Activity handles a new intent, the user cannot press the BACK key to 771return to what that instance was doing before the new intent arrived. 772</p> 773 774<p> 775For more on launch modes, see the description of the <code><a 776href="{@docRoot}guide/topics/manifest/activity-element.html#lmode"><activity></a></code> 777element. 778</p> 779 780 781<h3 id="clearstack">Clearing the stack</h3> 782 783<p> 784If the user leaves a task for a long time, the system clears the task of all 785activities except the root activity. When the user returns to the task again, 786it's as the user left it, except that only the initial activity is present. 787The idea is that, after 788a time, users will likely have abandoned what they were doing before and are 789returning to the task to begin something new. 790</p> 791 792<p> 793That's the default. There are some activity attributes that can be used to 794control this behavior and modify it: 795</p> 796 797<dl> 798<dt>The <code><a 799href="{@docRoot}guide/topics/manifest/activity-element.html#always">alwaysRetainTaskState</a></code> 800attribute</dt> 801<dd>If this attribute is set to "{@code true}" in the root activity of a task, 802the default behavior just described does not happen. 803The task retains all activities in its stack even after a long period.</dd> 804 805<dt>The <code><a 806href="{@docRoot}guide/topics/manifest/activity-element.html#clear">clearTaskOnLaunch</a></code> 807attribute</dt> 808<dd>If this attribute is set to "{@code true}" in the root activity of a task, 809the stack is cleared down to the root activity whenever the user leaves the task 810and returns to it. In other words, it's the polar opposite of 811{@code alwaysRetainTaskState}. The user always returns to the task in its 812initial state, even after a momentary absence.</dd> 813 814<dt>The <code><a 815href="{@docRoot}guide/topics/manifest/activity-element.html#finish">finishOnTaskLaunch</a></code> 816attribute</dt> 817<dd>This attribute is like {@code clearTaskOnLaunch}, but it operates on a 818single activity, not an entire task. And it can cause any activity to go 819away, including the root activity. When it's set to "{@code true}", the 820activity remains part of the task only for the current session. If the user 821leaves and then returns to the task, it no longer is present.</dd> 822</dl> 823 824<p> 825There's another way to force activities to be removed from the stack. 826If an Intent object includes the <code>{@link 827android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_CLEAR_TOP}</code> 828flag, and the target task already has an instance of the type of activity that 829should handle the intent in its stack, all activities above that instance 830are cleared away so that it stands at the top of the stack and can respond 831to the intent. 832If the launch mode of the designated activity is "{@code standard}", it too 833will be removed from the stack, and a new instance will be launched to handle 834the incoming intent. That's because a new instance is always created for 835a new intent when the launch mode is "{@code standard}". 836</p> 837 838<p> 839{@code FLAG_ACTIVITY_CLEAR_TOP} is most often used in conjunction 840with {@code FLAG_ACTIVITY_NEW_TASK}. When used together, these flags are 841a way of locating an existing activity in another task and putting it in 842a position where it can respond to the intent. 843</p> 844 845 846<h3 id="starttask">Starting tasks</h3> 847 848<p> 849An activity is set up as the entry point for a task by giving it 850an intent filter with "{@code android.intent.action.MAIN}" as the 851specified action and "{@code android.intent.category.LAUNCHER}" as 852the specified category. (There's an example of this type of filter 853in the earlier <a href="#ifilters">Intent Filters</a> section.) 854A filter of this kind causes an icon and label for the activity to be 855displayed in the application launcher, giving users a way both to 856launch the task and to return to it at any time after it has been 857launched. 858</p> 859 860<p> 861This second ability is important: Users must be able to leave a task 862and then come back to it later. For this reason, the two launch modes 863that mark activities as always initiating a task, "{@code singleTask}" 864and "{@code singleInstance}", should be used only when the activity has 865a {@code MAIN} and {@code LAUNCHER} filter. 866Imagine, for example, what could happen if the filter is missing: 867An intent launches a "{@code singleTask}" activity, initiating a new task, 868and the user spends some time working in that task. The user then presses 869the HOME key. The task is now ordered behind and obscured by the home 870screen. And, because it is not represented in the application launcher, 871the user has no way to return to it. 872</p> 873 874<p> 875A similar difficulty attends the {@code FLAG_ACTIVITY_NEW_TASK} flag. 876If this flag causes an activity to 877begin a new task and the user presses the HOME key to leave it, there 878must be some way for the user to navigate back to it again. Some 879entities (such as the notification manager) always start activities 880in an external task, never as part of their own, so they always put 881{@code FLAG_ACTIVITY_NEW_TASK} in the intents they pass to 882{@code startActivity()}. If you have an activity that can be invoked 883by an external entity that might use this flag, take care that the user 884has a independent way to get back to the task that's started. 885</p> 886 887<p> 888For those cases where you don't want the user to be able to return 889to an activity, set the {@code <activity>} element's {@code 890finishOnTaskLaunch} to "{@code true}". 891See <a href="#clearstack">Clearing the stack</a>, earlier. 892</p> 893 894 895<h2 id="procthread">Processes and Threads</h2> 896 897<p> 898When the first of an application's components needs to be run, Android 899starts a Linux process for it with a single thread of execution. By default, 900all components of the application run in that process and thread. 901</p> 902 903<p> 904However, you can arrange for components to run in other processes, and you 905can spawn additional threads for any process. 906</p> 907 908 909<h3 id="procs">Processes</h3> 910 911<p> 912The process where a component runs is controlled by the manifest file. 913The component elements — {@code <activity>}, 914{@code <service>}, {@code <receiver>}, and {@code <provider>} 915— each have a {@code process} attribute that can specify a process 916where that component should run. These attributes can be set so that each 917component runs in its own process, or so that some components share a process 918while others do not. They can also be set so that components of 919different applications run in the same process — provided that the 920applications share the same Linux user ID and are signed by the same authorities. 921The {@code <application>} element also has a {@code process} attribute, 922for setting a default value that applies to all components. 923</p> 924 925<p> 926All components are instantiated in the main thread of the specified 927process, and system calls to the component are dispatched from that 928thread. Separate threads are not created for each instance. Consequently, 929methods that respond to those calls — methods like 930<code>{@link android.view.View#onKeyDown View.onKeyDown()}</code> that report 931user actions and the lifecycle notifications discussed later in the 932<a href="#lcycles">Component Lifecycles</a> section — always run in the 933main thread of the process. This means 934that no component should perform long or blocking operations (such as networking 935operations or computation loops) when called by the system, since this will block 936any other components also in the process. You can spawn separate threads for 937long operations, as discussed under <a href="#threads">Threads</a>, next. 938</p> 939 940<p> 941Android may decide to shut down a process at some point, when memory is 942low and required by other processes that are more immediately serving 943the user. Application components running in the process are consequently 944destroyed. A process is restarted for those components when there's again 945work for them to do. 946</p> 947 948<p> 949When deciding which processes to terminate, Android weighs their relative 950importance to the user. For example, it more readily shuts down a process 951with activities that are no longer visible on screen than a process with 952visible activities. 953The decision whether to terminate a process, therefore, depends on the state 954of the components running in that process. Those states are the subject of 955a later section, <a href="#lcycles">Component Lifecycles</a>. 956</p> 957 958 959<h3 id="threads">Threads</h3> 960 961<p> 962Even though you may confine your application to a single process, there will 963likely be times when you will need to spawn a thread to do some background 964work. Since the user interface must always be quick to respond to user actions, 965the thread that hosts an activity should not also host time-consuming operations 966like network downloads. Anything that may not be completed quickly should be 967assigned to a different thread. 968</p> 969 970<p> 971Threads are created in code using standard Java {@link java.lang.Thread} 972objects. Android provides a number of convenience classes for managing 973threads — {@link android.os.Looper} for running a message loop within 974a thread, {@link android.os.Handler} for processing messages, and 975{@link android.os.HandlerThread} for setting up a thread with a message loop. 976</p> 977 978 979<h3 id="rpc">Remote procedure calls</h3> 980 981<p> 982Android has a lightweight mechanism for remote procedure calls (RPCs) 983— where a method is called locally, but executed remotely (in another 984process), with any result returned back to the caller. 985This entails decomposing the method call and all its attendant data to a 986level the operating system can understand, transmitting it from the local 987process and address space to the remote process and address space, and 988reassembling and reenacting the call there. Return values have to be 989transmitted in the opposite direction. Android provides all the code 990to do that work, so that you can concentrate on defining and implementing 991the RPC interface itself. 992</p> 993 994<p> 995An RPC interface can include only methods. By default, 996all methods are executed synchronously (the local method blocks until the 997remote method finishes), even if there is no return value. 998</p> 999 1000<p> 1001In brief, the mechanism works as follows: You'd begin by declaring the 1002RPC interface you want to implement using a simple IDL (interface definition 1003language). From that declaration, the 1004<code><a href="{@docRoot}guide/developing/tools/aidl.html">aidl</a></code> 1005tool generates a Java interface definition that must be made available to 1006both the local and the remote process. It contains two inner class, as shown 1007in the following diagram: 1008</p> 1009 1010<p style="margin-left: 2em"> 1011<img src="{@docRoot}images/binder_rpc.png" alt="RPC mechanism." /> 1012</p> 1013 1014<p> 1015The inner classes have all the code needed to administer remote procedure 1016calls for the interface you declared with the IDL. 1017Both inner classes implement the {@link android.os.IBinder} 1018interface. One of them is used locally and internally by the system; 1019the code you write can ignore it. 1020The other, called Stub, extends the {@link android.os.Binder} 1021class. In addition to internal code for effectuating the IPC calls, it 1022contains declarations for the methods in the RPC interface you declared. 1023You would subclass Stub to implement those methods, as indicated in the 1024diagram. 1025</p> 1026 1027<p> 1028Typically, the remote process would be managed by a service (because a 1029service can inform the system about the process and its connections to 1030other processes). It would have both the interface file generated by 1031the {@code aidl} tool and the Stub subclass implementing the 1032RPC methods. Clients of the service would have only the interface file 1033generated by the {@code aidl} tool. 1034</p> 1035 1036<p> 1037Here's how a connection between a service and its clients is set up: 1038</p> 1039 1040<ul> 1041<li>Clients of the service (on the local side) would implement 1042<code>{@link android.content.ServiceConnection#onServiceConnected 1043onServiceConnected()}</code> and 1044<code>{@link android.content.ServiceConnection#onServiceDisconnected 1045onServiceDisconnected()}</code> methods so they can be notified 1046when a successful connection to the remote service is established, and 1047when it goes away. They would then call 1048<code>{@link android.content.Context#bindService bindService()}</code> 1049to set up the connection. 1050</li> 1051 1052<li> 1053The service's <code>{@link android.app.Service#onBind onBind()}</code> 1054method would be implemented to either accept or reject the connection, 1055depending on the intent it receives (the intent passed to 1056{@code bindService()}). If the connection is accepted, it returns 1057an instance of the Stub subclass. 1058</li> 1059 1060<li>If the service accepts the connection, Android calls the 1061client's {@code onServiceConnected()} method and passes it an IBinder 1062object, a proxy for the Stub subclass managed by the service. Through 1063the proxy, the client can make calls on the remote service. 1064</li> 1065</ul> 1066 1067<p> 1068This brief description omits some details of the RPC mechanism. For more 1069information, see 1070<a href="{@docRoot}guide/developing/tools/aidl.html">Designing a Remote 1071Interface Using AIDL</a> and the {@link android.os.IBinder IBinder} class 1072description. 1073</p> 1074 1075 1076<h3 id="tsafe">Thread-safe methods</h3> 1077 1078<p> 1079In a few contexts, the methods you implement may be called from more 1080than one thread, and therefore must be written to be thread-safe. 1081</p> 1082 1083<p> 1084This is primarily true for methods that can be called remotely — 1085as in the RPC mechanism discussed in the previous section. 1086When a call on a method implemented in an IBinder object originates 1087in the same process as the IBinder, the method is executed in the 1088caller's thread. However, when the call originates in another process, 1089the method is executed in a thread chosen from a pool of threads that 1090Android maintains in the same process as the IBinder; it's not executed 1091in the main thread of the process. For example, whereas a service's 1092{@code onBind()} method would be called from the main thread of the 1093service's process, methods implemented in the object that {@code onBind()} 1094returns (for example, a Stub subclass that implements RPC methods) would 1095be called from threads in the pool. 1096Since services can have more than one client, more than one pool thread 1097can engage the same IBinder method at the same time. IBinder methods 1098must, therefore, be implemented to be thread-safe. 1099</p> 1100 1101<p> 1102Similarly, a content provider can receive data requests that originate in 1103other processes. Although the ContentResolver and ContentProvider classes 1104hide the details of how the interprocess communication is managed, 1105ContentProvider methods that respond to those requests — the methods 1106<code>{@link android.content.ContentProvider#query query()}</code>, 1107<code>{@link android.content.ContentProvider#insert insert()}</code>, 1108<code>{@link android.content.ContentProvider#delete delete()}</code>, 1109<code>{@link android.content.ContentProvider#update update()}</code>, and 1110<code>{@link android.content.ContentProvider#getType getType()}</code> 1111— are called from a pool of threads in the content provider's 1112process, not the main thread of the process. Since these methods 1113may be called from any number of threads at the same time, they too must 1114be implemented to be thread-safe. 1115</p> 1116 1117 1118<h2 id="lcycles">Component Lifecycles</h2> 1119 1120<p> 1121Application components have a lifecycle — a beginning when 1122Android instantiates them to respond to intents through to an end when 1123the instances are destroyed. In between, they may sometimes be active 1124or inactive,or, in the case of activities, visible to the user or 1125invisible. This section discusses the lifecycles of activities, 1126services, and broadcast receivers — including the states that they 1127can be in during their lifetimes, the methods that notify you of transitions 1128between states, and the effect of those states on the possibility that 1129the process hosting them might be terminated and the instances destroyed. 1130</p> 1131 1132 1133<h3 id="actlife">Activity lifecycle</h3> 1134 1135<p>An activity has essentially three states:</p> 1136 1137<ul> 1138<li> It is <em>active</em> or <em>running</em> when it is in the foreground of the 1139screen (at the top of the activity stack for the current task). This is the 1140activity that is the focus for the user's actions.</li> 1141 1142<li><p>It is <em>paused</em> if it has lost focus but is still visible to the user. 1143That is, another activity lies on top of it and that activity either is transparent 1144or doesn't cover the full screen, so some of the paused activity can show through. 1145A paused activity is completely alive (it maintains all state and member information 1146and remains attached to the window manager), but can be killed by the system in 1147extreme low memory situations.</p></li> 1148 1149<li><p>It is <em>stopped</em> if it is completely obscured by another activity. 1150It still retains all state and member information. However, it is no longer 1151visible to the user so its window is hidden and it will often be killed by the 1152system when memory is needed elsewhere.</p></li> 1153</ul> 1154 1155<p> 1156If an activity is paused or stopped, the system can drop it from memory either 1157by asking it to finish (calling its {@link android.app.Activity#finish finish()} 1158method), or simply killing its process. When it is displayed again 1159to the user, it must be completely restarted and restored to its previous state. 1160</p> 1161 1162<p> 1163As an activity transitions from state to state, it is notified of the change 1164by calls to the following protected methods: 1165</p> 1166 1167<p style="margin-left: 2em">{@code void onCreate(Bundle <i>savedInstanceState</i>)} 1168<br/>{@code void onStart()} 1169<br/>{@code void onRestart()} 1170<br/>{@code void onResume()} 1171<br/>{@code void onPause()} 1172<br/>{@code void onStop()} 1173<br/>{@code void onDestroy()}</p> 1174 1175<p> 1176All of these methods are hooks that you can override to do appropriate work 1177when the state changes. All activities must implement 1178<code>{@link android.app.Activity#onCreate onCreate()}</code> to do the 1179initial setup when the object is first instantiated. 1180Many will also implement <code>{@link android.app.Activity#onPause onPause()}</code> 1181to commit data changes and otherwise prepare to stop interacting with the user. 1182</p> 1183 1184<div class="sidebox-wrapper"> 1185<div class="sidebox"> 1186<h2>Calling into the superclass</h2> 1187<p> 1188An implementation of any activity lifecycle method should always first 1189call the superclass version. For example: 1190</p> 1191 1192<pre>protected void onPause() { 1193 super.onPause(); 1194 . . . 1195}</pre> 1196</div> 1197</div> 1198 1199 1200<p> 1201Taken together, these seven methods define the entire lifecycle of an 1202activity. There are three nested loops that you can monitor by 1203implementing them: 1204</p> 1205 1206<ul> 1207<li>The <b>entire lifetime</b> of an activity happens between the first call 1208to <code>{@link android.app.Activity#onCreate onCreate()}</code> through to a 1209single final call to <code>{@link android.app.Activity#onDestroy}</code>. 1210An activity does all its initial setup of "global" state in {@code onCreate()}, 1211and releases all remaining resources in {@code onDestroy()}. For example, 1212if it has a thread running in the background to download data from the network, 1213it may create that thread in {@code onCreate()} and then stop the thread in 1214{@code onDestroy()}.</li> 1215 1216<li><p>The <b>visible lifetime</b> of an activity happens between a call to 1217<code>{@link android.app.Activity#onStart onStart()}</code> until a 1218corresponding call to <code>{@link android.app.Activity#onStop onStop()}</code>. 1219During this time, the user can see the activity on-screen, though it may not 1220be in the foreground and interacting with the user. Between these two methods, 1221you can maintain resources that are needed to show the activity to the user. 1222For example, you can register a {@link android.content.BroadcastReceiver} in 1223{@code onStart()} to monitor for changes that impact your UI, and unregister 1224it in {@code onStop()} when the user can no longer see what you are displaying. 1225The {@code onStart()} and {@code onStop()} methods can be called multiple times, 1226as the activity alternates between being visible and hidden to the user.</p></li> 1227 1228<li><p>The <b>foreground lifetime</b> of an activity happens between a call 1229to <code>{@link android.app.Activity#onResume onResume()}</code> until a 1230corresponding call to <code>{@link android.app.Activity#onPause onPause()}</code>. 1231During this time, the activity is in front of all other activities on screen and 1232is interacting with the user. An activity can frequently transition between the 1233resumed and paused states — for example, {@code onPause()} is called when 1234the device goes to sleep or when a new activity is started, {@code onResume()} 1235is called when an activity result or a new intent is delivered. Therefore, the 1236code in these two methods should be fairly lightweight.</p></li> 1237</ul> 1238 1239<p> 1240The following diagram illustrates these loops and the paths an activity 1241may take between states. The colored ovals are major states the activity 1242can be in. The square rectangles represent the callback methods you can implement 1243to perform operations when the activity transitions between states. 1244<p> 1245 1246<p style="margin-left: 2em"><img src="{@docRoot}images/activity_lifecycle.png" 1247alt="State diagram for an Android activity lifecycle." /></p> 1248 1249<p> 1250The following table describes each of these methods in more detail and 1251locates it within the activity's overall lifecycle: 1252</p> 1253 1254<table border="2" width="85%" frame="hsides" rules="rows"> 1255<colgroup align="left" span="3"></colgroup> 1256<colgroup align="left"></colgroup> 1257<colgroup align="center"></colgroup> 1258<colgroup align="center"></colgroup> 1259 1260<thead> 1261<tr><th colspan="3">Method</th> <th>Description</th> <th>Killable?</th> <th>Next</th></tr> 1262</thead> 1263 1264<tbody> 1265<tr> 1266 <td colspan="3" align="left"><code>{@link android.app.Activity#onCreate onCreate()}</code></td> 1267 <td>Called when the activity is first created. 1268 This is where you should do all of your normal static set up — 1269 create views, bind data to lists, and so on. This method is passed 1270 a Bundle object containing the activity's previous state, if that 1271 state was captured (see <a href="#actstate">Saving Activity State</a>, 1272 later). 1273 <p>Always followed by {@code onStart()}.</p></td> 1274 <td align="center">No</td> 1275 <td align="center">{@code onStart()}</td> 1276</tr> 1277 1278<tr> 1279 <td rowspan="5" style="border-left: none; border-right: none;"> </td> 1280 <td colspan="2" align="left"><code>{@link android.app.Activity#onRestart 1281onRestart()}</code></td> 1282 <td>Called after the activity has been stopped, just prior to it being 1283 started again. 1284 <p>Always followed by {@code onStart()}</p></td> 1285 <td align="center">No</td> 1286 <td align="center">{@code onStart()}</td> 1287</tr> 1288 1289<tr> 1290 <td colspan="2" align="left"><code>{@link android.app.Activity#onStart onStart()}</code></td> 1291 <td>Called just before the activity becomes visible to the user. 1292 <p>Followed by {@code onResume()} if the activity comes 1293 to the foreground, or {@code onStop()} if it becomes hidden.</p></td> 1294 <td align="center">No</td> 1295 <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> 1296</tr> 1297 1298<tr> 1299 <td rowspan="2" style="border-left: none;"> </td> 1300 <td align="left"><code>{@link android.app.Activity#onResume onResume()}</code></td> 1301 <td>Called just before the activity starts 1302 interacting with the user. At this point the activity is at 1303 the top of the activity stack, with user input going to it. 1304 <p>Always followed by {@code onPause()}.</p></td> 1305 <td align="center">No</td> 1306 <td align="center">{@code onPause()}</td> 1307</tr> 1308 1309<tr> 1310 <td align="left"><code>{@link android.app.Activity#onPause onPause()}</code></td> 1311 <td>Called when the system is about to start resuming another 1312 activity. This method is typically used to commit unsaved changes to 1313 persistent data, stop animations and other things that may be consuming 1314 CPU, and so on. It should do whatever it does very quickly, because 1315 the next activity will not be resumed until it returns. 1316 <p>Followed either by {@code onResume()} if the activity 1317 returns back to the front, or by {@code onStop()} if it becomes 1318 invisible to the user.</td> 1319 <td align="center"><strong style="color:#800000">Yes</strong></td> 1320 <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> 1321</tr> 1322 1323<tr> 1324 <td colspan="2" align="left"><code>{@link android.app.Activity#onStop onStop()}</code></td> 1325 <td>Called when the activity is no longer visible to the user. This 1326 may happen because it is being destroyed, or because another activity 1327 (either an existing one or a new one) has been resumed and is covering it. 1328 <p>Followed either by {@code onRestart()} if 1329 the activity is coming back to interact with the user, or by 1330 {@code onDestroy()} if this activity is going away.</p></td> 1331 <td align="center"><strong style="color:#800000">Yes</strong></td> 1332 <td align="center">{@code onRestart()} <br/>or<br/> {@code onDestroy()}</td> 1333</tr> 1334 1335<tr> 1336 <td colspan="3" align="left"><code>{@link android.app.Activity#onDestroy 1337onDestroy()}</code></td> 1338 <td>Called before the activity is destroyed. This is the final call 1339 that the activity will receive. It could be called either because the 1340 activity is finishing (someone called <code>{@link android.app.Activity#finish 1341 finish()}</code> on it), or because the system is temporarily destroying this 1342 instance of the activity to save space. You can distinguish 1343 between these two scenarios with the <code>{@link 1344 android.app.Activity#isFinishing isFinishing()}</code> method.</td> 1345 <td align="center"><strong style="color:#800000">Yes</strong></td> 1346 <td align="center"><em>nothing</em></td> 1347</tr> 1348</tbody> 1349</table> 1350 1351<p> 1352Note the <b>Killable</b> column in the table above. It indicates 1353whether or not the system can kill the process hosting the activity 1354<em>at any time after the method returns, without executing another 1355line of the activity's code</em>. Three methods ({@code onPause()}, 1356{@code onStop()}, and {@code onDestroy()}) are marked "Yes." Because 1357{@code onPause()} is the first of the three, it's the only one that's 1358guaranteed to be called before the process is killed — 1359{@code onStop()} and {@code onDestroy()} may not be. Therefore, you 1360should use {@code onPause()} to write any persistent data (such as user 1361edits) to storage. 1362</p> 1363 1364<p> 1365Methods that are marked "No" in the <b>Killable</b> column protect the 1366process hosting the activity from being killed from the moment they are 1367called. Thus an activity is in a killable state, for example, from the 1368time {@code onPause()} returns to the time {@code onResume()} is called. 1369It will not again be killable until {@code onPause()} again returns. 1370</p> 1371 1372<p> 1373As noted in a later section, <a href="#proclife">Processes and lifecycle</a>, 1374an activity that's not technically "killable" by this definition might 1375still be killed by the system — but that would happen only in 1376extreme and dire circumstances when there is no other recourse. 1377</p> 1378 1379 1380<h4 id="actstate">Saving activity state</h4> 1381 1382<p> 1383When the system, rather than the user, shuts down an activity to conserve 1384memory, the user may expect to return to the activity and find it in its 1385previous state. 1386</p> 1387 1388<p> 1389To capture that state before the activity is killed, you can implement 1390an <code>{@link android.app.Activity#onSaveInstanceState 1391onSaveInstanceState()}</code> method for the activity. Android calls this 1392method before making the activity vulnerable to being destroyed — 1393that is, before {@code onPause()} is called. It 1394passes the method a {@link android.os.Bundle} object where you can record 1395the dynamic state of the activity as name-value pairs. When the activity is 1396again started, the Bundle is passed both to {@code onCreate()} and to a 1397method that's called after {@code onStart()}, <code>{@link 1398android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}</code>, 1399so that either or both of them can recreate the captured state. 1400</p> 1401 1402<p> 1403Unlike {@code onPause()} and the other methods discussed earlier, 1404{@code onSaveInstanceState()} and {@code onRestoreInstanceState()} are 1405not lifecycle methods. They are not always called. For example, Android 1406calls {@code onSaveInstanceState()} before the activity becomes 1407vulnerable to being destroyed by the system, but does not bother 1408calling it when the instance is actually being destroyed by a user action 1409(such as pressing the BACK key). In that case, the user won't expect to 1410return to the activity, so there's no reason to save its state. 1411</p> 1412 1413<p> 1414Because {@code onSaveInstanceState()} is not always called, you should 1415use it only to record the transient state of the activity, not to store 1416persistent data. Use {@code onPause()} for that purpose instead. 1417</p> 1418 1419 1420<h4 id="coordact">Coordinating activities</h4> 1421 1422<p> 1423When one activity starts another, they both experience lifecycle 1424transitions. One pauses and may stop, while the other starts up. 1425On occasion, you may need to coordinate these activities, one with 1426the other. 1427</p> 1428 1429<p> 1430The order of lifecycle callbacks is well defined, 1431particularly when the two activities are in the same process: 1432</p> 1433 1434<ol> 1435<li>The current activity's {@code onPause()} method is called.</li> 1436 1437<li>Next, the starting activity's {@code onCreate()}, {@code onStart()}, 1438and {@code onResume()} methods are called in sequence.</li> 1439 1440<li>Then, if the starting activity is no longer visible 1441on screen, its {@code onStop()} method is called.</li> 1442</ol> 1443 1444 1445<h3 id="servlife">Service lifecycle</h3> 1446 1447<p> 1448A service can be used in two ways: 1449</p> 1450 1451<ul> 1452<li>It can be started and allowed to run until someone stops it or 1453it stops itself. In this mode, it's started by calling 1454<code>{@link android.content.Context#startService Context.startService()}</code> 1455and stopped by calling 1456<code>{@link android.content.Context#stopService Context.stopService()}</code>. 1457It can stop itself by calling 1458<code>{@link android.app.Service#stopSelf() Service.stopSelf()}</code> or 1459<code>{@link android.app.Service#stopSelfResult Service.stopSelfResult()}</code>. 1460Only one {@code stopService()} call is needed to stop the service, no matter how 1461many times {@code startService()} was called.</li> 1462 1463<li><p>It can be operated programmatically using an interface that 1464it defines and exports. Clients establish a connection to the Service 1465object and use that connection to call into the service. The connection is 1466established by calling 1467<code>{@link android.content.Context#bindService Context.bindService()}</code>, 1468and is closed by calling 1469<code>{@link android.content.Context#unbindService Context.unbindService()}</code>. 1470Multiple clients can bind to the same service. 1471If the service has not already been launched, {@code bindService()} can optionally 1472launch it. 1473</p></li> 1474</ul> 1475 1476<p> 1477The two modes are not entirely separate. You can bind to a service that 1478was started with {@code startService()}. For example, a background music 1479service could be started by calling {@code startService()} with an Intent 1480object that identifies the music to play. Only later, possibly when the 1481user wants to exercise some control over the player or get information 1482about the current song, would an activity 1483establish a connection to the service by calling {@code bindService()}. 1484In cases like this, {@code stopService()} 1485will not actually stop the service until the last binding is closed. 1486</p> 1487 1488<p> 1489Like an activity, a service has lifecycle methods that you can implement 1490to monitor changes in its state. But they are fewer than the activity 1491methods — only three — and they are public, not protected: 1492</p> 1493 1494<p style="margin-left: 2em">{@code void onCreate()} 1495<br/>{@code void onStart(Intent <i>intent</i>)} 1496<br/>{@code void onDestroy()}</p> 1497 1498<p> 1499By implementing these methods, you can monitor two nested loops of the 1500service's lifecycle: 1501</p> 1502 1503<ul> 1504<li>The <b>entire lifetime</b> of a service happens between the time 1505<code>{@link android.app.Service#onCreate onCreate()}</code> is called and 1506the time <code>{@link android.app.Service#onDestroy}</code> returns. 1507Like an activity, a service does its initial setup in {@code onCreate()}, 1508and releases all remaining resources in {@code onDestroy()}. For example, 1509a music playback service could create the thread where the music will be played 1510in {@code onCreate()}, and then stop the thread in {@code onDestroy()}.</li> 1511 1512<li><p>The <b>active lifetime</b> of a service begins with a call to 1513<code>{@link android.app.Service#onStart onStart()}</code>. This method 1514is handed the Intent object that was passed to {@code startService()}. 1515The music service would open the Intent to discover which music to 1516play, and begin the playback.</p> 1517 1518<p> 1519There's no equivalent callback for when the service stops — no 1520{@code onStop()} method. 1521</p></li> 1522</ul> 1523 1524<p> 1525The {@code onCreate()} and {@code onDestroy()} methods are called for all 1526services, whether they're started by 1527<code>{@link android.content.Context#startService Context.startService()}</code> 1528or 1529<code>{@link android.content.Context#bindService Context.bindService()}</code>. 1530However, {@code onStart()} is called only for services started by {@code 1531startService()}. 1532</p> 1533 1534<p> 1535If a service permits others to 1536bind to it, there are additional callback methods for it to implement: 1537</p> 1538 1539<p style="margin-left: 2em">{@code IBinder onBind(Intent <i>intent</i>)} 1540<br/>{@code boolean onUnbind(Intent <i>intent</i>)} 1541<br/>{@code void onRebind(Intent <i>intent</i>)}</p> 1542 1543<p> 1544The <code>{@link android.app.Service#onBind onBind()}</code> callback is passed 1545the Intent object that was passed to {@code bindService} and 1546<code>{@link android.app.Service#onUnbind onUnbind()}</code> is handed 1547the intent that was passed to {@code unbindService()}. 1548If the service permits the binding, {@code onBind()} 1549returns the communications channel that clients use to interact with the service. 1550The {@code onUnbind()} method can ask for 1551<code>{@link android.app.Service#onRebind onRebind()}</code> 1552to be called if a new client connects to the service. 1553</p> 1554 1555<p> 1556The following diagram illustrates the callback methods for a service. 1557Although, it separates services that are created via {@code startService} 1558from those created by {@code bindService()}, keep in mind that any service, 1559no matter how it's started, can potentially allow clients to bind to it, 1560so any service may receive {@code onBind()} and {@code onUnbind()} calls. 1561</p> 1562 1563<p style="margin-left: 2em"><img src="{@docRoot}images/service_lifecycle.png" 1564alt="State diagram for Service callbacks." /></p> 1565 1566 1567<h3 id="broadlife">Broadcast receiver lifecycle</h3> 1568 1569<p> 1570A broadcast receiver has single callback method: 1571</p> 1572 1573<p style="margin-left: 2em">{@code void onReceive(Context <i>curContext</i>, Intent <i>broadcastMsg</i>)}</p> 1574 1575<p> 1576When a broadcast message arrives for the receiver, Android calls its 1577<code>{@link android.content.BroadcastReceiver#onReceive onReceive()}</code> 1578method and passes it the Intent object containing the message. The broadcast 1579receiver is considered to be active only while it is executing this method. 1580When {@code onReceive()} returns, it is inactive. 1581</p> 1582 1583<p> 1584A process with an active broadcast receiver is protected from being killed. 1585But a process with only inactive components can be killed by the system at 1586any time, when the memory it consumes is needed by other processes. 1587</p> 1588 1589<p> 1590This presents a problem when the response to a broadcast message is time 1591consuming and, therefore, something that should be done in a separate thread, 1592away from the main thread where other components of the user interface run. 1593If {@code onReceive()} spawns the thread and then returns, the entire process, 1594including the new thread, is judged to be inactive (unless other application 1595components are active in the process), putting it in jeopardy of being killed. 1596The solution to this problem is for {@code onReceive()} to start a service 1597and let the service do the job, so the 1598system knows that there is still active work being done in the process. 1599</p> 1600 1601<p> 1602The next section has more on the vulnerability of processes to being killed. 1603</p> 1604 1605 1606<h3 id="proclife">Processes and lifecycles</h3> 1607 1608<p>The Android system tries to maintain an application process for as 1609long as possible, but eventually it will need to remove old processes when 1610memory runs low. To determine which processes to keep and which to kill, 1611Android places each process into an "importance hierarchy" based on the 1612components running in it and the state of those components. Processes 1613with the lowest importance are eliminated first, then those with the next 1614lowest, and so on. There are five levels in the hierarchy. The following 1615list presents them in order of importance: 1616</p> 1617 1618<ol> 1619 1620<li>A <b>foreground process</b> is one that is required for 1621what the user is currently doing. A process is considered to be 1622in the foreground if any of the following conditions hold: 1623 1624<ul> 1625<li>It is running an activity that the user is interacting with 1626(the Activity object's <code>{@link android.app.Activity#onResume 1627onResume()}</code> method has been called).</li> 1628 1629<li><p>It hosts a service that's bound 1630to the activity that the user is interacting with.</p></li> 1631 1632<li><p>It has a {@link android.app.Service} object that's executing 1633one of its lifecycle callbacks (<code>{@link android.app.Service#onCreate 1634onCreate()}</code>, <code>{@link android.app.Service#onStart onStart()}</code>, 1635or <code>{@link android.app.Service#onDestroy onDestroy()}</code>).</p></li> 1636 1637<li><p>It has a {@link android.content.BroadcastReceiver} object that's 1638executing its <code>{@link android.content.BroadcastReceiver#onReceive 1639onReceive()}</code> method.</p></li> 1640</ul> 1641 1642<p> 1643Only a few foreground processes will exist at any given time. They 1644are killed only as a last resort — if memory is so low that 1645they cannot all continue to run. Generally, at that point, the device has 1646reached a memory paging state, so killing some foreground processes is 1647required to keep the user interface responsive. 1648</p></li> 1649 1650<li><p>A <b>visible process</b> is one that doesn't have any foreground 1651components, but still can affect what the user sees on screen. 1652A process is considered to be visible if either of the following conditions 1653holds:</p> 1654 1655<ul> 1656<li>It hosts an activity that is not in the foreground, but is still visible 1657to the user (its <code>{@link android.app.Activity#onPause onPause()}</code> 1658method has been called). This may occur, for example, if the foreground 1659activity is a dialog that allows the previous activity to be seen behind it.</li> 1660 1661<li><p>It hosts a service that's bound to a visible activity.</p></li> 1662</ul> 1663 1664<p> 1665A visible process is considered extremely important and will not be killed 1666unless doing so is required to keep all foreground processes running. 1667</p></li> 1668 1669<li><p>A <b>service process</b> is one that is running a service that 1670has been started with the 1671<code>{@link android.content.Context#startService startService()}</code> 1672method and that does not fall into either of the two higher categories. 1673Although service processes are not directly tied to anything the 1674user sees, they are generally doing things that the user cares about (such 1675as playing an mp3 in the background or downloading data on the network), 1676so the system keeps them running unless there's not enough 1677memory to retain them along with all foreground and visible processes. 1678</p></li> 1679 1680<li><p>A <b>background process</b> is one holding an activity 1681that's not currently visible to the user (the Activity object's 1682<code>{@link android.app.Activity#onStop onStop()}</code> method has been called). 1683These processes have no direct impact on the user experience, and can be killed 1684at any time to reclaim memory for a foreground, visible, or service process. 1685Usually there are many background processes running, so they are kept in an 1686LRU (least recently used) list to ensure that the process with the activity that 1687was most recently seen by the user is the last to be killed. 1688If an activity implements its lifecycle methods correctly, and captures its current 1689state, killing its process will not have a deleterious effect on the user experience. 1690</p></li> 1691 1692<li><p>An <b>empty process</b> is one that doesn't hold any active application 1693components. The only reason to keep such a process around is as a cache to 1694improve startup time the next time a component needs to run in it. The system 1695often kills these processes in order to balance overall system resources between 1696process caches and the underlying kernel caches.</p></li> 1697 1698</ol> 1699 1700<p> 1701Android ranks a process at the highest level it can, based upon the 1702importance of the components currently active in the process. For example, 1703if a process hosts a service and a visible activity, the process will be 1704ranked as a visible process, not a service process. 1705</p> 1706 1707<p> 1708In addition, a process's ranking may be increased because other processes are 1709dependent on it. A process that is serving another process can never be 1710ranked lower than the process it is serving. For example, if a content 1711provider in process A is serving a client in process B, or if a service in 1712process A is bound to a component in process B, process A will always be 1713considered at least as important as process B. 1714</p> 1715 1716<p> 1717Because a process running a service is ranked higher than one with background 1718activities, an activity that initiates a long-running operation might do 1719well to start a service for that operation, rather than simply spawn a thread 1720— particularly if the operation will likely outlast the activity. 1721Examples of this are playing music in the background 1722and uploading a picture taken by the camera to a web site. Using a service 1723guarantees that the operation will have at least "service process" priority, 1724regardless of what happens to the activity. As noted in the 1725<a href="#broadlife">Broadcast receiver lifecycle</a> section earlier, this 1726is the same reason that broadcast receivers should employ services rather 1727than simply put time-consuming operations in a thread. 1728</p> 1729