I am developing a feature with the possibility of switching the torch into ON/OFF states. Some days ago, we saw a new library from Google in io2019. I came up with an idea, why not use it.
After some time, I don't see any possibilities to use the only torch from the library.
Even in the official documentation, I wasn't able to find any good pieces of information for me, what's more, the sample app from their also don't have to handle my case.
Do you have something in mind what is easy to implement or perhaps you know how to do it with CameraX?
I am worried about using camera or camera2 because the amount of code to be paste is terrible.
Links:
[1] https://developer.android.com/training/camerax
[2] https://proandroiddev.com/android-camerax-preview-analyze-capture-1b3f403a9395
[3] https://github.com/android/camera/tree/master/CameraXBasic
[4] https://github.com/android/camera/tree/master/CameraXBasic
CameraX is an Android Jetpack library that was built with the intent to make camera development easier.
androidx.camera:camera-core:1.0.0-alpha10
You can check is torch available or not with this:
val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview, imageAnalyzer)
camera.cameraInfo.hasFlashUnit()
And you can enable torch with:
camera.cameraControl.enableTorch(true)
Turn on torch on Android, using Java.
Your typical camera preview code (such as from the google example) generally ends like this:
cameraProvider.bindToLifecycle((LifecycleOwner)this,
cameraSelector, imageAnalysis, preview);
to turn on/off the torch...
Camera cam = cameraProvider.bindToLifecycle((LifecycleOwner)this,
cameraSelector, imageAnalysis, preview);
if ( cam.getCameraInfo().hasFlashUnit() ) {
cam.getCameraControl().enableTorch(true); // or false
}
and that's it!
This is one way you can do it (Kotlin). If there is a better way please let me know. Following code assumes you have already established the availability of flash on the device.
Declare a flashMode var
private var flashMode: Int = ImageCapture.FLASH_MODE_OFF
In updateCameraUI set a listener
controls.findViewById<ImageButton>(R.id.flash_button).setOnClickListener {
when (flashMode) {
ImageCapture.FLASH_MODE_OFF ->
flashMode = ImageCapture.FLASH_MODE_ON
ImageCapture.FLASH_MODE_ON ->
flashMode = ImageCapture.FLASH_MODE_AUTO
ImageCapture.FLASH_MODE_AUTO ->
flashMode = ImageCapture.FLASH_MODE_OFF
}
// Re-bind use cases to include changes
bindCameraUseCases()
}
In bindCameraUseCases set the flash mode
imageCapture = ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
.setTargetAspectRatio(screenAspectRatio)
.setTargetResolution(screenSize)
.setTargetRotation(rotation)
.setFlashMode(flashMode)
.build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With