我在调用播放音频文件的方法时启动一个线程。
代码第一次运行正常,但是当我再次调用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;
}
如果有人知道这个问题的解决方案,我会非常感激。
答案 0 :(得分:1)
不应该手动停止线程。您应该在true
循环中使用布尔值而不是while
,并在要停止时将布尔值设置为false
通过设置器:
private boolean running;
@Override
public void run(){
running = true;
while(running) {...}
}
public void setRunning(boolean b){
this.running = b;
}
答案 1 :(得分:0)
要重新启动播放器,您需要重新准备。
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();
}
}
}
答案 2 :(得分:0)
当使用额外的布尔标志来控制线程的while循环时,不要忘记在其上使用volatile修饰符:
private volatile boolean running;
或进行适当的同步。
除此之外,我考虑使用Thread.isInterrupted()方法而不是额外的'running'标志: http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#isInterrupted()