英文:
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:
> android.hardware.camera2.CameraAccessException: CAMERA_IN_USE (4):
> setTorchMode:2325: Torch for camera "0" 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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论