Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use the camera after turning off the flashlight

I'm writing an application for school and it has features that requires the camera to take pictures, crop them, upload them to a server and afterwards the user has to be able to turn on the flashlight (as part of some tracking we're doing). All the above works perfectly - Untill the user turns off the flashlight and wants to take another picture. The camera stops working shows an error on screen that it can't connect to the camera.

I know there are commands like reconnect: http://developer.android.com/reference/android/hardware/Camera.html#reconnect() I've been fiddling around with it, and I can't for the life of me get it to work.

For using the camera I'm using an intent:

Intent intent    = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

And the flashlight code looks like this:

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());
        }
    }
}

 /*
 * Turning On flash
 */
private void turnOnFlash() {
    getCamera();
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);

        camera.setParameters(params);
        camera.startPreview();

        isFlashOn = true;
    }

}

/*
 * Turning Off flash
 */
private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        isFlashOn = false;
    }
}

Is there any way that I can use the same instance of the camera for both the flashlight and the camera (when it's an intent)? I found that if I release the camera et becomes null and it's unable to instanciate it again.

Thanks in advance

like image 412
Decoid Avatar asked Oct 21 '22 07:10

Decoid


1 Answers

@Decoid You just have to add an on pause method, which i am guessing you haven't as below:

    @Override
    protected void onPause()
    {
        super.onPause();
        if (!isFlashOn) {
            camera.release();
            camera = null;
    }
}
like image 193
We're All Mad Here Avatar answered Oct 30 '22 04:10

We're All Mad Here