14Retained Fragments

Currently, HelloMoon does not handle rotation gracefully. Run HelloMoon, play the audio, and then rotate the device. The audio will stop abruptly.

Here is the problem: On rotation, the HelloMoonActivity is destroyed. As this is happening, the FragmentManager is responsible for destroying the HelloMoonFragment. The FragmentManager calls the fragment’s waning lifecycle methods: onPause(), onStop(), and onDestroy(). In HelloMoonFragment.onDestroy(), you release the MediaPlayer, which stops the playback.

Back in Chapter 3, you fixed a rotation-handling issue in GeoQuiz by overriding Activity.onSaveInstanceState(Bundle). You saved out the data and had the new activity read it back in. Fragment has an onSaveInstanceState(Bundle) ...

Get Android Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.