在活动之间传递媒体播放器对象 [英] Passing media player object between activities

查看:81
本文介绍了在活动之间传递媒体播放器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在活动之间传递MediaPlayer对象,以便在整个应用程序中保持恒定的声音播放.

I wanted to know how to pass a MediaPlayer object between activities so that I can maintain a constant sound play through out the application.

推荐答案

您不要在活动之间传递 MediaPlayer 对象".

You don't "pass a MediaPlayer object between activities".

您需要从自定义服务在后台播放声音,并使您的活动与此服务互动.

You need to access MediaPlayer from a custom Service to play sound in the background, and have your activities interact with this service.

对于互动,我个人的偏好是使用 AIDL 进行绑定.每当我尝试使用简单的意图和 onStartCommand ()时,它都显示出不足以进行活动/服务交互(我也使用音频).但这可能对您有用.

For interaction my personal preference is binding using AIDL. Whenever I tried to use simple intents and onStartCommand() it revealed insufficient for activity/service interaction (I work with audio too). But it could work for you.

使用AIDL和绑定,您可以公开自定义功能,例如 play(uri) pause() rewind()等....如果尚未实例化 MediaPlayer 实例,则将在 play(uri)中创建该实例,并在服务的 onDestroy()中释放该实例.代码>.

With AIDL and binding, you could expose custom functions such as play(uri), pause(), rewind(), etc.... The MediaPlayer instance would be created in play(uri) if it isn't already instantiated, and released in your service's onDestroy().

您甚至可以向 RemoteCallbackList 注册一个侦听器,以获取有关位置变化或其他事件的通知.请参阅AIDL文档上的示例.这样做的好处是您的服务可以检测到侦听器何时注销.这样,如果另一个侦听器(活动)未快速注册,则在调用 stopSelf()之前,您可以在服务中设置少量超时.这很有用,因为您不一定知道某个活动是否因用户按下主屏幕按钮而暂停,或者因为他正在从一个活动切换到另一个活动而暂停.

You can even register a listener with a RemoteCallbackList to get notified about position changes or some other events. See the examples on the AIDL documentation. What's nice about this is that your service can detect when a listener unregisters. This way you can have a small timeout in the service before you call stopSelf(), if another listener (activity) doesn't register quickly. That's useful because you don't necessarily know if an activity pauses because the user pressed the home button, or because he's cycling from one activity to the other.

是的,这需要一点工作;)

Yeah, it needs a little work ;)

注意:您仍然需要在绑定之前调用 startService(),否则只要活动取消绑定,该服务就会停止.

Note: you still need to call startService() before binding, otherwise the service will stop whenever an activity unbinds.

这篇关于在活动之间传递媒体播放器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆