如果你想从不同的块访问的主题,你应该有它的声明为字段或最后的变量访问到所有的方法或类,而不是在内部匿名类,像这样
public void yourMethod() {
final Thread yourThread = null;
button.setOnClickListener(new View.OnClickListener() {
//OnClickListener oclbutton=new OnClickListener(){
@Override
public void onClick(View v) {
tvOut.setText("Server Started");
yourThread=new Thread (new MyServer());
thread.start();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//stop server
yourThread.stop();
}
});
}
现在,请注意使用Thread.stop()方法已经过时,所以不是作出这一呼吁,你可以做一些对你的MyServer类,如:
public class MyServer implements Runnable {
private boolean stopExecution = false;
public void setStopExecution(boolean stopExecution) {
this.stopExecution = stopExecution;
}
public void run() {
// as it is a server I assume you're doing a never ending loop
// now just make use of the control variable
while (!stopExecution) {
// do your stuff here...
}
}
}
,并在你的代码,你会做什么:
public void yourMethod(){ MyServer server = new MyServer();
button.setOnClickListener(new View.OnClickListener() {
//OnClickListener oclbutton=new OnClickListener(){
@Override
public void onClick(View v) {
tvOut.setText("Server Started");
Thread yourThread=new Thread (server);
thread.start();
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//stop server
server.setStopExecution(true);
}
});
}
最后一种方法是避免显示器出现问题的正确方法。另外看看Executor类来管理你的线程。
难道你不能只在声音监听器外面声明线程变量,并且在点击监听器上启动/停止相同的线程吗? – AndroidHustle 2013-04-25 17:51:14
可能重复的[你如何杀死Java中的线程?](http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java) – Raedwald 2016-09-04 08:26:22