I am trying to make an Android app that blinks the camera LED when the user presses the blink button. I'm able to blink the LED. I have added another button to stop the blinking of the LED when the user wants, but I am not able to stop the blinking.
What should I add to stop the blinking of the LED?
Here's my code:
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button blinkled,stop;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
String myString;
long blinkDelay =200;
int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActionBar().hide();
blinkled= (Button) findViewById(R.id.blink);
stop= (Button) findViewById(R.id.stop);
// get the camera
getCamera();
blinkled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Runnable r = new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
long end = start + 5 * 1000;
while (System.currentTimeMillis() < end) {
for (i = 0; i < 2; i++) {
if (i % 2 == 0) {
turnOnFlash1();
} else if (i % 2 == 1) {
turnOffFlash1();
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Thread th = new Thread(r);
th.start();
}
});
}
/*
* Get the camera
*/
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash1() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash1() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
if (camera != null) {
camera.release();
camera = null;
}
}