gpt4 book ai didi

java - TimerTask 已经安排好了

转载 作者:太空宇宙 更新时间:2023-11-03 12:09:19 25 4
gpt4 key购买 nike

我有一个播放本地音频文件的 MediaPlayer 对象。我正在使用 TimerTask 在播放音频时更新 TextView 上 SeekBar 和文本的位置。

只有一个按钮。当用户按下按钮时,音频开始。当他们第二次按下时,音频停止。当他们第三次按下它再次开始播放时,应用程序崩溃并出现错误

'causedby: TimerTask is scheduled already and InvocationTargetException'.

这是我的代码:

    public void onAudioClicked(View v) {
if (mainPlayer == null) {
mainPlayer = MediaPlayer.create(this, R.raw.session1);
// Get audio duration and set textview
int d = mainPlayer.getDuration();
TextView t = (TextView)findViewById(R.id.totalTime);
t.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(d),
TimeUnit.MILLISECONDS.toSeconds(d) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));

sb.setProgress(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
timer = new Timer();
timer.schedule(task, 1000);
} else {
mainPlayer.stop();
mainPlayer.release();
mainPlayer = null;
timer.cancel();
task.cancel();
timer = null;
}
}

TimerTask task = new TimerTask(){
public void run(){
int currentPosition = 0;
int total = mainPlayer.getDuration();
sb.setMax(total);
while (mainPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mainPlayer.getCurrentPosition();
runOnUiThread(updateControlsRunnable);
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
sb.setProgress(currentPosition);
}

}
};

final Runnable updateControlsRunnable = new Runnable () {
public void run(){
int d = mainPlayer.getCurrentPosition();
TextView t = (TextView)findViewById(R.id.currentTime);
t.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(d),
TimeUnit.MILLISECONDS.toSeconds(d) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));
}
};

最佳答案

请试试这个代码块:

sb.setProgress(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
timer = new Timer();
MyTask task=new MyTask();
timer.schedule(task,0, 1000);

private class MyTask extends TimerTask {
public void run() {
//Your code...
}
}

关于java - TimerTask 已经安排好了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16509503/

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