我正在开发一个简单的音乐播放器。所以就有了一个由Thread更新的SeekBar。但是当我第二次选择一首歌时,它崩溃了( java.lang.IllegalThreadStateException: Thread already started )。
这是我的代码:
updateSeekBar = new Thread(){
@Override
public void run(){
int totalDuration = mp.getDuration();
int currentPosition = 0;
while(mp != null && currentPosition<totalDuration){
try{
sleep(500);
currentPosition = mp.getCurrentPosition();
sb.setProgress(currentPosition);
}catch (InterruptedException e){
Log.i(TAG, "Thread ERROR" );
e.printStackTrace();
}
}
}
};
...
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.i(TAG, "Thread State: " + updateSeekBar.getState().toString());
Uri u = Uri.parse(songList.get(position).getPath().toString());
if(mp!=null){ mp.stop(); mp.reset(); mp.release(); }
mp = MediaPlayer.create(getApplicationContext(), u);
mp.start();
sb.setMax(mp.getDuration());
updateSeekBar.start();
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
}
@Override
public void onStartTrackingTouch(SeekBar seekBar){
}
@Override
public void onStopTrackingTouch(SeekBar seekBar){
mp.seekTo(seekBar.getProgress());
}
});
我怎样才能避免崩溃?
最佳答案
您必须在启动之前检查该线程的状态。
if (thread.getState() == Thread.State.NEW) {
thread.start();
}
关于java.lang.IllegalThreadStateException : Thread already started 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40437387/