Android: How to stop other active media players?

本小妞迷上赌 提交于 2019-12-31 07:10:09

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/14860258/android-how-to-stop-other-active-media-players

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!