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