A Service that Plays Audio

The previous service ran in the main thread of the app. This service is a IntentService, which executes in a separate thread.

An IntentService is destroyed as soon as its onHandleIntent method has completed. We go into an infinite loop to prevent that from happening. Meanwhile, the MediaPlayer.OnCompletionListener calls stopSelf, which calls onDestroy.

Source code in AudioService.zip

  1. AudioServiceActivity.java
  2. AudioService.java
  3. R.java
  4. main.xml
  5. musette.mid
  6. AndroidManifest.xml declares the service

Create the project

See MediaPlayer for the raw folder.

In the Android Studio project view, select the folder that holds MainActivity.java.
File → New → Service → Service (IntentService)
Class Name: AudioService
Finish

Things to try

  1. We saw in Offer how to print the name and ID number of the thread that is executing a given line of code. Demonstrate that the Activity and the Service are executed by two differnt threads.

  2. We’d want to use an IntentService for a lengthy download or database access, if we want these jobs to be executed by a separate thread and to keep running even after the death of the Activity that started them. But it might be overkill to use an IntentService to play a sound file. See prepare vs. prepareAsync and MediaPlayer.OnPreparedListener.