2
votes

I have a MediaPlayer that plays music starting in the main (launcher) activity. I have stumbled across two problems.

  1. When I press the home button or my app loses focus in general, the music is still playing.

  2. When I return to the main (launcher) activity the mediaPlayer starts again (creates new mediaPlayer) and the result is that there are two MediaPlayers playing the same file simultaneously.

*For the first problem I have tried to stop the music in onStop() method but the music stops when I go from main to other activities which is something I don't want and onDestroy doesn't work.

My code:

if (player == null) {
    player = MediaPlayer.create(this, R.raw.music);
    player.setLooping(true);
    if (!player.isPlaying()) {
       player.start();
    }
}

P.S I want the music to playing not only in main but on the other activities too.

2
Have you tried to stop the MediaPlayer in the onDestroy() method? - miguelarc
For your 1st problem, use ActivityLifeCycleCallback to get calback if your app is visible like here stackoverflow.com/a/50510902/5689605 For your second problem create a singleton media player in your app, and either play that or stop that. - Debanjan

2 Answers

0
votes

Your MediaPlayer is not being properly stopped when you exit. onStop() is called whenever the activity stops, either for a higher priority activity to enter, or to be "paused" by another activity (check activity lifecycle here). Try the stopPlaying() method from this answer in your onDestroy() method.

For the 2nd problem, you can follow one of two ways: either stick with the stopPlaying() method from the answer I gave you above, to stop the MediaPlayer and set it to null, or check the MediaPlayer existance at the beginning of the activity (try checking this before your MediaPlayer instantiation, otherwise the MediaPlayer will always exists).

0
votes

Make sure that you release the MediaPlayer resources that you created on destroying the activity, by calling player.release() and nullifying the MediaPlayer in onDestroy() method.

     @Override
 protected void onPause() {
      super.onPause();

      if(player != null)
             player.stop();
 }

 @Override
 protected void onStop() {
      super.onStop();

      if(player != null)
             player.stop();

 }

 @Override
 protected void onDestroy() {
      super.onDestroy();

      if(player != null)
             player.stop();

 }