因此,我正在编写一个可以远程控制另一台设备的灯光的应用程序。现在,我想有一个计时器,只要打开灯,它就会运行,而当我再次关闭它们时,它会停止运行。
现在,第一次可以很好地工作:这意味着当我第一次打开灯时,计时器开始运转,当我关闭灯时,它会停止。但是,当我再次尝试执行此操作时,应用程序崩溃了。任何人都知道问题可能在哪里吗?
这是我的代码:
//thread for the timer it's in the onCreate method
t = new Thread()
{
@Override
public void run(){
while(!(t.isInterrupted())){
try {
Thread.sleep(1000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
@Override
public void run() {
runningtime++;
runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
}
});
} catch (InterruptedException e) {
t.interrupt();
}
}
}
};
}
//the buttons and the button listeners
final Button buttonOn = findViewById(R.id.lightOn);
buttonOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
turnLightOn();
//timer-thread gets started
t.start();
test.setText("Status: ON");
}
});
final Button buttonOff = findViewById(R.id.lightOff);
buttonOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Code here executes on main thread after user presses button
turnLightOff();
//timer thread gets interrupted
t.interrupt();
test.setText("Status: OFF");
}
});
您根本无法在Java中重新启动线程
来自https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html上的Java API文档
一次启动一个线程永远是不合法的。特别是,线程一旦完成执行就可能不会重新启动。
基本上,您将要使用上面显示的相同逻辑来重新创建此线程。将其放入返回Thread的新方法中,然后从onClick调用该新方法以填充t可能很有意义。但是请当心有人敲击单击按钮,这可能会导致奇怪的行为。
//thread for the timer it's in the onCreate method
public Thread makeNewThread() {
return new Thread()
{
@Override
public void run(){
while(!(t.isInterrupted())){
try {
Thread.sleep(1000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
@Override
public void run() {
runningtime++;
runningTime.setText("Running since: " + String.valueOf(runningtime) + "seconds" );
}
});
} catch (InterruptedException e) {
t.interrupt();
}
}
}
};
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句