Saify
Saify

Reputation: 481

Flashlight blink on button click in android

I am developing a flashlight application in which I am trying to add blink functionality on button click. The code that i found for this is:

String myString = "0101010101";
long blinkDelay 50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
   if (myString.charAt(i) == '0') {
      params.setFlashMode(Parameters.FLASH_MODE_ON);
   } else {
      params.setFlashMode(Parameters.FLASH_MODE_OFF);
   }
   try {
      Thread.sleep(blinkDelay);
   } catch (InterruptedException e) {
      e.printStackTrace();
   }
}

But this code turns off flashlight after few blinks. How can i start flashlight blink on button click and stop it unless I click it again? Any Help?

Upvotes: 1

Views: 1091

Answers (3)

Mazhar Iqbal
Mazhar Iqbal

Reputation: 999

You will have to use a thread to prevent UI freeze. Thread will contain a while loop which will allow it to blink continuously.

 while (shouldGlow ) {
          flashLight();
          try {
              Thread.sleep(1000);
          } catch (InterruptedException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }

  }

//use boolean varibale to stop the loop

Upvotes: 0

Coding Freak
Coding Freak

Reputation: 103

  • You will have to use a separate thread to prevent UI freeze.
  • Thread will contain a while loop which will allow it to blink continuously.
  • To break the loop on button click use a boolean variable in while condition.

Hope it helps.

Upvotes: 2

Umar Hussain
Umar Hussain

Reputation: 3517

It's controlled by your string length so the for loop will break after the count of i becomes greater than last index. Use a while loop if you want to blink the flash continuously. You can use one boolean variable to switch between on off. And a boolean in while condition to break the loop when button is clicked

Upvotes: 2

Related Questions