手电筒Camera2 API

时间:2015-10-24 23:57:44

标签: android flashlight camera2

我可以在Android Camera2 API中同时使用相机预览和手电筒吗?

当我尝试使用CameraManager.setTorchMode(String cameraId, boolean enabled)时,相机未打开时工作正常。但是当Camera打开并且我尝试setTorchMode时,我收到了这个例外:

  

CameraService:setTorchMode:相机0的手电筒模式不可用,因为相机正在使用

4 个答案:

答案 0 :(得分:2)

不,他们互相排斥。

相机设备需要在相机打开时专门控制闪光灯,以确保它可以根据照片等需要进行闪光。

如果要在相机打开时打开手电筒,请使用相机API的闪光模式设置。对于新的camera2 API,将自动曝光模式设置为ON(CONTROL_AE_MODE_ON),将闪光模式设置为TORCH(FLASH_MODE_TORCH)。对于旧的相机API,那是Parameters.setFlashMode

答案 1 :(得分:2)

我找到了解决方案:

CaptureRequest.Builder builder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
builder.set(CaptureRequest.FLASH_MODE, enable ? CameraMetadata.FLASH_MODE_TORCH : CameraMetadata.FLASH_MODE_OFF);
CaptureRequest request = builder.build();
cameraCaptureSession.capture(request, null, null);

答案 2 :(得分:2)

该错误表明所涉及的相机已在使用中。

您需要相应地设置FLASH_MODECONTROL_AE_MODE

mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
// Then Send request to current camera session
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, null);

答案 3 :(得分:0)

同时设置FLASH_MODE和AE_MODE很重要。下面是工作代码:

public void toggleFlashMode(boolean enable){
try {
            if (mCameraType.equals(CameraType.BACK)) {
                if (enable) {
                    mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
                    mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                } else {
                    mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                    mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_OFF);
                }
                mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, null);
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
}