-1

I need to blink the LED every 2 seconds in my app. I have figured the code to switch the LED on and off using the following pieces of code:

Camera camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();

p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.startPreview();

Now as soon as the user presses the blink button, I need to execute the first piece of code for 2 seconds and then second piece of code for next 2 seconds. Also I need to stop the execution of this alternate LED on-off sequence as soon as the user presses the "Stop" button.

Any idea, how can I achieve this without making my app result in ANR?

  • Maybe use `AsyncTasks` and by using the `get` method to force the second piece of code to "wait" for the first one? Considering also the wait of 2 seconds? – g00dy Nov 04 '13 at 19:31
  • Read and `Handler` and `postDelayed` Also see this http://stackoverflow.com/questions/18247210/pausing-with-handler-and-postdelayed-in-android – Simon Nov 04 '13 at 20:25

1 Answers1

0

you could use a Thread to do it:

Camera camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();

new Thread(){
    public void run(){
        try{
            Thread.sleep(2000);
        }catch(Exception ex){}

        runOnUiThread(new Runnable(){
            public void run(){
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                camera.setParameters(p);
                camera.startPreview();
            }
        });
    }
}.start();
panini
  • 2,026
  • 19
  • 21
  • You should have to pass a test and have a license to use `Thread.sleep()`. There are some special cases when Thread.sleep makes sense. This is not one of them. Absolutely no need for it. – Simon Nov 04 '13 at 20:22