0

I am trying to turn on and off camera flashlight using the following code, but every time I call those functions it slows down my whole app. Which is kinda annoying. Is there any way I can do it in separate thread or perhaps in a different way? Thanks in advance.

private void turnOnFlash() {
        if (!isFlashOn && hasFlash) {
            if (camera == null || params == null) {
                return;
            }

            isFlashOn = true;

            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(params);
            camera.startPreview();
        }
    }

    private void turnOffFlash() {
        if (isFlashOn && hasFlash) {
            if (camera == null || params == null) {
                return;
            }

            isFlashOn = false;

            params = camera.getParameters();
            params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(params);
            camera.stopPreview();
        }
    }

and im calling it from another function like

if (intensity[3] < 0.5f) {
    turnOnFlash();
} else {
    turnOffFlash();
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
jquery404
  • 653
  • 1
  • 12
  • 26
  • Is there a reason you are calling startPreview and stopPreview in those methods? I don't think that is needed to change the flash mode parameter. – AChez9 Nov 07 '17 at 18:51
  • I turned it on for another purpose. I tried without calling those two methods. but the same result though. – jquery404 Nov 07 '17 at 19:13

1 Answers1

0

setParameters and getParameters may take noticeable time.

But what really slows the app is that UI thread becomes the handler for all camera callbacks. Here in an old answer I showed how easy it is to handle the camera in a background HandlerThread.

Note that the camera API you use here was deprecated some years ago, while the current camera2 API handles this threading issue correctly, and don't need these tricks anymore.

You can post turnOffFlash() and turnOnFlash() to the same HandlerThread.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307