gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:58 24 4
gpt4 key购买 nike

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

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

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

};

最佳答案

您可以使用 Android 生命周期。

我认为您可以在 onStop()onDestroy() 上调用 mp.pause();

示例代码:

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

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

关于android - 如何在应用程序关闭/最小化时停止 MediaPlayer 声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com