简体   繁体   English

如何在多个片段之间共享MediaPlayer对象?

[英]How to share a MediaPlayer object between multiple fragments?

I have set up 1 Main Activity (that extends Activity class) and 2 Fragments (that extends the fragment class). 我设置了1个Main Activity(扩展了Activity类)和2个Fragments(扩展了Fragment类)。

I've tried setting up an Interface, which is implemented by the 2 fragments. 我尝试设置一个由2个片段实现的接口。 And each fragment implements the particular function from the interface like this: 每个片段都从接口实现以下特定功能:

public stopMusic()
{
  mediaplay.release(); // here, the mediaplay object belongs to only the respective fragment
}

Now, I know doesn't work, because the MediaPlayer object is not common to both fragments, ie it's not being shared among them. 现在,我知道这是行不通的,因为MediaPlayer对象对于两个片段而言并不通用,即,它们之间没有共享。

I'm looking to release the mediaplayer object streaming a file in Fragment1.java, if I hit a button from another fragment, like Fragment2java. 如果我按下另一个片段(例如Fragment2java)中的按钮,我正在寻求释放流式播放器在Fragment1.java中的文件的媒体播放器对象。 Likewise, to release the mediaplayer object streaming a file in Fragment2.java, if I hit a button from Fragment1.java. 同样,如果我按Fragment1.java中的一个按钮,则要释放在Fragment2.java中流传输文件的mediaplayer对象。

How can I make this happen? 我怎样才能做到这一点? An example code would really help. 示例代码确实有帮助。

Let's say fragment A is the controlling fragment and fragment B is the media player. 假设片段A是控制片段,片段B是媒体播放器。 All communication should be done via the parent Activity. 所有通信都应通过父活动进行。 So in fragment B you create 'public interface(s)' which the parent activity implements, then the parent Activity should call the method(s) in fragment B. 因此,在片段B中,您将创建父活动实现的“公共接口”,然后父活动应调用片段B中的方法。

Also depending on what you are really doing with the media player or whatever, does that belong in the background as opposed to fragment B? 还取决于您对媒体播放器的实际操作或其他功能,与片段B相对应,它是在后台吗?

Note: fragments should be loosely coupled and never communicate from fragment to fragment, always communicate via the parent Activity. 注意:片段应该松散耦合,并且永远不要在片段之间进行通信,始终通过父Activity进行通信。

Hope this helps. 希望这可以帮助。

You have to do the following: 您必须执行以下操作:

  • In your MainActivity make an attribute (lets call it myMediaPlayerObject ) 在您的MainActivity中创建一个属性(将其myMediaPlayerObject
  • In your fragments you can get current activity like here: Activity a = getActivity(); 在您的片段中,您可以获得如下所示的当前活动: Activity a = getActivity();
  • Now you can cast this activity and call a function like here: ((MainActivity)a).stopMusic(); 现在您可以进行此活动的转换并调用如下函数: ((MainActivity)a).stopMusic(); or directly use the object ((MainActivity)a).myMediaPlayerObject 或直接使用对象((MainActivity)a).myMediaPlayerObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM