如何在应用程序关闭/最小化时停止 MediaPlayer 声音?

Riy*_*ana 3 android android-button android-mediaplayer android-activity

在我的秒表应用程序中,开始按钮应该启动声音,暂停按钮应该停止声音。到目前为止,我的程序运行良好。

但是在播放声音的过程中,如果我返回或最小化应用程序,声音不会停止。它会继续播放(一直播放,即使设备处于空闲状态)。奇怪的是,当我重新打开应用程序以停止声音时,它永远不会停止。怎么解决这个问题呢?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timerValue = (TextView) findViewById(R.id.timerValue);

    startButton = (Button) findViewById(R.id.startButton);
    mp = MediaPlayer.create(getApplicationContext(), R.raw.sound);
    startButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            startTime = SystemClock.uptimeMillis();
            customHandler.postDelayed(updateTimerThread, 0);

               mp.start();
                mp.setLooping(true);


        }
    });

    pauseButton = (Button) findViewById(R.id.pauseButton);

    pauseButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            timeSwapBuff += timeInMilliseconds;
            customHandler.removeCallbacks(updateTimerThread);
            if(mp.isPlaying())
            {
                mp.pause();

            }
       }
    });
    resetButton = (Button) findViewById(R.id.reset);


    resetButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            timerValue.setText("" + 00 + ":"
                    + String.format("%02d", 00) + ":"
                    + String.format("%03d", 00));
            startTime = SystemClock.uptimeMillis();
            timeSwapBuff = 0;

        }
    });

}

private Runnable updateTimerThread = new Runnable() {

    public void run() {

        timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

        updatedTime = timeSwapBuff + timeInMilliseconds;

        int secs = (int) (updatedTime / 1000);
        int mins = secs / 60;
        secs = secs % 60;
        int milliseconds = (int) (updatedTime % 1000);
        timerValue.setText("" + mins + ":"
                + String.format("%02d", secs) + ":"
                + String.format("%03d", milliseconds));
        customHandler.postDelayed(this, 0);
    }

};
Run Code Online (Sandbox Code Playgroud)

bji*_*ang 5

您可以使用 Android 生命周期。

我想你可以mp.pause();打电话onStop()onDestroy()

示例代码:

@Override
    protected void onStop() {
        super.onPause();
        mp.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mp.pause();
    }
Run Code Online (Sandbox Code Playgroud)