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.javaAudioService.javaR.javamain.xmlmusette.midAndroidManifest.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.