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