Java Reference
In-Depth Information
fromthetime
onPause()
returnsuntilthetime
onResume()
iscalled.Theactivity
won't again be killable until
onPause()
returns.
These seven methods define an activity's entire lifecycle and describe the following
three nested loops:
• The
entire lifetime
of an activity is defined as everything from the first call
to
onCreate(Bundle)
through to a single final call to
onDestroy()
.
An activity performs all its initial setup of “global” state in
onCreate(Bundle)
,andreleasesallremainingenvironmentalresourcesin
onDestroy()
. For example, when the activity has a thread running in the
background to download data from the network, it might create that thread in
onCreate(Bundle)
and stop the thread in
onDestroy()
.
• The
visible lifetime
of an activity is defined as everything from a call to
onStart()
throughtoacorrespondingcallto
onStop()
.Duringthistime,
theusercanseetheactivityonscreen,althoughitmightnotbeintheforeground
andinteractingwiththeuser.Betweenthesetwomethods,theactivitycanmain-
tainresourcesthatareneededtoshowitselftotheuser.Forexample,itcanre-
gisterabroadcastreceiverin
onStart()
tomonitorforchangesthatimpact
its user interface, and unregister this object in
onStop()
when the user can
nolongerseewhattheactivityisdisplaying.The
onStart()
and
onStop()
methods can be called multiple times, as the activity alternates between being
visible to and being hidden from the user.
• The
foreground lifetime
of an activity is defined as everything from a call to
onResume()
through to a corresponding call to
onPause()
. During this
time, the activity is in front of all other activities onscreen and is interacting
with the user. An activity can frequently transition between the resumed and
pausedstates;forexample,
onPause()
iscalledwhenthedevicegoestosleep
or when a new activity is started, and
onResume()
is called when an activ-
ityresultoranewintentisdelivered.Thecodeinthesetwomethodsshouldbe
fairly lightweight.
Note
Eachlifecyclecallbackmethodisahookthatanactivitycanoverridetoper-
formappropriatework.Allactivitiesmustimplement
onCreate(Bundle)
tocarry
out the initial setup when the activity object is first instantiated. Many activities also
implement
onPause()
to commit data changes and otherwise prepare to stop inter-
acting with the user.
Figure 12-3
illustrates an activity's lifecycle in terms of these seven methods.