Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate between Music Playback Service and UI Thread

I have got a list of Music Titles in a ListView.

I can click on each item to play the Music through a MediaPlayer in a Service.

Now I want to implement 2 Features:

  • Music ProgressBar which is showing the current position in the song
  • The service shall continue playing when Song is over with the next song in the list

So how can I update the UI from a background service? (I know there are some solutions on Stackoverflow but they seem to me a little bit of an overkill to send a Broadcast each Second from the Service i.e.) Do I have to use Binding? What is the benefit of Binding? Right now I just start the service with an Intent (startService(intent)) which contains the Song path.

What about the 2nd question? How can I do that?

like image 877
Sebastian Oberste-Vorth Avatar asked Nov 19 '25 04:11

Sebastian Oberste-Vorth


1 Answers

I guess you built the service by yourself. Thus you know how it is built and how to get access to a mediaPlayer reference. What you need to do is to transform your service into a bound service. Maybe you will want your service to be started via startService (otherwise the bound service won't survive your activity), but afterwards, you will have to bind to it from inside your activity.

Once you are bound, you will get a IBinder (that you will define) and will be able to export the mediaPlayer reference to the bound activity through this IBinder. Afterwards, everything is quite straightforward, plug a listener on the media player and update your UI (in the UI thread !).

Also, you will need your service to be put forward.

like image 110
Snicolas Avatar answered Nov 20 '25 18:11

Snicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!