Challenge: Play Sound Across Rotation

Currently, BeatBox will stop playing the sound if you rotate the device. This challenge will fix that.

The main issue in the current app is where you save your BeatBox object. Your MainActivity holds a reference to your BeatBox, but it is destroyed and re-created across rotation. This means that your initial BeatBox releases the SoundPool and re-creates it every time you rotate.

You have already seen how to persist information across rotation in GeoQuiz and CriminalIntent. Add a Jetpack ViewModel to BeatBox to keep your BeatBox object alive across rotation.

You can expose the BeatBox object as a public property from your ViewModel. This way, MainActivity can access the BeatBox instance from ...

Get Android Programming: The Big Nerd Ranch Guide, 4th Edition 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.