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