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
.
AudioServiceActivity.java
AudioService.java
R.java
main.xml
musette.mid
AndroidManifest.xml
declares the serviceSee 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
Activity
and the
Service
are executed by two differnt threads.
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
.