weird behaviour of service and media player

微笑、不失礼 提交于 2020-12-15 06:51:57

问题


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:

  1. I start the service and bind to it from the activity.
  2. the service invokes the MediaPlayer Object with a valid mediaLocation and the media starts playing
  3. I destroy the activity, while being destroyed, I use the unbindService(mServiceConn) method to unbind to the service, the media keeps playing
  4. I close the service, from it's close button in the notification UI, which calls it's stopSelf method, and remove the notification using the notificationManager.cancel(ID)
  5. At this point, since the service was both started and bound I have called both the unbind and stopSelf methods, so acc. to the android docs this would be enough to stop a started-bound service.
  6. The notification closes
  7. and the service's onDestroy also gets called(checked using Logcat outputs)
  8. 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.


回答1:


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.



来源:https://stackoverflow.com/questions/64634815/weird-behaviour-of-service-and-media-player

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!