Question

Following is the code which I used for opening Torch and closing it. But when I close it, it crashes. LogCat says " Runtime Exception : Fail to connect to camera service "!

+ hasFlash is not getting any value and is throwing Nullpointer exception. (I'm using it to check if the flash is present or not.)

What am I doing Wrong?

boolean hasFlash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(hasFlash==true)

{

            if(s.equalsIgnoreCase("FlashLight On") || s.equalsIgnoreCase("Flash Light On"))
            {
                Camera cam = Camera.open();     
                Parameters p = cam.getParameters();
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                cam.setParameters(p);
                return "Turning on";

            }
            if(s.equalsIgnoreCase("FlashLight Off") || s.equalsIgnoreCase("Flash Light Off"))
            {

                Camera cam = Camera.open();
                Parameters p = cam.getParameters();
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                cam.setParameters(p);
                cam.stopPreview();
                cam.release();

                return "Turning off";
            }
            }
            else
            {
                return "Flash Not Available";
            }
Was it helpful?

Solution

Change

Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
cam.stopPreview();
cam.release();

return "Turning off";

to

cam.stopPreview();
cam.release();

return "Turning off";

I ran into a lot of these issues building an open source flashlight for Android which may help you with further questions.

Flashlight by Joe github

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top