当调用一个方法播放音频文件时,我正在启动一个线程。
代码第一次运行正常,但当我再次调用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;
}
如果有人知道这个问题的解决方案,我将不胜感激
线程不应该手动停止。您应该在while
循环中使用布尔值而不是true
,并在想要停止时通过setter将布尔值设置为false
:
private boolean running;
@Override
public void run(){
running = true;
while(running) {...}
}
public void setRunning(boolean b){
this.running = b;
}
要重新启动您的播放器,您需要再次做好准备。
public void restartAudio() {
Log.e(TAG, "restartAudio");
if (mp.isPlaying()) {
mp.seekTo(0);
}else{
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
当使用额外的布尔标志来控制线程的while循环时,不要忘记在其上使用volatile修饰符:
private volatile boolean running;
或者进行适当的同步。
除此之外,我还考虑使用Thread.isInterrupted()方法,而不是额外的"running"标志:http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#isInterrupted()
原因如下:https://stackoverflow.com/a/3196058/1350225