Search code examples
androidcameraled

Android Camera LED light goes to Off after 2 seconds?


I am using the camera flash light in my application, I was done coding for that, it's working on/off the light. but after 2 seconds it goes to off. If I press the on button again it was giving force close. This is the code i am using for this, please help me.

I want this like if user presses the on button light On, upto user press Off button.

private void processOffClick()  {

    //togglebutton.setButtonDrawable(R.drawable.offbutton);
    System.out.println("in off state");
    if( cam != null ){
        cam.stopPreview();
        cam.release();
    }
}
private void processOnClick()  {

    //togglebutton.setButtonDrawable(R.drawable.onbutton);
    System.out.println("in on state");       
    cam = Camera.open();     
    Parameters params = cam.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_ON);
    cam.setParameters(params);

    cam.startPreview();
    cam.autoFocus(new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
        }
    });      
}

Solution

  • put the lines:

    Parameters params = cam.getParameters();
    params.setFlashMode(Parameters.FLASH_MODE_ON);
    cam.setParameters(params);
    

    in processOffClick instead of putting it in processOnClick like that:

    boolean clicked = false;
    private void processOffClick()  {
    
      //togglebutton.setButtonDrawable(R.drawable.offbutton);
      clicked = false;
      System.out.println("in off state");
      if( cam != null ){
          cam.stopPreview();
          cam.release();
      }
    }
    private void processOnClick()  {
      clicked = true;
      //togglebutton.setButtonDrawable(R.drawable.onbutton);
      System.out.println("in on state");       
      cam = Camera.open();     
      Parameters params = cam.getParameters();
      params.setFlashMode(Parameters.FLASH_MODE_ON);
    
      while(clicked)  { 
         cam.setParameters(params);
    
         cam.startPreview();
            cam.autoFocus(new AutoFocusCallback() {
               public void onAutoFocus(boolean success, Camera camera) {
            }
         });
      } 
    }
    

    It might work, i didn't check the code

    I added a while loop so it would hold the flash and the focus until its unclicked.