Android media player seekbar
I have a service that creates, plays and handles a mediaplayer (just audio), yet I have a seekbar in the main activity that I want to, naturally, show the progress of the audio file and allow the user to seek to various positions.
What I'm having a hell of a time figuring out is: what would be the best or proper way to connect the 开发者_Go百科seekbar in the UI to the mediaplayer in the service?
Here is how I would do this:
Bind to service that plays audio. The interface that server returns in
onBindshould havegetCurrentPos()andgetDuration()functions.In your Activity's
onCreatebind to service- In your Activity's 
onResumeuseHandler'spostDelayedfunction to start updates. - In your Activity's 
onPausestop all callbacks posted viapostDelayedfunction. - In runnable that is passed to 
postDelayedrunboundService.getCurrentPos()andboundService.getDuration()and update the seekbar appropriately. 
To summarize, you should use service binding and handler for recurring updates.
- For bound services read "Bound services" documentation (local bounded service should be sufficient in your scenario).
 - How to user 
Handlerfor periodic updates read this question: Repeat a task with a time delay? 
Try taking a look at MediaController to see if it's of use to you.
You can also try Otto from Square
You just need to create a class SeekBarSyncEvent.java, put the parameters you need in there:
- int progress
 - int duration
 - boolean fromUser
 - whatever you need
 
Then you can initialize the seekbar from the activity by posting an event from the bus with your SeekBarSyncEvent class in the onPrepared() method from your service.
Finally create the @Subscribe method on your activity so it calls to your seekBarUpdate() method.
This should work fine, nice and easy to maintain.
 加载中,请稍侯......
      
精彩评论