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