I\'m new to Android, so I have a problem. In Android I want to play background music as soon as my music player starts and have it continue even if the activity changes from
If you have not very much activities,
You can manage this task by adding boolean flags in activities, where you want music to be played.
When you stop one Activity these flags will show you, whether other Activities need your MediaPlayer
So in your main Activity:
public class MainActivity extends Activity {
static MediaPlayer introPlayer;
static boolean sActive;
@Override
protected void onResume() {
// starting the player if it is not playing
if (!introPlayer.isPlaying()) {
introPlayer.start();
introPlayer.setLooping(true);
}
// true when activity is active
sActive = true;
super.onResume();
}
@Override
protected void onPause() {
sActive = false;
super.onPause();
}
@Override
protected void onStop() {
// before stoping mediaplayer checking whether it is not used by other activities
if (introPlayer.isPlaying()
&& !(Activity2.sActive || Activity3.sActive)) {
introPlayer.pause();
}
super.onStop();
}
}
Other activities:
public class Activity2 extends Activity {
static boolean sActive;
@Override
protected void onPause() {
sActive = false;
super.onPause();
}
@Override
protected void onStop() {
// pausing the player in case of exiting from the app
if (MainActivity.introPlayer.isPlaying() && !(MainActivity.sActive || Activity3.sActive)) {
MainActivity.introPlayer.pause();
}
super.onStop();
}
@Override
protected void onResume() {
sActive = true;
if (!MainActivity.introPlayer.isPlaying()) {
MainActivity.introPlayer.start();
MainActivity.introPlayer.setLooping(true);
}
super.onResume();
}
}
And
public class Activity3 extends Activity {
static boolean sActive;
@Override
protected void onPause() {
sActive = false;
super.onPause();
}
@Override
protected void onStop() {
// pausing the player in case of exiting from the app
if (MainActivity.introPlayer.isPlaying() && !(MainActivity.sActive || Activity2.sActive)) {
MainActivity.introPlayer.pause();
}
super.onStop();
}
@Override
protected void onResume() {
sActive = true;
if (!MainActivity.introPlayer.isPlaying()) {
MainActivity.introPlayer.start();
MainActivity.introPlayer.setLooping(true);
}
super.onResume();
}
}