I spend about 20 hours until now and my problem there still is . I am creating an android application that has several Activities (mainMenu , aboutUs,setting). I followed the best answered of below link and that was O.K . Music played using asyncTask isn't stopping by using cancel
When i run my app,(my code is in mainActivity ), the music begin and it does not stop when navigate to other Activities . This is GOOD . But i put a ToggleButton in my setting_activity Activity that i hope this Button starts and stops this music. NOW my question is how can i stop and/or start music again from setting_activity ?
in another solution : I create a class MusicManager and i call it`s start and stop . But this was several problems too :
- Music started in mainMenu_activity but only play for about 15 seconds and then stopped.
I could not stop the music from another activities.At this time i play music in mainMenua_ctivity as this line codes :
MusicManager mm = new MusicManager(this, R.raw.background_sound); mm.play();
How can i stop playing that ? 3. The music stopped when i navigate to other activities .
public class MusicManager implements OnPreparedListener {
static MediaPlayer mPlayer;
Context context;
private int mySoundId;
public MusicManager(Context ctx, int musicID) {
context = ctx;
mySoundId = musicID;
mPlayer = MediaPlayer.create(context, mySoundId);
mPlayer.setOnPreparedListener(this);
}
public void play() {
mPlayer = MediaPlayer.create(context, mySoundId);
}
public void stop() {
mPlayer.stop();
mPlayer.release();
}
@Override
public void onPrepared(MediaPlayer player) {
player.start();
mPlayer.setLooping(true);
mPlayer.setVolume(25, 25);
}
}
Finally i want to play a background music in all activities without stop/start music . How can i do it ?
You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.
Here are some code example about it: https://stackoverflow.com/a/8209975/2804473 The code below is written by Synxmax here at StackOverflow, and covered in the link above:
The top answer is correct, however you have to add the service to the manifest file.
Simon's answer above is correct. I had similar problem where I have fragments which had music player and I needed to go back to that UI on click of a button. Your case is similar but instead of going back to UI, you want to control playback. Here is what I did for my application. This takes care of playback of audio list including shuffle and repeat functionality. This takes care of showing media controls in notification bar too.
MusicPlayerService
with following code:<service android:name=".service.MediaPlayerService" />