A (175)

(Tuis.) #1
CHAPTER 13: Android Service Class and Threads: Background Processing 487

Now you can add the functionality that you want this Service subclass to have in the background.
Since I didn’t get a chance to show you how to play long-format digital audio assets in the previous
chapter, I will take that opportunity here, and show you how to declare, instantiate, and utilize a
MediaPlayer object, so that you know how to do this to playback long-form audio.


Using a Service to Carry Out a Task


This topic fits into the chapter’s sequence perfectly, as it should probably be done as a Service
object, so that the UI thread in your main process does not become overwhelmed (overloaded) with
processing tasks, as it is already doing digital video decoding, multi-state ImageButtons, and hybrid
(frame and tween) animation, among other things.



  1. Declare a MediaPlayer object at the top of your AmbientService class and
    name it ambientAudioPlayer, as shown in Figure 13-3. I hope that you are
    getting comfortable declaring Android objects at the top of your class
    Java logic by now! Mouseover the red error highlight and select the
    Import ‘MediaPlayer’ (android.media) option so that Eclipse ADT will write
    the import android.media.MediaPlayer; Java statement for you.


Figure 13-3. Declare a MediaPlayer object named ambientAudioPlayer and then mouseover the error and choose Import



  1. The next step, as you are now familiar, is the instantiation and configuration
    of this ambientAudioPlayer MediaPlayer object. This is done using
    the MediaPlayer.create( ) method call, which you will use to pass your
    AmbientService Context object and a reference to an ambient.m4a MPEG-4
    AAC ambient planet background audio file. You will copy that file into your
    /res/raw folder next.

  2. Copy the ambient.m4a digital audio asset into your HelloUniverse project’s
    /res/raw folder from the book assets repository. I omit the screenshots here,
    as you have seen how this is done in previous chapters. Once this is done,
    you are ready to write code!

Free download pdf