I am working on media play app based on this example: How to design activity-service interaction for a simple mp3 player?
It works fine, but I am unsure of how to request data from the service on demand. Specifically, I want to update a progress bar with the position of the song so the service should be able to give that information back to the client activity. The update should happen once a second.
Since it is only on demand (ie. only when the activity is visible) a broadcast would probably not be the solution.
So from what I know so far, I could either use a Messenger or I could bind the service.
What would be the most appropriate in the given situation, ie. with an update frequence of 1 second?
Addition:
As far as I know, the service will stop with the activity when it’s bound. This is of course not what I want with a music player. I have therefore tried both binding the service and sending commands with an intent using startService(). This seems to work fine, but is it a sensible approach? The reason I do this is that the service will keep on living after the activity stops when started by startService.
If you are looking for some guidelines for implementing music player the best place is to check android’s default Music Player source.
And for your question i think the proper way is to bind your activity to the service and keep the reference to service. Than simply start a timer in your activity and ask the service for current progress every second.
Addition:
Check again the source code. You’ll notice that when all activities are unbind from the service there is check if there is something to play. If there is something to play the service is not stopped and the playback continues otherwise the service is stopped ( to free it resources and wait for the time when it’s needed again). To see the above implemented in real life check the MusicPlaybackService‘s method onUnbind().