1 page.title=Activities 2 page.tags=activity,intent 3 @jd:body 4 5 <div id="qv-wrapper"> 6 <div id="qv"> 7 <h2>In this document</h2> 8 <ol> 9 <li><a href="#Creating">Creating an Activity</a> 10 <ol> 11 <li><a href="#UI">Implementing a user interface</a></li> 12 <li><a href="#Declaring">Declaring the activity in the manifest</a></li> 13 </ol> 14 </li> 15 <li><a href="#StartingAnActivity">Starting an Activity</a> 16 <ol> 17 <li><a href="#StartingAnActivityForResult">Starting an activity for a result</a></li> 18 </ol> 19 </li> 20 <li><a href="#ShuttingDown">Shutting Down an Activity</a></li> 21 <li><a href="#Lifecycle">Managing the Activity Lifecycle</a> 22 <ol> 23 <li><a href="#ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</a></li> 24 <li><a href="#SavingActivityState">Saving activity state</a></li> 25 <li><a href="#ConfigurationChanges">Handling configuration changes</a></li> 26 <li><a href="#CoordinatingActivities">Coordinating activities</a></li> 27 </ol> 28 </li> 29 </ol> 30 31 <h2>Key classes</h2> 32 <ol> 33 <li>{@link android.app.Activity}</li> 34 </ol> 35 36 <h2>See also</h2> 37 <ol> 38 <li><a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back 39 Stack</a></li> 40 </ol> 41 42 </div> 43 </div> 44 45 46 47 <p>An {@link android.app.Activity} is an application component that provides a screen with which 48 users can interact in order to do something, such as dial the phone, take a photo, send an email, or 49 view a map. Each activity is given a window in which to draw its user interface. The window 50 typically fills the screen, but may be smaller than the screen and float on top of other 51 windows.</p> 52 53 <p> An application usually consists of multiple activities that are loosely bound 54 to each other. Typically, one activity in an application is specified as the "main" activity, which 55 is presented to the user when launching the application for the first time. Each 56 activity can then start another activity in order to perform different actions. Each time a new 57 activity starts, the previous activity is stopped, but the system preserves the activity 58 in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and 59 takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, 60 so, when the user is done with the current activity and presses the <em>Back</em> button, it 61 is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is 62 discussed more in the <a href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks 63 and Back Stack</a> document.)</p> 64 65 <p>When an activity is stopped because a new activity starts, it is notified of this change in state 66 through the activity's lifecycle callback methods. 67 There are several callback methods that an activity might receive, due to a change in its 68 state—whether the system is creating it, stopping it, resuming it, or destroying it—and 69 each callback provides you the opportunity to perform specific work that's 70 appropriate to that state change. For instance, when stopped, your activity should release any 71 large objects, such as network or database connections. When the activity resumes, you can 72 reacquire the necessary resources and resume actions that were interrupted. These state transitions 73 are all part of the activity lifecycle.</p> 74 75 <p>The rest of this document discusses the basics of how to build and use an activity, 76 including a complete discussion of how the activity lifecycle works, so you can properly manage 77 the transition between various activity states.</p> 78 79 80 81 <h2 id="Creating">Creating an Activity</h2> 82 83 <p>To create an activity, you must create a subclass of {@link android.app.Activity} (or 84 an existing subclass of it). In your subclass, you need to implement callback methods that the 85 system calls when the activity transitions between various states of its lifecycle, such as when 86 the activity is being created, stopped, resumed, or destroyed. The two most important callback 87 methods are:</p> 88 89 <dl> 90 <dt>{@link android.app.Activity#onCreate onCreate()}</dt> 91 <dd>You must implement this method. The system calls this when creating your 92 activity. Within your implementation, you should initialize the essential components of your 93 activity. 94 Most importantly, this is where you must call {@link android.app.Activity#setContentView 95 setContentView()} to define the layout for the activity's user interface.</dd> 96 <dt>{@link android.app.Activity#onPause onPause()}</dt> 97 <dd>The system calls this method as the first indication that the user is leaving your 98 activity (though it does not always mean the activity is being destroyed). This is usually where you 99 should commit any changes that should be persisted beyond the current user session (because 100 the user might not come back).</dd> 101 </dl> 102 103 <p>There are several other lifecycle callback methods that you should use in order to provide a 104 fluid user experience between activities and handle unexpected interuptions that cause your activity 105 to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in 106 the section about <a href="#Lifecycle">Managing the Activity Lifecycle</a>.</p> 107 108 109 110 <h3 id="UI">Implementing a user interface</h3> 111 112 <p> The user interface for an activity is provided by a hierarchy of views—objects derived 113 from the {@link android.view.View} class. Each view controls a particular rectangular space 114 within the activity's window and can respond to user interaction. For example, a view might be a 115 button that initiates an action when the user touches it.</p> 116 117 <p>Android provides a number of ready-made views that you can use to design and organize your 118 layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such 119 as a button, text field, checkbox, or just an image. "Layouts" are views derived from {@link 120 android.view.ViewGroup} that provide a unique layout model for its child views, such as a linear 121 layout, a grid layout, or relative layout. You can also subclass the {@link android.view.View} and 122 {@link android.view.ViewGroup} classes (or existing subclasses) to create your own widgets and 123 layouts and apply them to your activity layout.</p> 124 125 <p>The most common way to define a layout using views is with an XML layout file saved in your 126 application resources. This way, you can maintain the design of your user interface separately from 127 the source code that defines the activity's behavior. You can set the layout as the UI for your 128 activity with {@link android.app.Activity#setContentView(int) setContentView()}, passing the 129 resource ID for the layout. However, you can also create new {@link android.view.View}s in your 130 activity code and build a view hierarchy by inserting new {@link 131 android.view.View}s into a {@link android.view.ViewGroup}, then use that layout by passing the root 132 {@link android.view.ViewGroup} to {@link android.app.Activity#setContentView(View) 133 setContentView()}.</p> 134 135 <p>For information about creating a user interface, see the <a 136 href="{@docRoot}guide/topics/ui/index.html">User Interface</a> documentation.</p> 137 138 139 140 <h3 id="Declaring">Declaring the activity in the manifest</h3> 141 142 <p>You must declare your activity in the manifest file in order for it to 143 be accessible to the system. To declare your activity, open your manifest file and add an <a 144 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element 145 as a child of the <a 146 href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> 147 element. For example:</p> 148 149 <pre> 150 <manifest ... > 151 <application ... > 152 <activity android:name=".ExampleActivity" /> 153 ... 154 </application ... > 155 ... 156 </manifest > 157 </pre> 158 159 <p>There are several other attributes that you can include in this element, to define properties 160 such as the label for the activity, an icon for the activity, or a theme to style the activity's 161 UI. The <a href="{@docRoot}guide/topics/manifest/activity-element.html#nm">{@code android:name}</a> 162 attribute is the only required attribute—it specifies the class name of the activity. Once 163 you publish your application, you should not change this name, because if you do, you might break 164 some functionality, such as application shortcuts (read the blog post, <a 165 href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things 166 That Cannot Change</a>).</p> 167 168 <p>See the <a 169 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> element 170 reference for more information about declaring your activity in the manifest.</p> 171 172 173 <h4>Using intent filters</h4> 174 175 <p>An <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code 176 <activity>}</a> element can also specify various intent filters—using the <a 177 href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code 178 <intent-filter>}</a> element—in order to declare how other application components may 179 activate it.</p> 180 181 <p>When you create a new application using the Android SDK tools, the stub activity 182 that's created for you automatically includes an intent filter that declares the activity 183 responds to the "main" action and should be placed in the "launcher" category. The intent filter 184 looks like this:</p> 185 186 <pre> 187 <activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"> 188 <intent-filter> 189 <action android:name="android.intent.action.MAIN" /> 190 <category android:name="android.intent.category.LAUNCHER" /> 191 </intent-filter> 192 </activity> 193 </pre> 194 195 <p>The <a href="{@docRoot}guide/topics/manifest/action-element.html">{@code 196 <action>}</a> element specifies that this is the "main" entry point to the application. The <a 197 href="{@docRoot}guide/topics/manifest/category-element.html">{@code 198 <category>}</a> element specifies that this activity should be listed in the 199 system's application launcher (to allow users to launch this activity).</p> 200 201 <p>If you intend for your application to be self-contained and not allow other applications to 202 activate its activities, then you don't need any other intent filters. Only one activity should 203 have the "main" action and "launcher" category, as in the previous example. Activities that 204 you don't want to make available to other applications should have no intent filters and you can 205 start them yourself using explicit intents (as discussed in the following section).</p> 206 207 <p>However, if you want your activity to respond to implicit intents that are delivered from 208 other applications (and your own), then you must define additional intent filters for your 209 activity. For each type of intent to which you want to respond, you must include an <a 210 href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code 211 <intent-filter>}</a> that includes an 212 <a href="{@docRoot}guide/topics/manifest/action-element.html">{@code 213 <action>}</a> element and, optionally, a <a 214 href="{@docRoot}guide/topics/manifest/category-element.html">{@code 215 <category>}</a> element and/or a <a 216 href="{@docRoot}guide/topics/manifest/data-element.html">{@code 217 <data>}</a> element. These elements specify the type of intent to which your activity can 218 respond.</p> 219 220 <p>For more information about how your activities can respond to intents, see the <a 221 href="{@docRoot}guide/components/intents-filters.html">Intents and Intent Filters</a> 222 document.</p> 223 224 225 226 <h2 id="StartingAnActivity">Starting an Activity</h2> 227 228 <p>You can start another activity by calling {@link android.app.Activity#startActivity 229 startActivity()}, passing it an {@link android.content.Intent} that describes the activity you 230 want to start. The intent specifies either the exact activity you want to start or describes the 231 type of action you want to perform (and the system selects the appropriate activity for you, 232 which 233 can even be from a different application). An intent can also carry small amounts of data to be 234 used by the activity that is started.</p> 235 236 <p>When working within your own application, you'll often need to simply launch a known activity. 237 You can do so by creating an intent that explicitly defines the activity you want to start, 238 using the class name. For example, here's how one activity starts another activity named {@code 239 SignInActivity}:</p> 240 241 <pre> 242 Intent intent = new Intent(this, SignInActivity.class); 243 startActivity(intent); 244 </pre> 245 246 <p>However, your application might also want to perform some action, such as send an email, text 247 message, or status update, using data from your activity. In this case, your application might 248 not have its own activities to perform such actions, so you can instead leverage the activities 249 provided by other applications on the device, which can perform the actions for you. This is where 250 intents are really valuable—you can create an intent that describes an action you want to 251 perform and the system 252 launches the appropriate activity from another application. If there are 253 multiple activities that can handle the intent, then the user can select which one to use. For 254 example, if you want to allow the user to send an email message, you can create the 255 following intent:</p> 256 257 <pre> 258 Intent intent = new Intent(Intent.ACTION_SEND); 259 intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); 260 startActivity(intent); 261 </pre> 262 263 <p>The {@link android.content.Intent#EXTRA_EMAIL} extra added to the intent is a string array of 264 email addresses to which the email should be sent. When an email application responds to this 265 intent, it reads the string array provided in the extra and places them in the "to" field of the 266 email composition form. In this situation, the email application's activity starts and when the 267 user is done, your activity resumes.</p> 268 269 270 271 272 <h3 id="StartingAnActivityForResult">Starting an activity for a result</h3> 273 274 <p>Sometimes, you might want to receive a result from the activity that you start. In that case, 275 start the activity by calling {@link android.app.Activity#startActivityForResult 276 startActivityForResult()} (instead of {@link android.app.Activity#startActivity 277 startActivity()}). To then receive the result from the subsequent 278 activity, implement the {@link android.app.Activity#onActivityResult onActivityResult()} callback 279 method. When the subsequent activity is done, it returns a result in an {@link 280 android.content.Intent} to your {@link android.app.Activity#onActivityResult onActivityResult()} 281 method.</p> 282 283 <p>For example, perhaps you want the user to pick one of their contacts, so your activity can 284 do something with the information in that contact. Here's how you can create such an intent and 285 handle the result:</p> 286 287 <pre> 288 private void pickContact() { 289 // Create an intent to "pick" a contact, as defined by the content provider URI 290 Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); 291 startActivityForResult(intent, PICK_CONTACT_REQUEST); 292 } 293 294 @Override 295 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 296 // If the request went well (OK) and the request was PICK_CONTACT_REQUEST 297 if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { 298 // Perform a query to the contact's content provider for the contact's name 299 Cursor cursor = getContentResolver().query(data.getData(), 300 new String[] {Contacts.DISPLAY_NAME}, null, null, null); 301 if (cursor.moveToFirst()) { // True if the cursor is not empty 302 int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); 303 String name = cursor.getString(columnIndex); 304 // Do something with the selected contact's name... 305 } 306 } 307 } 308 </pre> 309 310 <p>This example shows the basic logic you should use in your {@link 311 android.app.Activity#onActivityResult onActivityResult()} method in order to handle an 312 activity result. The first condition checks whether the request was successful—if it was, then 313 the {@code resultCode} will be {@link android.app.Activity#RESULT_OK}—and whether the request 314 to which this result is responding is known—in this case, the {@code requestCode} matches the 315 second parameter sent with {@link android.app.Activity#startActivityForResult 316 startActivityForResult()}. From there, the code handles the activity result by querying the 317 data returned in an {@link android.content.Intent} (the {@code data} parameter).</p> 318 319 <p>What happens is, a {@link 320 android.content.ContentResolver} performs a query against a content provider, which returns a 321 {@link android.database.Cursor} that allows the queried data to be read. For more information, see 322 the <a 323 href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> document.</p> 324 325 <p>For more information about using intents, see the <a 326 href="{@docRoot}guide/components/intents-filters.html">Intents and Intent 327 Filters</a> document.</p> 328 329 330 <h2 id="ShuttingDown">Shutting Down an Activity</h2> 331 332 <p>You can shut down an activity by calling its {@link android.app.Activity#finish 333 finish()} method. You can also shut down a separate activity that you previously started by calling 334 {@link android.app.Activity#finishActivity finishActivity()}.</p> 335 336 <p class="note"><strong>Note:</strong> In most cases, you should not explicitly finish an activity 337 using these methods. As discussed in the following section about the activity lifecycle, the 338 Android system manages the life of an activity for you, so you do not need to finish your own 339 activities. Calling these methods could adversely affect the expected user 340 experience and should only be used when you absolutely do not want the user to return to this 341 instance of the activity.</p> 342 343 344 <h2 id="Lifecycle">Managing the Activity Lifecycle</h2> 345 346 <p>Managing the lifecycle of your activities by implementing callback methods is 347 crucial to developing a strong 348 and flexible application. The lifecycle of an activity is directly affected by its association with 349 other activities, its task and back stack.</p> 350 351 <p>An activity can exist in essentially three states:</p> 352 353 <dl> 354 <dt><i>Resumed</i></dt> 355 <dd>The activity is in the foreground of the screen and has user focus. (This state is 356 also sometimes referred to as "running".)</dd> 357 358 <dt><i>Paused</i></dt> 359 <dd>Another activity is in the foreground and has focus, but this one is still visible. That is, 360 another activity is visible on top of this one and that activity is partially transparent or doesn't 361 cover the entire screen. A paused activity is completely alive (the {@link android.app.Activity} 362 object is retained in memory, it maintains all state and member information, and remains attached to 363 the window manager), but can be killed by the system in extremely low memory situations.</dd> 364 365 <dt><i>Stopped</i></dt> 366 <dd>The activity is completely obscured by another activity (the activity is now in the 367 "background"). A stopped activity is also still alive (the {@link android.app.Activity} 368 object is retained in memory, it maintains all state and member information, but is <em>not</em> 369 attached to the window manager). However, it is no longer visible to the user and it 370 can be killed by the system when memory is needed elsewhere.</dd> 371 </dl> 372 373 <p>If an activity is paused or stopped, the system can drop it from memory either by asking it to 374 finish (calling its {@link android.app.Activity#finish finish()} method), or simply killing its 375 process. When the activity is opened again (after being finished or killed), it must be created all 376 over.</p> 377 378 379 380 <h3 id="ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</h3> 381 382 <p>When an activity transitions into and out of the different states described above, it is notified 383 through various callback methods. All of the callback methods are hooks that you 384 can override to do appropriate work when the state of your activity changes. The following skeleton 385 activity includes each of the fundamental lifecycle methods:</p> 386 387 388 <pre> 389 public class ExampleActivity extends Activity { 390 @Override 391 public void {@link android.app.Activity#onCreate onCreate}(Bundle savedInstanceState) { 392 super.onCreate(savedInstanceState); 393 // The activity is being created. 394 } 395 @Override 396 protected void {@link android.app.Activity#onStart onStart()} { 397 super.onStart(); 398 // The activity is about to become visible. 399 } 400 @Override 401 protected void {@link android.app.Activity#onResume onResume()} { 402 super.onResume(); 403 // The activity has become visible (it is now "resumed"). 404 } 405 @Override 406 protected void {@link android.app.Activity#onPause onPause()} { 407 super.onPause(); 408 // Another activity is taking focus (this activity is about to be "paused"). 409 } 410 @Override 411 protected void {@link android.app.Activity#onStop onStop()} { 412 super.onStop(); 413 // The activity is no longer visible (it is now "stopped") 414 } 415 @Override 416 protected void {@link android.app.Activity#onDestroy onDestroy()} { 417 super.onDestroy(); 418 // The activity is about to be destroyed. 419 } 420 } 421 </pre> 422 423 <p class="note"><strong>Note:</strong> Your implementation of these lifecycle methods must 424 always call the superclass implementation before doing any work, as shown in the examples above.</p> 425 426 <p>Taken together, these methods define the entire lifecycle of an activity. By implementing these 427 methods, you can monitor three nested loops in the activity lifecycle: </p> 428 429 <ul> 430 <li>The <b>entire lifetime</b> of an activity happens between the call to {@link 431 android.app.Activity#onCreate onCreate()} and the call to {@link 432 android.app.Activity#onDestroy}. Your activity should perform setup of 433 "global" state (such as defining layout) in {@link android.app.Activity#onCreate onCreate()}, and 434 release all remaining resources in {@link android.app.Activity#onDestroy}. For example, if your 435 activity has a thread running in the background to download data from the network, it might create 436 that thread in {@link android.app.Activity#onCreate onCreate()} and then stop the thread in {@link 437 android.app.Activity#onDestroy}.</li> 438 439 <li><p>The <b>visible lifetime</b> of an activity happens between the call to {@link 440 android.app.Activity#onStart onStart()} and the call to {@link 441 android.app.Activity#onStop onStop()}. During this time, the user can see the activity 442 on-screen and interact with it. For example, {@link android.app.Activity#onStop onStop()} is called 443 when a new activity starts and this one is no longer visible. Between these two methods, you can 444 maintain resources that are needed to show the activity to the user. For example, you can register a 445 {@link android.content.BroadcastReceiver} in {@link 446 android.app.Activity#onStart onStart()} to monitor changes that impact your UI, and unregister 447 it in {@link android.app.Activity#onStop onStop()} when the user can no longer see what you are 448 displaying. The system might call {@link android.app.Activity#onStart onStart()} and {@link 449 android.app.Activity#onStop onStop()} multiple times during the entire lifetime of the activity, as 450 the activity alternates between being visible and hidden to the user.</p></li> 451 452 <li><p>The <b>foreground lifetime</b> of an activity happens between the call to {@link 453 android.app.Activity#onResume onResume()} and the call to {@link android.app.Activity#onPause 454 onPause()}. During this time, the activity is in front of all other activities on screen and has 455 user input focus. An activity can frequently transition in and out of the foreground—for 456 example, {@link android.app.Activity#onPause onPause()} is called when the device goes to sleep or 457 when a dialog appears. Because this state can transition often, the code in these two methods should 458 be fairly lightweight in order to avoid slow transitions that make the user wait.</p></li> 459 </ul> 460 461 <p>Figure 1 illustrates these loops and the paths an activity might take between states. 462 The rectangles represent the callback methods you can implement to perform operations when 463 the activity transitions between states. <p> 464 465 <img src="{@docRoot}images/activity_lifecycle.png" alt="" /> 466 <p class="img-caption"><strong>Figure 1.</strong> The activity lifecycle.</p> 467 468 <p>The same lifecycle callback methods are listed in table 1, which describes each of the callback 469 methods in more detail and locates each one within the 470 activity's overall lifecycle, including whether the system can kill the activity after the 471 callback method completes.</p> 472 473 <p class="table-caption"><strong>Table 1.</strong> A summary of the activity lifecycle's 474 callback methods.</p> 475 476 <table border="2" width="85%" frame="hsides" rules="rows"> 477 <colgroup align="left" span="3"></colgroup> 478 <colgroup align="left"></colgroup> 479 <colgroup align="center"></colgroup> 480 <colgroup align="center"></colgroup> 481 482 <thead> 483 <tr><th colspan="3">Method</th> <th>Description</th> <th>Killable after?</th> <th>Next</th></tr> 484 </thead> 485 486 <tbody> 487 <tr> 488 <td colspan="3" align="left"><code>{@link android.app.Activity#onCreate onCreate()}</code></td> 489 <td>Called when the activity is first created. 490 This is where you should do all of your normal static set up — 491 create views, bind data to lists, and so on. This method is passed 492 a Bundle object containing the activity's previous state, if that 493 state was captured (see <a href="#actstate">Saving Activity State</a>, 494 later). 495 <p>Always followed by {@code onStart()}.</p></td> 496 <td align="center">No</td> 497 <td align="center">{@code onStart()}</td> 498 </tr> 499 500 <tr> 501 <td rowspan="5" style="border-left: none; border-right: none;"> </td> 502 <td colspan="2" align="left"><code>{@link android.app.Activity#onRestart 503 onRestart()}</code></td> 504 <td>Called after the activity has been stopped, just prior to it being 505 started again. 506 <p>Always followed by {@code onStart()}</p></td> 507 <td align="center">No</td> 508 <td align="center">{@code onStart()}</td> 509 </tr> 510 511 <tr> 512 <td colspan="2" align="left"><code>{@link android.app.Activity#onStart onStart()}</code></td> 513 <td>Called just before the activity becomes visible to the user. 514 <p>Followed by {@code onResume()} if the activity comes 515 to the foreground, or {@code onStop()} if it becomes hidden.</p></td> 516 <td align="center">No</td> 517 <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> 518 </tr> 519 520 <tr> 521 <td rowspan="2" style="border-left: none;"> </td> 522 <td align="left"><code>{@link android.app.Activity#onResume onResume()}</code></td> 523 <td>Called just before the activity starts 524 interacting with the user. At this point the activity is at 525 the top of the activity stack, with user input going to it. 526 <p>Always followed by {@code onPause()}.</p></td> 527 <td align="center">No</td> 528 <td align="center">{@code onPause()}</td> 529 </tr> 530 531 <tr> 532 <td align="left"><code>{@link android.app.Activity#onPause onPause()}</code></td> 533 <td>Called when the system is about to start resuming another 534 activity. This method is typically used to commit unsaved changes to 535 persistent data, stop animations and other things that may be consuming 536 CPU, and so on. It should do whatever it does very quickly, because 537 the next activity will not be resumed until it returns. 538 <p>Followed either by {@code onResume()} if the activity 539 returns back to the front, or by {@code onStop()} if it becomes 540 invisible to the user.</td> 541 <td align="center"><strong style="color:#800000">Yes</strong></td> 542 <td align="center">{@code onResume()} <br/>or<br/> {@code onStop()}</td> 543 </tr> 544 545 <tr> 546 <td colspan="2" align="left"><code>{@link android.app.Activity#onStop onStop()}</code></td> 547 <td>Called when the activity is no longer visible to the user. This 548 may happen because it is being destroyed, or because another activity 549 (either an existing one or a new one) has been resumed and is covering it. 550 <p>Followed either by {@code onRestart()} if 551 the activity is coming back to interact with the user, or by 552 {@code onDestroy()} if this activity is going away.</p></td> 553 <td align="center"><strong style="color:#800000">Yes</strong></td> 554 <td align="center">{@code onRestart()} <br/>or<br/> {@code onDestroy()}</td> 555 </tr> 556 557 <tr> 558 <td colspan="3" align="left"><code>{@link android.app.Activity#onDestroy 559 onDestroy()}</code></td> 560 <td>Called before the activity is destroyed. This is the final call 561 that the activity will receive. It could be called either because the 562 activity is finishing (someone called <code>{@link android.app.Activity#finish 563 finish()}</code> on it), or because the system is temporarily destroying this 564 instance of the activity to save space. You can distinguish 565 between these two scenarios with the <code>{@link 566 android.app.Activity#isFinishing isFinishing()}</code> method.</td> 567 <td align="center"><strong style="color:#800000">Yes</strong></td> 568 <td align="center"><em>nothing</em></td> 569 </tr> 570 </tbody> 571 </table> 572 573 <p>The column labeled "Killable after?" indicates whether or not the system can 574 kill the process hosting the activity at any time <em>after the method returns</em>, without 575 executing another line of the activity's code. Three methods are marked "yes": ({@link 576 android.app.Activity#onPause 577 onPause()}, {@link android.app.Activity#onStop onStop()}, and {@link android.app.Activity#onDestroy 578 onDestroy()}). Because {@link android.app.Activity#onPause onPause()} is the first 579 of the three, once the activity is created, {@link android.app.Activity#onPause onPause()} is the 580 last method that's guaranteed to be called before the process <em>can</em> be killed—if 581 the system must recover memory in an emergency, then {@link 582 android.app.Activity#onStop onStop()} and {@link android.app.Activity#onDestroy onDestroy()} might 583 not be called. Therefore, you should use {@link android.app.Activity#onPause onPause()} to write 584 crucial persistent data (such as user edits) to storage. However, you should be selective about 585 what information must be retained during {@link android.app.Activity#onPause onPause()}, because any 586 blocking procedures in this method block the transition to the next activity and slow the user 587 experience.</p> 588 589 <p> Methods that are marked "No" in the <b>Killable</b> column protect the process hosting the 590 activity from being killed from the moment they are called. Thus, an activity is killable 591 from the time {@link android.app.Activity#onPause onPause()} returns to the time 592 {@link android.app.Activity#onResume onResume()} is called. It will not again be killable until 593 {@link android.app.Activity#onPause onPause()} is again called and returns. </p> 594 595 <p class="note"><strong>Note:</strong> An activity that's not technically "killable" by this 596 definition in table 1 might still be killed by the system—but that would happen only in 597 extreme circumstances when there is no other recourse. When an activity might be killed is 598 discussed more in the <a 599 href="{@docRoot}guide/components/processes-and-threads.html">Processes and 600 Threading</a> document.</p> 601 602 603 <h3 id="SavingActivityState">Saving activity state</h3> 604 605 <p>The introduction to <a href="#Lifecycle">Managing the Activity Lifecycle</a> briefly mentions 606 that 607 when an activity is paused or stopped, the state of the activity is retained. This is true because 608 the {@link android.app.Activity} object is still held in memory when it is paused or 609 stopped—all information about its members and current state is still alive. Thus, any changes 610 the user made within the activity are retained so that when the activity returns to the 611 foreground (when it "resumes"), those changes are still there.</p> 612 613 <p>However, when the system destroys an activity in order to recover memory, the {@link 614 android.app.Activity} object is destroyed, so the system cannot simply resume it with its state 615 intact. Instead, the system must recreate the {@link android.app.Activity} object if the user 616 navigates back to it. Yet, the user is unaware 617 that the system destroyed the activity and recreated it and, thus, probably 618 expects the activity to be exactly as it was. In this situation, you can ensure that 619 important information about the activity state is preserved by implementing an additional 620 callback method that allows you to save information about the state of your activity: {@link 621 android.app.Activity#onSaveInstanceState onSaveInstanceState()}.</p> 622 623 <p>The system calls {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} 624 before making the activity vulnerable to destruction. The system passes this method 625 a {@link android.os.Bundle} in which you can save 626 state information about the activity as name-value pairs, using methods such as {@link 627 android.os.Bundle#putString putString()} and {@link 628 android.os.Bundle#putInt putInt()}. Then, if the system kills your application 629 process and the user navigates back to your activity, the system recreates the activity and passes 630 the {@link android.os.Bundle} to both {@link android.app.Activity#onCreate onCreate()} and {@link 631 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()}. Using either of these 632 methods, you can extract your saved state from the {@link android.os.Bundle} and restore the 633 activity state. If there is no state information to restore, then the {@link 634 android.os.Bundle} passed to you is null (which is the case when the activity is created for 635 the first time).</p> 636 637 <img src="{@docRoot}images/fundamentals/restore_instance.png" alt="" /> 638 <p class="img-caption"><strong>Figure 2.</strong> The two ways in which an activity returns to user 639 focus with its state intact: either the activity is destroyed, then recreated and the activity must restore 640 the previously saved state, or the activity is stopped, then resumed and the activity state 641 remains intact.</p> 642 643 <p class="note"><strong>Note:</strong> There's no guarantee that {@link 644 android.app.Activity#onSaveInstanceState onSaveInstanceState()} will be called before your 645 activity is destroyed, because there are cases in which it won't be necessary to save the state 646 (such as when the user leaves your activity using the <em>Back</em> button, because the user is 647 explicitly 648 closing the activity). If the system calls {@link android.app.Activity#onSaveInstanceState 649 onSaveInstanceState()}, it does so before {@link 650 android.app.Activity#onStop onStop()} and possibly before {@link android.app.Activity#onPause 651 onPause()}.</p> 652 653 <p>However, even if you do nothing and do not implement {@link 654 android.app.Activity#onSaveInstanceState onSaveInstanceState()}, some of the activity state is 655 restored by the {@link android.app.Activity} class's default implementation of {@link 656 android.app.Activity#onSaveInstanceState onSaveInstanceState()}. Specifically, the default 657 implementation calls the corresponding {@link 658 android.view.View#onSaveInstanceState onSaveInstanceState()} method for every {@link 659 android.view.View} in the layout, which allows each view to provide information about itself 660 that should be saved. Almost every widget in the Android framework implements this method as 661 appropriate, such that any visible changes to the UI are automatically saved and restored when your 662 activity is recreated. For example, the {@link android.widget.EditText} widget saves any text 663 entered by the user and the {@link android.widget.CheckBox} widget saves whether it's checked or 664 not. The only work required by you is to provide a unique ID (with the <a 665 href="{@docRoot}guide/topics/resources/layout-resource.html#idvalue">{@code android:id}</a> 666 attribute) for each widget you want to save its state. If a widget does not have an ID, then the 667 system cannot save its state.</p> 668 669 <div class="sidebox-wrapper"> 670 <div class="sidebox"> 671 <p>You can also explicitly stop a view in your layout from saving its state by setting the 672 {@link android.R.attr#saveEnabled android:saveEnabled} attribute to {@code "false"} or by calling 673 the {@link android.view.View#setSaveEnabled setSaveEnabled()} method. Usually, you should not 674 disable this, but you might if you want to restore the state of the activity UI differently.</p> 675 </div> 676 </div> 677 678 <p>Although the default implementation of {@link 679 android.app.Activity#onSaveInstanceState onSaveInstanceState()} saves useful information about 680 your activity's UI, you still might need to override it to save additional information. 681 For example, you might need to save member values that changed during the activity's life (which 682 might correlate to values restored in the UI, but the members that hold those UI values are not 683 restored, by default).</p> 684 685 <p>Because the default implementation of {@link 686 android.app.Activity#onSaveInstanceState onSaveInstanceState()} helps save the state of the UI, if 687 you override the method in order to save additional state information, you should always call the 688 superclass implementation of {@link android.app.Activity#onSaveInstanceState onSaveInstanceState()} 689 before doing any work. Likewise, you should also call the superclass implementation of {@link 690 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} if you override it, so the 691 default implementation can restore view states.</p> 692 693 <p class="note"><strong>Note:</strong> Because {@link android.app.Activity#onSaveInstanceState 694 onSaveInstanceState()} is not guaranteed 695 to be called, you should use it only to record the transient state of the activity (the state of 696 the UI)—you should never use it to store persistent data. Instead, you should use {@link 697 android.app.Activity#onPause onPause()} to store persistent data (such as data that should be saved 698 to a database) when the user leaves the activity.</p> 699 700 <p>A good way to test your application's ability to restore its state is to simply rotate the 701 device so that the screen orientation changes. When the screen orientation changes, the system 702 destroys and recreates the activity in order to apply alternative resources that might be available 703 for the new screen configuration. For this reason alone, it's very important that your activity 704 completely restores its state when it is recreated, because users regularly rotate the screen while 705 using applications.</p> 706 707 708 <h3 id="ConfigurationChanges">Handling configuration changes</h3> 709 710 <p>Some device configurations can change during runtime (such as screen orientation, keyboard 711 availability, and language). When such a change occurs, Android recreates the running activity 712 (the system calls {@link android.app.Activity#onDestroy}, then immediately calls {@link 713 android.app.Activity#onCreate onCreate()}). This behavior is 714 designed to help your application adapt to new configurations by automatically reloading your 715 application with alternative resources that you've provided (such as different layouts for 716 different screen orientations and sizes).</p> 717 718 <p>If you properly design your activity to handle a restart due to a screen orientation change and 719 restore the activity state as described above, your application will be more resilient to other 720 unexpected events in the activity lifecycle.</p> 721 722 <p>The best way to handle such a restart is 723 to save and restore the state of your activity using {@link 724 android.app.Activity#onSaveInstanceState onSaveInstanceState()} and {@link 725 android.app.Activity#onRestoreInstanceState onRestoreInstanceState()} (or {@link 726 android.app.Activity#onCreate onCreate()}), as discussed in the previous section.</p> 727 728 <p>For more information about configuration changes that happen at runtime and how you can handle 729 them, read the guide to <a href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling 730 Runtime Changes</a>.</p> 731 732 733 734 <h3 id="CoordinatingActivities">Coordinating activities</h3> 735 736 <p>When one activity starts another, they both experience lifecycle transitions. The first activity 737 pauses and stops (though, it won't stop if it's still visible in the background), while the other 738 activity is created. In case these activities share data saved to disc or elsewhere, it's important 739 to understand that the first activity is not completely stopped before the second one is created. 740 Rather, the process of starting the second one overlaps with the process of stopping the first 741 one.</p> 742 743 <p>The order of lifecycle callbacks is well defined, particularly when the two activities are in the 744 same process and one is starting the other. Here's the order of operations that occur when Activity 745 A starts Acivity B: </p> 746 747 <ol> 748 <li>Activity A's {@link android.app.Activity#onPause onPause()} method executes.</li> 749 750 <li>Activity B's {@link android.app.Activity#onCreate onCreate()}, {@link 751 android.app.Activity#onStart onStart()}, and {@link android.app.Activity#onResume onResume()} 752 methods execute in sequence. (Activity B now has user focus.)</li> 753 754 <li>Then, if Activity A is no longer visible on screen, its {@link 755 android.app.Activity#onStop onStop()} method executes.</li> 756 </ol> 757 758 <p>This predictable sequence of lifecycle callbacks allows you to manage the transition of 759 information from one activity to another. For example, if you must write to a database when the 760 first activity stops so that the following activity can read it, then you should write to the 761 database during {@link android.app.Activity#onPause onPause()} instead of during {@link 762 android.app.Activity#onStop onStop()}.</p> 763 764 <!-- 765 <h2>Beginner's Path</h2> 766 767 <p>For more information about how Android maintains a history of activities and 768 enables user multitasking, continue with the <b><a 769 href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back 770 Stack</a></b> document.</p> 771 --> 772