Changing Flash setting of Android Camera 2 at runtime

那年仲夏 提交于 2019-12-01 19:20:02

I don't know why your preview turn black, but you don't need to close capture session manually. From .close() method's docs:

Using createCaptureSession(List , CameraCaptureSession.StateCallback, Handler) directly without closing is the recommended approach for quickly switching to a new session, since unchanged target outputs can be reused more efficiently.

So you can reuse existing CaptureRequest.Builder, set your changed value, build new PreviewRequest and just start new session with this new request, like this:

try {
    // Change some capture settings
    mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
    // Build new request (we can't just edit existing one, as it is immutable)
    mPreviewRequest = mPreviewRequestBuilder.build();
    // Set new repeating request with our changed one
    mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
} catch (CameraAccessException e) {
    e.printStackTrace();
}

It will be much faster (almost without any visible freeze of preview).

As mentioned by @cyborg86pl when switching flash modes you should not switch CONTROL_AE_MODE . Instead you can switch between FLASH_MODE´s. Here is a working example for my case:

  when (currentFlashState) {
        FlashState.AUTO -> {
          previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
        }
        FlashState.ON -> {
          previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
          previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH)
        }
        FlashState.OFF -> {
          previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
          previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF)
        }
      }
 previewRequest = previewRequestBuilder.build()
 captureSession.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler)

What you want is disabling flash, not auto-exposure (AE), thus you want to use CONTROL_AE_MODE_ON rather than CONTROL_AE_MODE_OFF.

As mentioned in the documentation:

CONTROL_AE_MODE_ON

The camera device's autoexposure routine is active, with no flash control.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!