使用SOS模式构建手电筒应用程序。有3个按钮(开、关和求救)。应用程序在正常打开和关闭模式下工作,但不能在SOS模式下工作。(SOS模式不会关闭)
//this method gets called when Off button is pressed
private void turnOffFlash() {
if (FlashOn) {
if (myCamera == null || myParameters == null) {
return;
}
myParameters = myCamera.getParameters();
myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(myParameters);
myCamera.stopPreview();
try {
if (SOSon)
Flashthread.interrupt();
SOSon = false;
} catch (Exception ex) {
throw ex;
}
FlashOn = false;
number_of_press=0;
}
}这里使用的是Flashthread
void onSOSPress() {
if (number_of_press == 1) {
try {
SOSon = true;
if (!Flashthread.isInterrupted()) {
if (SOSon) {
Flashthread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < System.currentTimeMillis(); i++) {
if (FlashOn) {
myParameters.setFlashMode(Parameters.FLASH_MODE_OFF);
myCamera.setParameters(myParameters);
FlashOn = false;
} else {
TurnOnFlash();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Flashthread.start();
}
} else
Flashthread.resume();
} catch (Exception ex) {
throw ex;
}
}
}在turnOffFlash方法中,由于我了解到Interrupt方法并不真正“中断”线程,那么我可以使用什么来代替Thread.Interrupt();,这样按下Off按钮就可以停止SOS模式?我试过stop()和destroy(),但两者都使应用程序崩溃。
发布于 2016-08-20 23:21:19
您应该使用注释中建议的Handler,但如果您想继续使用此系统,请使用一个标志来告诉您的线程停止:
boolean shouldStop = false;
...
while (!shouldStop){
if(FlashOn){
...//do SOS stuff
}
}
...
public void endSOS(){
shouldStop = true;
}发布于 2016-08-20 23:32:17
如果您想强制抛出异常,则需要使用Thread#interrupt()。
boolean isClose = false;
while(!isClose){
try {
// Your code here
} catch (InterruptedException e) {
if(isClose){
break;
}
}
}
public void killThread(){
isClose = true;
interrupt();
}来实现代码。
MyCustomThread t = new MyCustomThread(....);
// Assuming that the thread is already running
t.killThread();这种方法通常用在Volley等流行的库中。
https://stackoverflow.com/questions/39055659
复制相似问题