简体   繁体   中英

Music doesn't stop when I press home or back button

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM