Java TimerTask已计划好
我有一个播放本地音频文件的Java TimerTask已计划好,java,android,android-mediaplayer,timertask,Java,Android,Android Mediaplayer,Timertask,我有一个播放本地音频文件的MediaPlayer对象。我正在使用TimerTask在音频播放时更新搜索栏的位置和文本视图上的文本 有一个按钮。当用户按下按钮时,音频开始。当他们第二次按下时,音频停止。当他们第三次按它开始再次播放时,应用程序因错误而崩溃 'causedby: TimerTask is scheduled already and InvocationTargetException'. 这是我的密码: public void onAudioClicked(View v) {
MediaPlayer
对象。我正在使用TimerTask
在音频播放时更新搜索栏的位置和文本视图上的文本
有一个按钮。当用户按下按钮时,音频开始。当他们第二次按下时,音频停止。当他们第三次按它开始再次播放时,应用程序因错误而崩溃
'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))));
}
};
音频点击时的公共无效(视图v){
如果(mainPlayer==null){
mainPlayer=MediaPlayer.create(这个,R.raw.session1);
//获取音频持续时间并设置textview
int d=mainPlayer.getDuration();
TextView t=(TextView)findViewById(R.id.totalTime);
t、 setText(字符串格式(“%d:%d”),
时间单位为毫秒至分钟(d),
时间单位。毫秒。至秒(d)——
TimeUnit.MINUTES.toSeconds(TimeUnit.ms.toMinutes(d));
某人取得进步(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
定时器=新定时器();
时间表(任务,1000);
}否则{
mainPlayer.stop();
mainPlayer.release();
mainPlayer=null;
timer.cancel();
task.cancel();
定时器=空;
}
}
TimerTask任务=新的TimerTask(){
公开募捐{
int currentPosition=0;
int total=mainPlayer.getDuration();
sb.setMax(总计);
while(mainPlayer!=null&¤tPosition
请尝试此代码块:
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...
}
}
您是否正在使用
定时器
变量,在其他方法中的某个位置来实现相同的目的?