Game Development Reference
In-Depth Information
a paused state. For our games, we only need to know that we are now
actually running, and the
onResume()
method signals that to us.
The activity can be destroyed silently after
onPause()
. We should never
assume that either
onStop()
or
onDestroy()
gets called. We also know
that
onPause()
will always be called before
onStop()
. We can therefore
safely ignore the
onStop()
and
onDestroy()
methods and just override
onPause()
. In this method, we have to make sure that all the states
we want to persist, like high scores and level progress, get written to
external storage, such as an SD card. After
onPause()
, all bets are off,
and we won't know whether our activity will ever get the chance to
run again.
2.
We know that
onDestroy()
might never be called if the system decides
to kill the activity after
onPause()
or
onStop()
. However, sometimes we'd
like to know whether the activity is actually going to be killed. So how
do we do that if
onDestroy()
is not going to get called? The
Activity
class has a method called
Activity.isFinishing()
that we can call at
any time to check whether our activity is going to get killed. We are at
least guaranteed that the
onPause()
method is called before the activity
is killed. All we need to do is call this
isFinishing()
method inside the
onPause()
method to decide whether the activity is going to die after the
onPause()
call.
3.
This makes life a lot easier. We only override the
onCreate()
,
onResume()
, and
onPause()
methods.
In
ï?®
onCreate()
, we set up our window and UI component to which we render
and from which we receive input.
ï?®
onResume()
, we (re)start our main loop thread (discussed in Chapter 3).
In
In
ï?®
onPause()
, we simply pause our main loop thread, and if
Activity.isFinishing()
returns
true
, we also save to disk any state we
want to persist.
Many people struggle with the activity life cycle, but if we follow these simple rules, our game
will be capable of handling pausing, resuming, and cleaning up.
In Practice
Let's write our first test example that demonstrates the activity life cycle. We'll want to have
some sort of output that displays which state changes have happened so far. We'll do this in
two ways:
The sole UI component that the activity will display is a
TextView
. As its
name suggests, it displays text, and we've already used it implicitly for
displaying each entry in our starter activity. Each time we enter a new
state, we will append a string to the
TextView
, which will display all the
state changes that have happened so far.
1.