I’m creating an app for make the flash camera blink, but I have a problem with switching off the method. These are my variables:
Camera camera = null;
Parameters parameters;
int delay = 600;
int period = 600;
int delay1 = 300;
int period1 = 600;
Timer timer, timer2;
This method I’m using to make the flash camera blink:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
cameraOn();
}
},delay1,period1);
timer2 = new Timer();
timer2.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
cameraOff();
}
},delay,period);
And now is when the problem comes, there’s a button to switch off all this, but sometimes it works and sometimes it doesn’t. Sometimes it switches off perfect, sometimes it goes back to the previous activity like I want, but the flash camera stays switched on. What is wrong? Here are the methods to switch on-off the camera flash:
private void cameraOff() {
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
private void cameraOn() {
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
And here is the button:
@Override
public void onClick(View arg0) {
timer.cancel();
timer2.cancel();
if(camera != null){
cameraOff();
}else{
finish();
}
}
Your application (as provided) is never going to work, due to a design flaw:
In the
cameraOff()method you setcameratonull. This method is triggered at a fixed interval, so next time the method is called again you have aNullPointerExceptionascamerawas set tonull…I do not know why you feel the urge to set it to
null, but you need to do so elsewhere, or add checks whethercameraisnullor not.Furthermore (to probable cause of your problem), the
TimerTasksare executed on a different thread. When you cancel your timers, the value ofcamerais unknown and it might be possible thatcameraOff()is called twice. Once from theTimerTaskthread (as it was about to execute) and once from your main thread (becausecamerawas not yet set sonull).Again, I wonder why you need to set
cameratonull, as this seems to cause most of your problems.