Alternatives to thread interruption?

Create a Flashlight application with SOS mode. It has 3 buttons (On, Off and SOS). The application works in the usual On and Off mode, but not in SOS mode (SOS mode does not turn off)

//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; } } 

and Flashthread used here

 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; } } } 

In the turnOffFlash method, since I read that the interrupt method does not actually β€œinterrupt” / kill the thread, which I can use instead of Thread.Interrupt(); so that pressing the Off button stops SOS > mode? I tried stop() and destroy() , but both of them crashed the application.

+3
source share
2 answers

What you should use is the Handler , as suggested in the comments, but if you want to stick to this system, use a flag to stop your thread from stopping:

 boolean shouldStop = false; ... while (!shouldStop){ if(FlashOn){ ...//do SOS stuff } } ... public void endSOS(){ shouldStop = true; } 
+1
source

You want to use Thread#interrupt() if you want an Exception thrown.

 boolean isClose = false; while(!isClose){ try { // Your code here } catch (InterruptedException e) { if(isClose){ break; } } } public void killThread(){ isClose = true; interrupt(); } 

To implement the code.

  MyCustomThread t = new MyCustomThread(....); // Assuming that the thread is already running t.killThread(); 

This approach is often used in one of the popular libraries such as Volley , etc.

+1
source

Source: https://habr.com/ru/post/1013232/


All Articles