A (175)

(Tuis.) #1

488 CHAPTER 13: Android Service Class and Threads: Background Processing



  1. Create an onCreate( ) method for the AmbientService Service subclass
    using the following Java code, shown in Figure 13-4. Then add the
    MediaPlayer.create( ) method call and .setLooping( ) method call to
    instantiate and configure your MediaPlayer object. That way, when your
    service is started, your MediaPlayer object will be as well:


@Override
public void onCreate() {
ambientAudioPlayer = MediaPlayer.create(this, R.raw.ambient);
ambientAudioPlayer.setLooping(true);
}

Figure 13-4. Add an onCreate( ) method, instantiate a MediaPlayer object, and then set it to loop using .setLooping( )


If you do not see the ambient.m4a digital audio asset in the /res/raw folder, as shown on the left
side of Figure 13-4, it simply means that you forgot to right-click on your project folder and select
the Refresh menu command after you copied the ambient background audio asset into the
/res/raw folder.



  1. You will also have red error highlights under the R.raw.ambient part of the
    MediaPlayer object instantiation until you use the Refresh command (utility).
    Just as it is logical to instantiate (create) and configure your MediaPlayer
    object in an .onCreate( ) method for this Service subclass, it is logical to
    start the MediaPlayer object playback using the .onStart( ) method for the
    Service. The Java code, shown in Figure 13-5, looks like the following:


@Override
public void onStart(Intent intent, int startid) {
ambientAudioPlayer.start();
}
Free download pdf