0

I'm doing my first game in android, it's almost done, but I have a problem with the music, the music starts and ends when you start the game or die, but if you press the home button or the back button it doesn't ever stop

I have tried looking here for solution, but nothing works well with my code

This is the SoundBank class, playBackground it's called when the game starts, stopBackground when you die

public class SoundBank {

    Context context;
    MediaPlayer background, hit;
    int mute;
    GameOver gameOver = new GameOver();

    public SoundBank(Context context){
        this.context = context;
        hit = MediaPlayer.create(context,R.raw.sfx_hit);
        background = MediaPlayer.create(context,R.raw.background);
        mute = gameOver.getMute();
    }

    public void playHit(){
        if(mute != 1){
            hit.start();
        }
    }

    public void playBackground(){
        if(background != null){
            background.start();
            background.setLooping(true);
        }
    }

    public void stopBackground(){
        if(background != null){
            background.stop();
        }
    }

}

I expect the music to end when I press home button or back button

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30

2 Answers2

1

In your activity class add the following overriden method:

@Override
public void onPause() {
    super.onPause();
    stopBackground();
}

So if your app is going in background and media is running then it will be stopped.

Hari N Jha
  • 484
  • 1
  • 3
  • 11
  • 1
    i would also suggest saving a boolean flag to indicate it was paused due to home press or back press. and in onResume another method that you should override, check if the music needs to be automatically resumed – Kushan Aug 30 '19 at 10:03
  • yes I agree if the requirement goes in this direction then it can be paused here and can be resumed in `onResume()` method. – Hari N Jha Aug 30 '19 at 10:20
0

If you can, I suggest you use ProcessLifecycleOwner to determine when your application has been sent to the background, to perform all the cleanup you need.

There are plenty of answers here on SO that detail how to use or implement this.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144