A (175)

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

Notice that this is the only method of the three that takes two parameters—an Intent object
named intent, which is needed to start the Service, and a start ID integer value, which you can
use in your code inside the method if you want to have different types of Service objects starting
the programming logic. Inside of the .onStart( ) method you have your code that calls the .start( )
method off of the ambientAudioPlayer MediaPlayer object.


Now that you have created methods that create and start your Service subclass, you only need to
implement the method that stops and removes your Service subclass from system memory.


This is typically called the .onDestroy( ) method, and is one of the three methods that is required to
be coded (implemented) when you create any Android Service subclass. Once you finish coding
your .onDestroy( ) method, your Service subclass will be ready for use, and you can declare it for
use in your AndroidManifest.xml file.


Just like you start your ambientAudioPlayer MediaPlayer object’s playback loop in the
AmbientService Service class’s .onStart( ) method, you similarly stop the ambientAudioPlayer
MediaPlayer object playback loop in your Service class’s .onDestroy( ) method.


An onDestroy( ) method allows developers to control their own optimization of system memory
usage, so that the Android OS does not have to do it by stopping the process. When the Service
subclass is stopped via this .onDestroy( ) method, the MediaPlayer object is also stopped.
Therefore, the ambient planet sound digital audio loop does not continue to play, as the MediaPlayer
object exists independent of (or next to) the Service object.


Figure 13-5. Add an onStart( ) method and then start the ambientAudioPlayer MediaPlayer object playback loop using .start( )

Free download pdf