When a Fragment
is attached to an Activity
as we did in Chapter 5 and will do in this chapter, its lifecycle is tied to that of its parent Activity
. There are six Activity
lifecycle methods that have corresponding Fragment
lifecycle methods—onCreate
, onStart
, on-Resume
, onPause
, onStop
and onDestroy
. When the system calls these methods on an Activity
, it will also call these corresponding methods (and potentially other Fragment
lifecycle methods) on all of the Activity
’s attached Fragment
s.
This app uses Fragment
lifecycle methods onPause
and onDestroy
. An Activity
’s onPause method is called when another Activity
receives the focus, which pauses the one that loses the focus and sends it to the background. When an Activity
hosts Fragment
s and the Activity
is paused, all of its Fragment
s’ onPause methods are called. In this app, the CannonView
is displayed in a CannonGameFragment
(Section 6.7). We override onPause
to suspend game play in the CannonView
so that the game does not continue executing when the user cannot interact with it—this saves battery power. Many Activity
lifecycle methods have corresponding methods in a Fragment
’s lifecycle.
When an Activity
is shut down, its onDestroy method is called, which in turn calls the onDestroy methods of all the Fragment
s hosted by the Activity
. We use this method in the CannonFragment
to release the CannonView
’s sound resources.
We discuss other Activity
and Fragment
lifecycle methods as we need them. For more information on the complete Activity
lifecycle, visit:
and for more information about the complete Fragment
lifecycle, visit: