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