Android 媒体播放器搜索栏
我有一个创建、播放和处理媒体播放器(只是音频)的服务,但我在主要活动中有一个搜索栏,我想自然地显示音频文件的进度并允许用户搜索到不同的位置。
我花了很长时间才弄清楚:将 UI 中的搜索栏连接到服务中的媒体播放器的最佳或正确方法是什么?
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 seekbar in the UI to the mediaplayer in the service?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是我执行此操作的方法:
绑定到播放音频的服务。服务器在
onBind
中返回的接口应该具有getCurrentPos()
和getDuration()
函数。在您的 Activity 的
onCreate
中绑定到服务onResume
中使用Handler
的postDelayed
函数开始更新。onPause
中,停止通过postDelayed
函数发布的所有回调。postDelayed
的 runnable 中运行boundService.getCurrentPos()
和boundService.getDuration()
并相应地更新搜索栏。总而言之,您应该使用服务绑定和处理程序来进行定期更新。
Handler
进行定期更新阅读这个问题:延迟重复任务?Here is how I would do this:
Bind to service that plays audio. The interface that server returns in
onBind
should havegetCurrentPos()
andgetDuration()
functions.In your Activity's
onCreate
bind to serviceonResume
useHandler
'spostDelayed
function to start updates.onPause
stop all callbacks posted viapostDelayed
function.postDelayed
runboundService.getCurrentPos()
andboundService.getDuration()
and update the seekbar appropriately.To summarize, you should use service binding and handler for recurring updates.
Handler
for periodic updates read this question: Repeat a task with a time delay?尝试查看 MediaController 看看它是否对您有用。
Try taking a look at MediaController to see if it's of use to you.
您还可以尝试 Square 的 Otto
您只需要创建一个类
SeekBarSyncEvent.java
SeekBarSyncEvent
类从总线发布事件来从活动初始化搜索栏您的服务中的
onPrepared()
方法。最后在您的 Activity 上创建
@Subscribe
方法,以便它调用您的seekBarUpdate()
方法。这应该工作得很好,很漂亮并且易于维护。
You can also try Otto from Square
You just need to create a class
SeekBarSyncEvent.java
, put the parameters you need in there:Then you can initialize the seekbar from the activity by posting an event from the bus with your
SeekBarSyncEvent
class in theonPrepared()
method from your service.Finally create the
@Subscribe
method on your activity so it calls to yourseekBarUpdate()
method.This should work fine, nice and easy to maintain.