Life Cycles of the Rich and Famous
During its lifetime,each activity of an Android program can be in one
of several states,as shown in Figure 2.3,on the following page.You,
the developer,do not have control over what state your program is in.
That’s all managed by the system.However,you do get notified when
the state is about to change through the onXX()method calls.
You override these methods in your Activity class,and Android will call
them at the appropriate time:
?onCreate(Bundle):This is called when the activity first starts up.
You can use it to perform one-time initialization such as creating
the user interface.onCreate()takes one parameter that is either
null or some state information previously saved by the onSaveIn-
stanceState()method.
?onStart():This indicates the activity is about to be displayed to the
user.
?onResume():This is called when your activity can start interacting
with the user.This is a good place to start animations and music.
?onPause():This runs when the activity is about to go into the back-
ground,usually because another activity has been launched in
front of it.This is where you should save your program’s persis-
tent state,such as a database record being edited.
?onStop():This is called when your activity is no longer visible to
the user and it won’t be needed for a while.If memory is tight,
onStop()may never be called(the system may simply terminate
your process).
?onRestart():If this method is called,it indicates your activity is
being redisplayed to the user from a stopped state.
?onDestroy():This is called right before your activity is destroyed.If
memory is tight,onDestroy()may never be called(the system may
simply terminate your process).
?onSaveInstanceState(Bundle):Android will call this method to allow
the activity to save per-instance state,such as a cursor position
within a text field.Usually you won’t need to override it because
the default implementation saves the state for all your user inter-
face controls automatically.4
?onRestoreInstanceState(Bundle):This is called when the activity is
being reinitialized from a state previously saved by the onSave-
InstanceState()method.The default implementation restores the
state of your user interface.
Activities that are not running in the foreground may be stopped or
the Linux process that houses them may be killed at any time in order
to make room for new activities.This will be a common occurrence,
so it’s important that your application be designed from the beginning
with this in mind.In some cases,the onPause()method may be the last
method called in your activity,so that’s where you should save any data
you want to keep around for next time.