我在调用播放音频文件的方法时启动了一个线程。
代码第一次运行正常,但是当我再次调用 play 方法时,我需要启动线程,就像第一次调用它一样。我试图中断线程甚至停止它,但似乎没有任何效果。
如何正确重启线程?
这是一些帮助解释的代码。
全局变量
private Thread thread1;
线程代码:
thread1 = new Thread(new Runnable()
{
@Override
public void run()
{
try {
int i=0;
final TextView timeDuration = (TextView) findViewById(R.id.timeDisplay);
final SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar1);
while (running)
{
info();
j = 0;
while(i>0 && running)
{
while(j<duration && running && (playStatus.getValue() == "TRANSITIONING" || playStatus.getValue() == "PLAYING"))
{
seekBar.setMax((int) duration);
seekBar.setProgress(0);
runOnUiThread(new Runnable()
{
public void run()
{
System.out.println("PLAYBACK STATUS: "+playStatus.getValue());
timeDuration.setText(""+(j+1));
seekBar.setProgress(j+1);
if(j==(duration-1))
{
setRunning(false);
}
}
});
Thread.sleep(1 * 1000);
j++;
if(seekBar.getProgress() == seekBar.getMax())
{
runOnUiThread(new Runnable()
{
public void run()
{
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.GONE);
timeDuration.setText(""+"0");
seekBar.setProgress(0);
flag = false;
System.out.println("J VALUE 1: = "+j);
duration = 0;
setRunning(false);
}
});
}
}
}
j = 0;
i++;
Thread.sleep(1 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
play();
此代码工作正常并播放曲目。然后它重置搜索栏并等待再次调用播放方法。
public void play()
{
try
{
thread1.start();
}
catch(Exception e)
{
return;
}
}
这里是推荐给我的 setRunning 方法。
public void setRunning(boolean b)
{
this.running = b;
}
如果有人知道这个问题的解决方案,我将不胜感激。