Home | History | Annotate | Download | only in activity-lifecycle
      1 page.title=Starting an Activity
      2 parent.title=Managing the Activity Lifecycle
      3 parent.link=index.html
      4 
      5 trainingnavtop=true
      6 next.title=Pausing and Resuming an Activity
      7 next.link=pausing.html
      8 
      9 @jd:body
     10 
     11 
     12 <div id="tb-wrapper">
     13   <div id="tb">
     14     
     15     <h2>This lesson teaches you to</h2>
     16 <ol>
     17   <li><a href="#lifecycle-states">Understand the Lifecycle Callbacks</a></li>
     18   <li><a href="#launching-activity">Specify Your App's Launcher Activity</a></li>
     19   <li><a href="#Create">Create a New Instance</a></li>
     20   <li><a href="#Destroy">Destroy the Activity</a></li>
     21 </ol>
     22     
     23     <h2>You should also read</h2>
     24     <ul>
     25       <li><a href="{@docRoot}guide/components/activities.html">Activities</a></li>
     26     </ul>
     27 
     28 <h2>Try it out</h2>
     29 
     30 <div class="download-box">
     31  <a href="http://developer.android.com/shareables/training/ActivityLifecycle.zip"
     32 class="button">Download the demo</a>
     33  <p class="filename">ActivityLifecycle.zip</p>
     34 </div>
     35 
     36   </div>
     37 </div>
     38 
     39 <p>Unlike other programming paradigms in which apps are launched with a {@code main()} method, the
     40 Android system initiates code in an {@link android.app.Activity} instance by invoking specific
     41 callback methods that correspond to specific stages of its
     42 lifecycle. There is a sequence of callback methods that start up an activity and a sequence of
     43 callback methods that tear down an activity.</p>
     44 
     45 <p>This lesson provides an overview of the most important lifecycle methods and shows you how to
     46 handle the first lifecycle callback that creates a new instance of your activity.</p>
     47 
     48 
     49 
     50 <h2 id="lifecycle-states">Understand the Lifecycle Callbacks</h2>
     51 
     52 <p>During the life of an activity, the system calls a core set of lifecycle methods in
     53 a sequence similar to a step pyramid. That is, each stage of the
     54 activity lifecycle is a separate step on the pyramid. As the system creates a new activity instance,
     55 each callback method moves the activity state one step toward the top. The top of the pyramid is the
     56 point at which the activity is running in the foreground and the user can interact with it.</p>
     57 
     58 <p>As the user begins to leave the activity, the system calls other methods that move the activity
     59 state back down the pyramid in order to dismantle the activity. In some cases, the activity will
     60 move only part way down the pyramid and wait (such as when the user switches to another app), from
     61 which point the activity can move back to the top (if the user returns to the activity) and
     62 resume where the user left off.</p>
     63 
     64 
     65 <img src="{@docRoot}images/training/basics/basic-lifecycle.png" />
     66 <p class="img-caption"><strong>Figure 1.</strong> A simplified illustration of the Activity
     67 lifecycle, expressed as a step pyramid. This shows how, for every callback used to take
     68 the activity a step toward the Resumed state at the top, there's a callback method
     69 that takes the activity a step down. The activity can also return to the resumed state from the
     70 Paused and Stopped state.</p>
     71 
     72 
     73 <p>Depending on the complexity of your activity, you probably don't need to implement all the
     74 lifecycle methods. However, it's important that you understand each one and implement those that
     75 ensure your app behaves the way users expect. Implementing your activity lifecycle methods properly
     76 ensures your app behaves well in several ways, including that it:</p>
     77 <ul>
     78   <li>Does not crash if the user receives a phone call or switches to another app
     79 while using your app.</li>
     80   <li>Does not consume valuable system resources when the user is not actively using
     81 it.</li>
     82   <li>Does not lose the user's progress if they leave your app and return to it at a
     83 later time.</li>
     84   <li>Does not crash or lose the user's progress when the screen rotates between
     85 landscape and portrait orientation.</li>
     86 </ul>
     87 
     88 <!--
     89 <p class="table-caption"><strong>Table 1.</strong> Activity lifecycle state pairs and callback 
     90 methods.</p>
     91 <table>
     92   <tr>
     93     <th scope="col">Lifecycle State</th>
     94     <th scope="col">Startup Method</th>
     95     <th scope="col">Teardown Method</th>
     96   </tr>
     97   <tr>
     98     <td>Created / Destroyed</td>
     99     <td>{@link android.app.Activity#onCreate onCreate()}</td>
    100     <td>{@link android.app.Activity#onDestroy()}</td>
    101   </tr>
    102   <tr>
    103     <td>Started / Stopped</td>
    104     <td>{@link android.app.Activity#onStart()}</td>
    105     <td>{@link android.app.Activity#onStop()}</td>
    106   </tr>
    107   <tr>
    108     <td>Resumed / Resumed</td>
    109     <td>{@link android.app.Activity#onResume()}</td>
    110     <td>{@link android.app.Activity#onPause()}</td>
    111   </tr>
    112 </table>
    113 -->
    114 
    115 <p>As you'll learn in the following lessons, there are several situations in which an activity
    116 transitions between different states that are illustrated in figure 1. However, only three of
    117 these states can be static. That is, the activity can exist in one of only three states for an
    118 extended period of time:</p>
    119 <dl>
    120   <dt>Resumed</dt>
    121     <dd>In this state, the activity is in the foreground and the user can interact with it.
    122 (Also sometimes referred to as the "running" state.)</dd>
    123   <dt>Paused</dt>
    124     <dd>In this state, the activity is partially obscured by another activity&mdash;the
    125 other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The
    126 paused activity does not receive user input and cannot execute any code.
    127   <dt>Stopped</dt>
    128     <dd>In this state, the activity is completely hidden and not visible to the user; it is
    129 considered to be in the background. While stopped, the activity instance and all its state
    130 information such as member variables is retained, but it cannot execute any code.</dd>
    131 </dl>
    132 
    133 <p>The other states (Created and Started) are transient and the system quickly moves from them to
    134 the next state by calling the next lifecycle callback method. That is, after the system calls
    135 {@link android.app.Activity#onCreate onCreate()}, it quickly calls {@link
    136 android.app.Activity#onStart()}, which is quickly followed by {@link
    137 android.app.Activity#onResume()}.</p>
    138 
    139 <p>That's it for the basic activity lifecycle. Now you'll start learning about some of the
    140 specific lifecycle behaviors.</p>
    141 
    142 
    143 
    144 <h2 id="launching-activity">Specify Your App's Launcher Activity</h2> 
    145 
    146 <p>When the user selects your app icon from the Home screen, the system calls the {@link
    147 android.app.Activity#onCreate onCreate()} method for the {@link android.app.Activity} in your app
    148 that you've declared to be the "launcher" (or "main") activity. This is the activity that serves as
    149 the main entry point to your app's user interface.</p>
    150 
    151 <p>You can define which activity to use as the main activity in the Android manifest file, <a
    152 href="{@docRoot}guide/topics/manifest/manifest-intro.html">{@code AndroidManifest.xml}</a>, which is
    153 at the root of your project directory.</p>
    154 
    155 <p>The main activity for your app must be declared in the manifest with an <a
    156 href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code
    157 &lt;intent-filter>}</a> that includes the {@link
    158 android.content.Intent#ACTION_MAIN MAIN} action and
    159 {@link android.content.Intent#CATEGORY_LAUNCHER LAUNCHER} category. For example:</p> 
    160 
    161 <pre>
    162 &lt;activity android:name=".MainActivity" android:label="&#64;string/app_name">
    163     &lt;intent-filter>
    164         &lt;action android:name="android.intent.action.MAIN" />
    165         &lt;category android:name="android.intent.category.LAUNCHER" />
    166     &lt;/intent-filter>
    167 &lt;/activity>
    168 </pre>
    169 
    170 <p class="note"><strong>Note:</strong> When you create a new Android project with the Android SDK
    171 tools, the default project files include an {@link android.app.Activity} class that's declared in
    172 the manifest with this filter.</p>
    173 
    174 <p>If either the {@link android.content.Intent#ACTION_MAIN MAIN} action or
    175 {@link android.content.Intent#CATEGORY_LAUNCHER LAUNCHER} category are not declared for one of your
    176 activities, then your app icon will not appear in the Home screen's list of apps.</p>
    177 
    178 
    179 
    180 <h2 id="Create">Create a New Instance</h2>
    181 
    182 <p>Most apps include several different activities that allow the user to perform different actions.
    183 Whether an activity is the main activity that's created when the user clicks your app icon or a
    184 different activity that your app starts in response to a user action, the system creates
    185 every new instance of {@link android.app.Activity} by calling its {@link
    186 android.app.Activity#onCreate onCreate()} method.</p>
    187 
    188 <p>You must implement the {@link android.app.Activity#onCreate onCreate()} method to perform basic
    189 application startup logic that should happen only once for the entire life of the activity. For
    190 example, your implementation of {@link android.app.Activity#onCreate onCreate()} should define the
    191 user interface and possibly instantiate some class-scope variables.</p>
    192 
    193 <p>For example, the following example of the {@link android.app.Activity#onCreate onCreate()}
    194 method shows some code that performs some fundamental setup for the activity, such as
    195 declaring the user interface (defined in an XML layout file), defining member variables,
    196 and configuring some of the UI.</p>
    197 
    198 <pre>
    199 TextView mTextView; // Member variable for text view in the layout
    200 
    201 &#64;Override
    202 public void onCreate(Bundle savedInstanceState) {
    203     super.onCreate(savedInstanceState);
    204 
    205     // Set the user interface layout for this Activity
    206     // The layout file is defined in the project res/layout/main_activity.xml file
    207     setContentView(R.layout.main_activity);
    208     
    209     // Initialize member TextView so we can manipulate it later
    210     mTextView = (TextView) findViewById(R.id.text_message);
    211     
    212     // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    213     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    214         // For the main activity, make sure the app icon in the action bar
    215         // does not behave as a button
    216         ActionBar actionBar = getActionBar();
    217         actionBar.setHomeButtonEnabled(false);
    218     }
    219 }
    220 </pre>
    221 
    222 <p class="caution"><strong>Caution:</strong> Using the {@link android.os.Build.VERSION#SDK_INT} to
    223 prevent older systems from executing new APIs works in this way on Android 2.0 (API level
    224 5) and higher only. Older versions will encounter a runtime exception.</p>
    225 
    226 <p>Once the {@link android.app.Activity#onCreate onCreate()} finishes execution, the system
    227 calls the {@link android.app.Activity#onStart()} and {@link android.app.Activity#onResume()} methods
    228 in quick succession. Your activity never resides in the Created or Started states. Technically, the
    229 activity becomes visible to the user when {@link android.app.Activity#onStart()} is called, but
    230 {@link android.app.Activity#onResume()} quickly follows and the activity remains in the Resumed
    231 state until something occurs to change that, such as when a phone call is received, the user
    232 navigates to another activity, or the device screen turns off.</p>
    233 
    234 <p>In the other lessons that follow, you'll see how the other start up methods, {@link
    235 android.app.Activity#onStart()} and {@link android.app.Activity#onResume()}, are useful during your
    236 activity's lifecycle when used to resume the activity from the Paused or Stopped states.</p>
    237 
    238 <p class="note"><strong>Note:</strong> The {@link android.app.Activity#onCreate onCreate()}
    239 method includes a parameter called <code>savedInstanceState</code> that's discussed in the
    240 latter lesson about <a href="recreating.html">Recreating an Activity</a>.</p>
    241 
    242 
    243 <img src="{@docRoot}images/training/basics/basic-lifecycle-create.png" />
    244 <p class="img-caption"><strong>Figure 2.</strong> Another illustration of the activity lifecycle
    245 structure with an emphasis on the three main callbacks that the system calls in sequence when
    246 creating a new instance of the activity: {@link android.app.Activity#onCreate onCreate()}, {@link
    247 android.app.Activity#onStart()}, and {@link android.app.Activity#onResume()}. Once this sequence of
    248 callbacks complete, the activity reaches the Resumed state where users can interact with the
    249 activity until they switch to a different activity.</p>
    250 
    251 
    252 
    253 
    254 
    255 
    256 
    257 <h2 id="Destroy">Destroy the Activity</h2>
    258 
    259 <p>While the activity's first lifecycle callback is {@link android.app.Activity#onCreate
    260 onCreate()}, its very last callback is  {@link android.app.Activity#onDestroy}. The system calls
    261 this method on your activity as the final
    262 signal that your activity instance is being completely removed from the system memory.</p>
    263 
    264 <p>Most apps don't need to implement this method because local class references are destroyed
    265 with the activity and your activity should perform most cleanup during {@link
    266 android.app.Activity#onPause} and {@link android.app.Activity#onStop}. However, if your
    267 activity includes background threads that you created during {@link
    268 android.app.Activity#onCreate onCreate()} or other long-running resources that could
    269 potentially leak memory if not properly closed, you should kill them during  {@link
    270 android.app.Activity#onDestroy}.</p>
    271 
    272 <pre>
    273 &#64;Override
    274 public void onDestroy() {
    275     super.onDestroy();  // Always call the superclass
    276     
    277     // Stop method tracing that the activity started during onCreate()
    278     android.os.Debug.stopMethodTracing();
    279 }
    280 </pre>
    281 
    282 <p class="note"><strong>Note:</strong> The system calls {@link android.app.Activity#onDestroy}
    283 after it has already called {@link android.app.Activity#onPause} and {@link
    284 android.app.Activity#onStop} in all situations except one: when you call {@link
    285 android.app.Activity#finish()} from within the {@link android.app.Activity#onCreate onCreate()}
    286 method. In some cases, such as when your activity operates as a temporary decision maker to
    287 launch another activity, you might call {@link android.app.Activity#finish()} from within {@link
    288 android.app.Activity#onCreate onCreate()} to destroy the activity. In this case, the system
    289 immediately calls {@link android.app.Activity#onDestroy} without calling any of the other
    290 lifecycle methods.</p>
    291