2016-08-20 46 views
3

使用SOS模式构建手电筒应用程序。有3个按钮(开,关和SOS)。应用程序工作在正常的开和关模式,但不是在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方法,因为我读了中断方法并不真正“中断”/杀死线程,我可以使用什么来代替Thread.Interrupt();,以便按下Off按钮可以停止SOS模式? 我试过stop()destroy(),但都崩溃的应用程序。

+1

的一个经常被用来为什么要用启动和杀死线程在所有的这样一个令人费解的系统?使用'Handler'代替有什么问题? –

+0

将使用'处理程序'来尝试SOS模式。但是总的来说,在这种情况下,中断不会真的完成任务,我需要做些什么? –

+0

如果可能的话,你可以请发送一个代码示例来实现这个使用'处理程序'?谢谢! –

回答

1

你应该使用的是在评论提出了Handler,但如果你想坚持使用这个系统,使用标志来告诉你线程停止:

boolean shouldStop = false; 

... 
while (!shouldStop){ 
    if(FlashOn){ 
    ...//do SOS stuff 
    } 
} 

... 
public void endSOS(){ 
    shouldStop = true; 
} 
+1

谢谢,这解决了我的问题加上一些其他代码 –

+0

只是次要问题。这段代码是否会只运行一次SOS模式,因为任何线程一旦停止都无法重新启动? –

+0

是的,虽然你可以修改它以允许重新启动。然而,我会做的只是实例化这个类的新实例,并启动它。合理? –

1

您要使用的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