6.3.3. Activity and Fragment Lifecycle Methods

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 Fragments.

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 Fragments and the Activity is paused, all of its Fragments’ 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 Fragments 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset