Adding Sounds to Sudoku

In this section, we're going to take what we've learned and add background music to the Sudoku game we've been building. One song will play during the opening screen, and another will play during the actual game. This will demonstrate not just how to play music but also some important life-cycle considerations.

To add music to the main screen, we just need to override these two methods in the Sudoku class:

Download Sudokuv3/src/org/example/sudoku/

@Override protected void onResume() { super.onResume();, R.raw.main);

@Override protected void onPause() { super.onPause(); Music.stop(this);

If you recall from Section 2.2, It's Alive!, on page 35, the onResume() method is called when the activity is ready to begin interacting with the user. This is a good place to start up the music, so we put a ) call there. The Music class will be defined shortly.

^ Why Does It Restart the Video When I Rotate the Display?

Android assumes by default that your program knows nothing about screen rotations. To pick up possible resource changes, Android destroys and re-creates your activity from scratch. That means onCreate() is called again, which means the video is started again (as this example is currently written).

This behavior will be fine for 90 percent of all applications, so most developers will not have to worry about it. It's even a useful way to test your application life-cycle and state-saving/restoring code (see Section 2.2, It's Alive!, on page 35). However, there are a couple of ways to be smarter and optimize the transition.

The simplest way is to implement onRetainNonConfigurationln-stance() in your activity to save some data that will be kept across the calls to onDestroy() and onCreate(). When you come back, you use getLastNonConfigurationInstance() in the new instance of your activity to recover that information. You can keep anything, even references to your current intent and running threads.

The more complicated way is to use the android:configChanges= property in AndroidManifest.xml to inform Android which changes you can handle. For example, if you set it to keyboardHidden\orientation, then Android will not destroy and re-create your activity when the user flips the keyboard. Instead, it will call onConfigurationChanged(Configuration) and assume you know what you're doing.*

*. See for more details.

0 0

Post a comment