先生 请帮我添加一个线程,该线程从按钮单击开始,并以另一个按钮单击结束线程。在两者之间,我有一个声音播放,直到线程停止。
你可以试试这个简单的代码:
final volatile boolean toExit = false;
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(!toExit){
// Your code
Thread.sleep(100);
}
}
});
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
t.start();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
toExit = true;
}
});
单击按钮 2 后线程将停止并运行到 while(!toExit)
。
线程停止方法已弃用。最好的解决方案是在运行方法中使用布尔变量。
您的线程:
public class MyThread implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;
public void terminate() {
running = false;
}
@Override
public void run() {
while (running) {
try {
//Your code that needs to be run multiple times
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
}
}
在您的活动中:
MyThread t=new Thread();
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
t.start();
}
});
findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
t.terminate();
}
});
使用以下代码
public class SomeBackgroundProcess implements Runnable {
Thread backgroundThread;
public void start() {
if( backgroundThread == null ) {
backgroundThread = new Thread( this );
backgroundThread.start();
}
}
public void stop() {
if( backgroundThread != null ) {
backgroundThread.interrupt();
}
}
public void run() {
try {
Log.i("Thread starting.");
while( !backgroundThread.interrupted() ) {
doSomething();
}
Log.i("Thread stopping.");
} catch( InterruptedException ex ) {
// important you respond to the InterruptedException and stop processing
// when its thrown! Notice this is outside the while loop.
Log.i("Thread shutting down as it was requested to stop.");
} finally {
backgroundThread = null;
}
}
希望这对你有帮助