1page.title=Starting an Activity 2parent.title=Managing the Activity Lifecycle 3parent.link=index.html 4 5trainingnavtop=true 6next.title=Pausing and Resuming an Activity 7next.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" 32class="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 40Android system initiates code in an {@link android.app.Activity} instance by invoking specific 41callback methods that correspond to specific stages of its 42lifecycle. There is a sequence of callback methods that start up an activity and a sequence of 43callback 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 46handle 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 53a sequence similar to a step pyramid. That is, each stage of the 54activity lifecycle is a separate step on the pyramid. As the system creates a new activity instance, 55each callback method moves the activity state one step toward the top. The top of the pyramid is the 56point 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 59state back down the pyramid in order to dismantle the activity. In some cases, the activity will 60move only part way down the pyramid and wait (such as when the user switches to another app), from 61which point the activity can move back to the top (if the user returns to the activity) and 62resume 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 67lifecycle, expressed as a step pyramid. This shows how, for every callback used to take 68the activity a step toward the Resumed state at the top, there's a callback method 69that takes the activity a step down. The activity can also return to the resumed state from the 70Paused and Stopped state.</p> 71 72 73<p>Depending on the complexity of your activity, you probably don't need to implement all the 74lifecycle methods. However, it's important that you understand each one and implement those that 75ensure your app behaves the way users expect. Implementing your activity lifecycle methods properly 76ensures 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 79while using your app.</li> 80 <li>Does not consume valuable system resources when the user is not actively using 81it.</li> 82 <li>Does not lose the user's progress if they leave your app and return to it at a 83later time.</li> 84 <li>Does not crash or lose the user's progress when the screen rotates between 85landscape and portrait orientation.</li> 86</ul> 87 88<!-- 89<p class="table-caption"><strong>Table 1.</strong> Activity lifecycle state pairs and callback 90methods.</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 116transitions between different states that are illustrated in figure 1. However, only three of 117these states can be static. That is, the activity can exist in one of only three states for an 118extended 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—the 125other activity that's in the foreground is semi-transparent or doesn't cover the entire screen. The 126paused 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 129considered to be in the background. While stopped, the activity instance and all its state 130information 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 134the 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 136android.app.Activity#onStart()}, which is quickly followed by {@link 137android.app.Activity#onResume()}.</p> 138 139<p>That's it for the basic activity lifecycle. Now you'll start learning about some of the 140specific 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 147android.app.Activity#onCreate onCreate()} method for the {@link android.app.Activity} in your app 148that you've declared to be the "launcher" (or "main") activity. This is the activity that serves as 149the 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 152href="{@docRoot}guide/topics/manifest/manifest-intro.html">{@code AndroidManifest.xml}</a>, which is 153at 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 156href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code 157<intent-filter>}</a> that includes the {@link 158android.content.Intent#ACTION_MAIN MAIN} action and 159{@link android.content.Intent#CATEGORY_LAUNCHER LAUNCHER} category. For example:</p> 160 161<pre> 162<activity android:name=".MainActivity" android:label="@string/app_name"> 163 <intent-filter> 164 <action android:name="android.intent.action.MAIN" /> 165 <category android:name="android.intent.category.LAUNCHER" /> 166 </intent-filter> 167</activity> 168</pre> 169 170<p class="note"><strong>Note:</strong> When you create a new Android project with the Android SDK 171tools, the default project files include an {@link android.app.Activity} class that's declared in 172the 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 176activities, 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. 183Whether an activity is the main activity that's created when the user clicks your app icon or a 184different activity that your app starts in response to a user action, the system creates 185every new instance of {@link android.app.Activity} by calling its {@link 186android.app.Activity#onCreate onCreate()} method.</p> 187 188<p>You must implement the {@link android.app.Activity#onCreate onCreate()} method to perform basic 189application startup logic that should happen only once for the entire life of the activity. For 190example, your implementation of {@link android.app.Activity#onCreate onCreate()} should define the 191user 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()} 194method shows some code that performs some fundamental setup for the activity, such as 195declaring the user interface (defined in an XML layout file), defining member variables, 196and configuring some of the UI.</p> 197 198<pre> 199TextView mTextView; // Member variable for text view in the layout 200 201@Override 202public 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 223prevent older system's from executing new APIs works in this way on Android 2.0 (API level 2245) 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 227calls the {@link android.app.Activity#onStart()} and {@link android.app.Activity#onResume()} methods 228in quick succession. Your activity never resides in the Created or Started states. Technically, the 229activity 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 231state until something occurs to change that, such as when a phone call is received, the user 232navigates 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 235android.app.Activity#onStart()} and {@link android.app.Activity#onResume()}, are useful during your 236activity'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()} 239method includes a parameter called <code>savedInstanceState</code> that's discussed in the 240latter 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 245structure with an emphasis on the three main callbacks that the system calls in sequence when 246creating a new instance of the activity: {@link android.app.Activity#onCreate onCreate()}, {@link 247android.app.Activity#onStart()}, and {@link android.app.Activity#onResume()}. Once this sequence of 248callbacks complete, the activity reaches the Resumed state where users can interact with the 249activity 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 260onCreate()}, its very last callback is {@link android.app.Activity#onDestroy}. The system calls 261this method on your activity as the final 262signal 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 265with the activity and your activity should perform most cleanup during {@link 266android.app.Activity#onPause} and {@link android.app.Activity#onStop}. However, if your 267activity includes background threads that you created during {@link 268android.app.Activity#onCreate onCreate()} or other long-running resources that could 269potentially leak memory if not properly closed, you should kill them during {@link 270android.app.Activity#onDestroy}.</p> 271 272<pre> 273@Override 274public 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} 283after it has already called {@link android.app.Activity#onPause} and {@link 284android.app.Activity#onStop} in all situations except one: when you call {@link 285android.app.Activity#finish()} from within the {@link android.app.Activity#onCreate onCreate()} 286method. In some cases, such as when your activity operates as a temporary decision maker to 287launch another activity, you might call {@link android.app.Activity#finish()} from within {@link 288android.app.Activity#onCreate onCreate()} to destroy the activity. In this case, the system 289immediately calls {@link android.app.Activity#onDestroy} without calling any of the other 290lifecycle methods.</p> 291