It may happen that the service. With the service or not, although it can often be a sign that the program you developed is not as reliable as it should be. Even if you create a service, you still need to know when to pause and when to resume it.
I implemented a simple solution that seems to work for me without rebuilding the whole application in order to have a better mechanism for working with applications:
After launching mediaPlayer in the initial activity in which you want to start music:
In the initial and each subsequent action, create a member variable: private boolean mStopTheMusic = true;
Then, in EVERY active action that you want the music to continue to play and stop, it redefines the following accordingly: (note: the stop will be properly when any other application appears in the foreground, not yours. These are suitable moments to stop music) And at any time when you programmatically start a new activity on top of the current one, set mStopTheMusic = false so that your background music does not stop.
@Override public void onResume() { super.onResume(); mStopTheMusic = true; if (!MusicPlayer.IsMusicPlaying()) MusicPlayer.StartMusic(); } @Override public void onPause() { super.onPause(); if (mStopTheMusic) MusicPlayer.PauseMusic(); } @Override public void onBackPressed() { mStopTheMusic = false; super.onBackPressed(); }
source share