1page.title=Stopping and Restarting an Activity 2parent.title=Managing the Activity Lifecycle 3parent.link=index.html 4 5trainingnavtop=true 6previous.title=Pausing and Resuming an Activity 7previous.link=pausing.html 8next.title=Recreating an Activity 9next.link=recreating.html 10 11@jd:body 12 13<div id="tb-wrapper"> 14 <div id="tb"> 15 16 <h2>This lesson teaches you to</h2> 17 <ol> 18 <li><a href="#Stop">Stop Your Activity</a></li> 19 <li><a href="#Start">Start/Restart Your Activity</a></li> 20 </ol> 21 22 <h2>You should also read</h2> 23 <ul> 24 <li><a href="{@docRoot}guide/components/activities.html">Activities</a> 25 </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>Properly stopping and restarting your activity is an important process in the activity lifecycle 40that ensures your users perceive that your app is always alive and doesn't lose their progress. 41There are a few of key scenarios in which your activity is stopped and restarted:</p> 42 43<ul> 44 <li>The user opens the Recent Apps window and switches from your app to another app. The 45activity in your app that's currently in the foreground is stopped. If the user returns to your 46app from the Home screen launcher icon or the Recent Apps window, the activity restarts.</li> 47 <li>The user performs an action in your app that starts a new activity. The current activity 48is stopped when the second activity is created. If the user then presses the <em>Back</em> 49button, the first activity is restarted.</li> 50 <li>The user receives a phone call while using your app on his or her phone.</li> 51</ul> 52 53<p>The {@link android.app.Activity} class provides two lifecycle methods, {@link 54android.app.Activity#onStop()} and {@link android.app.Activity#onRestart()}, which allow you to 55specifically handle how your activity handles being stopped and restarted. Unlike the paused state, 56which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer 57visible and the user's focus is in a separate activity (or an entirely separate app).</p> 58 59<p class="note"><strong>Note:</strong> Because the system retains your {@link android.app.Activity} 60instance in system memory when it is stopped, it's possible that you don't need to implement the 61{@link android.app.Activity#onStop()} and {@link android.app.Activity#onRestart()} (or even {@link 62android.app.Activity#onStart()} methods at all. For most activities that are relatively simple, the 63activity will stop and restart just fine and you might only need to use {@link 64android.app.Activity#onPause()} to pause ongoing actions and disconnect from system resources.</p> 65 66<img src="{@docRoot}images/training/basics/basic-lifecycle-stopped.png" /> 67<p class="img-caption"><strong>Figure 1.</strong> When the user leaves your activity, the system 68calls {@link android.app.Activity#onStop onStop()} to stop the activity (1). If the user returns 69while the activity is stopped, the system calls {@link android.app.Activity#onRestart onRestart()} 70(2), quickly followed by {@link android.app.Activity#onStart onStart()} (3) and {@link 71android.app.Activity#onResume()} (4). Notice that no matter what scenario causes the activity to 72stop, the system always calls {@link android.app.Activity#onPause onPause()} before calling {@link 73android.app.Activity#onStop onStop()}.</p> 74 75 76 77<h2 id="Stop">Stop Your Activity</h2> 78 79<p>When your activity receives a call to the {@link android.app.Activity#onStop()} method, it's no 80longer visible and should release almost all resources that aren't needed while the user is not 81using it. Once your activity is stopped, the system might destroy the instance if it needs to 82recover system memory. In extreme cases, the system might simply kill your app process without 83calling the activity's final {@link android.app.Activity#onDestroy()} callback, so it's important 84you use {@link android.app.Activity#onStop()} to release resources that might leak memory.</p> 85 86<p>Although the {@link android.app.Activity#onPause onPause()} method is called before 87{@link android.app.Activity#onStop()}, you should use {@link android.app.Activity#onStop onStop()} 88to perform larger, more CPU intensive shut-down operations, such as writing information to a 89database.</p> 90 91<p>For example, here's an implementation of {@link android.app.Activity#onStop onStop()} that 92saves the contents of a draft note to persistent storage:</p> 93 94<!-- TODO: Find a better example for onStop, because this kind of thing should probably use a 95separate thread but that's too complicated to show here. --> 96<pre> 97@Override 98protected void onStop() { 99 super.onStop(); // Always call the superclass method first 100 101 // Save the note's current draft, because the activity is stopping 102 // and we want to be sure the current note progress isn't lost. 103 ContentValues values = new ContentValues(); 104 values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText()); 105 values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle()); 106 107 getContentResolver().update( 108 mUri, // The URI for the note to update. 109 values, // The map of column names and new values to apply to them. 110 null, // No SELECT criteria are used. 111 null // No WHERE columns are used. 112 ); 113} 114</pre> 115 116<p>When your activity is stopped, the {@link android.app.Activity} object is kept resident in memory 117and is recalled when the activity resumes. You don’t need to re-initialize components that were 118created during any of the callback methods leading up to the Resumed state. The system also 119keeps track of the current state for each {@link android.view.View} in the layout, so if the user 120entered text into an {@link android.widget.EditText} widget, that content is retained so you don't 121need to save and restore it.</p> 122 123<p class="note"><strong>Note:</strong> Even if the system destroys your activity while it's stopped, 124it still retains the state of the {@link android.view.View} objects (such as text in an {@link 125android.widget.EditText}) in a {@link android.os.Bundle} (a blob of key-value pairs) and restores 126them if the user navigates back to the same instance of the activity (the <a 127href="recreating.html">next lesson</a> talks more about using a {@link android.os.Bundle} to save 128other state data in case your activity is destroyed and recreated).</p> 129 130 131 132<h2 id="Start">Start/Restart Your Activity</h2> 133 134<p>When your activity comes back to the foreground from the stopped state, it receives a call to 135{@link android.app.Activity#onRestart()}. The system also calls the {@link 136android.app.Activity#onStart()} method, which happens every time your activity becomes visible 137(whether being restarted or created for the first time). The {@link 138android.app.Activity#onRestart()} method, however, is called only when the activity resumes from the 139stopped state, so you can use it to perform special restoration work that might be necessary only if 140the activity was previously stopped, but not destroyed.</p> 141 142<p>It's uncommon that an app needs to use {@link android.app.Activity#onRestart()} to restore 143the activity's state, so there aren't any guidelines for this method that apply to 144the general population of apps. However, because your {@link android.app.Activity#onStop()} 145method should essentially clean up all your activity's resources, you'll need to re-instantiate them 146when the activity restarts. Yet, you also need to instantiate them when your activity is created 147for the first time (when there's no existing instance of the activity). For this reason, you 148should usually use the {@link android.app.Activity#onStart()} callback method as the counterpart 149to the {@link android.app.Activity#onStop()} method, because the system calls {@link 150android.app.Activity#onStart()} both when it creates your activity and when it restarts the 151activity from the stopped state.</p> 152 153<p>For example, because the user might have been away from your app for a long time before 154coming back it, the {@link android.app.Activity#onStart()} method is a good place to verify that 155required system features are enabled:</p> 156 157<pre> 158@Override 159protected void onStart() { 160 super.onStart(); // Always call the superclass method first 161 162 // The activity is either being restarted or started for the first time 163 // so this is where we should make sure that GPS is enabled 164 LocationManager locationManager = 165 (LocationManager) getSystemService(Context.LOCATION_SERVICE); 166 boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 167 168 if (!gpsEnabled) { 169 // Create a dialog here that requests the user to enable GPS, and use an intent 170 // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action 171 // to take the user to the Settings screen to enable GPS when they click "OK" 172 } 173} 174 175@Override 176protected void onRestart() { 177 super.onRestart(); // Always call the superclass method first 178 179 // Activity being restarted from stopped state 180} 181</pre> 182 183 184 185 186<p>When the system destroys your activity, it calls the {@link android.app.Activity#onDestroy()} 187method for your {@link android.app.Activity}. Because you should generally have released most of 188your resources with {@link android.app.Activity#onStop()}, by the time you receive a call to {@link 189android.app.Activity#onDestroy()}, there's not much that most apps need to do. This method is your 190last chance to clean out resources that could lead to a memory leak, so you should be sure that 191additional threads are destroyed and other long-running actions like method tracing are also 192stopped.</p> 193 194