I can’t figure out how to turn on the flashlight? The trigger works, but the flashlight itself does not turn on (or does not turn off).
val cameraProviderFuture = remember {
ProcessCameraProvider.getInstance(context)
}
var flashlightEnabled by remember {
mutableStateOf(false)
}
IconButton(
onClick = { flashlightEnabled = !flashlightEnabled }
) {
Icon(
painter = painterResource(
if (flashlightEnabled)
R.drawable.round_flash_on_24
else
R.drawable.round_flash_off_24
),
contentDescription = null
)
}
AndroidView(
factory = { context ->
val previewView = PreviewView(context)
val selector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
val preview = Preview.Builder().build()
preview.setSurfaceProvider(previewView.surfaceProvider)
val imageAnalysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
imageAnalysis.setAnalyzer(
ContextCompat.getMainExecutor(context),
BarcodeAnalyzerMLKit { format, value ->
onNavigateToDetail(format, value)
}
)
try {
cameraProviderFuture.get().bindToLifecycle(
lifecycleOwner,
selector,
preview,
imageAnalysis
).apply {
if (cameraInfo.hasFlashUnit()) {
cameraControl.enableTorch(flashlightEnabled)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
previewView
}
)
As I understand it, after the camera is initialized, it is not updated in any way. The only solution is to add a camera variable at a higher level and control this variable?
val camera = remember<Camera?> { null }
IconButton(
onClick = {
flashlightEnabled = !flashlightEnabled
if (camera?.cameraInfo!!.hasFlashUnit()) {
camera?.cameraControl!!.enableTorch(flashlightEnabled)
}
}
) {
Icon(
painter = painterResource(
if (flashlightEnabled)
R.drawable.round_flash_on_24
else
R.drawable.round_flash_off_24
),
contentDescription = null
)
}