I have an activity that starts and binds to a music playing service, hence I have implemented both the onStartCommand
and onBind
methods. I have a MediaPlayer
object in the service used to play media files.
These are the steps I perform:
- I start the service and bind to it from the activity.
- the service invokes the
MediaPlayer
Object with a valid
mediaLocation and the media starts playing - I destroy the activity, while being destroyed, I use the
unbindService(mServiceConn)
method to unbind to the service, the
media keeps playing - I close the service, from it’s close button in the notification UI,
which calls it’sstopSelf
method, and remove the notification
using thenotificationManager.cancel(ID)
- At this point, since the
service
was bothstarted
andbound
I
have called both theunbind
andstopSelf
methods, so acc. to the android docs
this would be enough to stop a started-bound service. - The notification closes
- and the
service
‘sonDestroy
also gets called(checked using
Logcat outputs) - yet the
MediaPlayer
keeps on playing the music
My confusion is, if the UI(activity) and notification both are destroyed, then shouldn’t the whole process be destroyed, hence making the MediaPlayer
stop? Or is the service
not destroyed, which is why the media is still being played?
I could work around the media being played by forceFully stopping it in the service
‘s onDestroy
or similar methods but how do I even know the service (and the process in it’s entirety) is all cleaned up? So, it’s not taking up any unseen resources?
PS.: The code was too long to post a runnable example, so no code was posted, yet mostly it’s just standard stuff, nothing from personal logic was added.
Advertisement
Answer
When you use media player
to play music, the media player does not directly play the music, but requests the playback engine of the android system to play the music.
When you no longer use the playback engine of the android system, you should call the release()
method of the media player
to release system resources.