打开摄像头时打开手电筒。

huangapple go评论214阅读模式
英文:

Turn on torch when camera is open

问题

需要在打开相机时打开手电筒。

class FlashLight(private val context: Context) {
    private val cameraManager by lazy { context.getSystemService(Context.CAMERA_SERVICE) as CameraManager }
    private val backCameraId by lazy { cameraManager.cameraIdList[0] }
    
    fun turnOnFlashLight() = changeFlashStatus(shouldBeTurnedOn = true)

    fun turnOffFlashLight() = changeFlashStatus(shouldBeTurnedOn = false)

    private fun changeFlashStatus(shouldBeTurnedOn: Boolean) {
        try {
            cameraManager.setTorchMode(backCameraId, shouldBeTurnedOn)
        } catch (e: Exception){
            L.e(e)
        }
    }
}

我的代码在相机关闭时工作正常,但当我在我的应用程序内运行相机并尝试打开手电筒时,出现错误:

android.hardware.camera2.CameraAccessException: CAMERA_IN_USE (4):
setTorchMode:2325: 相机“0”的手电筒不可用


<details>
<summary>英文:</summary>

I need to turn on torch when camera is open.


    class FlashLight(private val context: Context) {
        private val cameraManager by lazy { context.getSystemService(Context.CAMERA_SERVICE) as CameraManager }
        private val backCameraId by lazy { cameraManager.cameraIdList[0] }
        
        fun turnOnFlashLight() = changeFlashStatus(shouldBeTurnedOn = true)
    
        fun turnOffFlashLight() = changeFlashStatus(shouldBeTurnedOn = false)
    
        private fun changeFlashStatus(shouldBeTurnedOn: Boolean) {
            try {
                cameraManager.setTorchMode(backCameraId, shouldBeTurnedOn)
            } catch (e: Exception){
                L.e(e)
            }
        }
    }

My code is working when camera is closed but when I run camera inside my app and want to turn torch on I get error:

&gt; android.hardware.camera2.CameraAccessException: CAMERA_IN_USE (4):
&gt; setTorchMode:2325: Torch for camera &quot;0&quot; is not available



</details>


# 答案1
**得分**: 2

你可以在与相机相同的会话中启用 torch。您可以使用此键启用闪光模式 https://developer.android.com/reference/android/hardware/camera2/CaptureRequest#FLASH_MODE 并将值设置为 https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#FLASH_MODE_TORCH。

<details>
<summary>英文:</summary>

If you want to enable torch in the same session with your camera.
You can enable the flash mode using this key 

https://developer.android.com/reference/android/hardware/camera2/CaptureRequest#FLASH_MODE and set the value as https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#FLASH_MODE_TORCH



</details>



huangapple
  • 本文由 发表于 2023年2月14日 21:06:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定