0

I'm trying to create a music player. My application has 2 players -

(a) plays songs from the memory

(b) plays online music streams using URLs

The home/default activity of my app is (a). For player (b) there is a separate activity.

Issue is when user presses the play button in activity (b) to play the URL stream, the track from the memory gets played.

It seems like MediaPlayer from activity (a) is still active.

So I want:

  • If user presses the play button, all other media player gets stopped.

    Is there any way to get reference of other media players; Check if they are active; If yes, then stop them.

From a vague perspective, I thought this can be done by sending a broadcast to the Service of activity (a), and make a function there which will listen it and stop the player.

But it seems a bit brute to me & also how should I get the reference of the player in (a).

Hope I've cleared my doubt.

Please suggest.

Thank You

reiley
  • 3,759
  • 12
  • 58
  • 114

1 Answers1

5

You can create a class in your project and call it MediaPlayerRegistry where you store a reference to each mediaPlayer object you are currently using. and access them anywhere in your app to stop / release / replay them. it would look something like this:

public class MediaPlayerRegistry {
      public static List<MediaPlayer> mList = new ArrayList<MediaPlayer>();
}

Then from any activity you have you can call:

MediaPlayerRegistry.mList.put(MediaPlayer mPlayer);

to add it to your registry... and when you want to release it stop any running object.

for ( MediaPlayer player : MediaPlayerRegistry.mList) {
if (player != null && player.isplaying() {
      player.release();
}
}

just think of it as your own pool of MediaPlayer objects

Mr.Me
  • 9,192
  • 5
  • 39
  • 51
  • Thank you, that is one easy solution. But the mediaPlayer may not be playing, so isPlaying() will return false. How to solve it? – reiley Feb 15 '13 at 10:18
  • I've done some back tracking & found this problem. (http://stackoverflow.com/a/14860443/1433826) – reiley Feb 15 '13 at 21:11