简体   繁体   中英

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).

I've tried setting up an Interface, which is implemented by the 2 fragments. 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.

I'm looking to release the mediaplayer object streaming a file in Fragment1.java, if I hit a button from another fragment, like Fragment2java. Likewise, to release the mediaplayer object streaming a file in Fragment2.java, if I hit a button from Fragment1.java.

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. 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.

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?

Note: fragments should be loosely coupled and never communicate from fragment to fragment, always communicate via the parent Activity.

Hope this helps.

You have to do the following:

  • In your MainActivity make an attribute (lets call it myMediaPlayerObject )
  • In your fragments you can get current activity like here: Activity a = getActivity();
  • Now you can cast this activity and call a function like here: ((MainActivity)a).stopMusic(); or directly use the object ((MainActivity)a).myMediaPlayerObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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