当我按下主屏幕或后退按钮时音乐不会停止

时间:2019-08-30 09:29:34

标签: java android

我正在用android做我的第一个游戏,快要完成了,但是我的音乐有问题,当您开始游戏或死亡时音乐会开始和结束,但是如果您按下主屏幕按钮或后退按钮它永远不会停止

我尝试在这里寻找解决方案,但是我的代码无法正常工作

这是SoundBank类,在游戏开始时称为playBackground,死时称为stopBackground

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();
        }
    }

}

我希望当我按下主页按钮或后退按钮时音乐会结束

2 个答案:

答案 0 :(得分:1)

在您的活动类中,添加以下替代方法:

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

因此,如果您的应用在后台运行且媒体正在运行,则它将停止。

答案 1 :(得分:0)

如果可以的话,建议您使用 <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" > <RelativeLayout . . . </RelativeLayout> </android.support.v7.widget.Toolbar> 确定何时将应用程序发送到后台,以执行所需的所有清理工作。

SO上有plenty of answers,其中详细说明了如何使用或实现此功能。