Search code examples
javaandroidkotlinandroid-cameraandroid-camera2

Keep flashlight ON while camera is opened


I want to build an app that keeps the front LED flash/torch on while taking a picture. So I have the following code that opens the camera using an implicit intent:

val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, requestImageCapture)

And the code for turning on and off the torch/flash of the phone:

if(isLightOn) {
    val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
    val cameraId = manager.cameraIdList[0]
    manager.setTorchMode(cameraId, false)
    isLightOn = false
} else {
    val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
    val cameraId = manager.cameraIdList[0]
    manager.setTorchMode(cameraId, true)
    isLightOn = true
}

I've set the listeners of 2 buttons to perform these actions. Though they work well on their own, the torch/flash does not stay on when the camera is opened with the intent. Is there any way by which I can achieve this behavior?


Solution

  • The code for the torch works, but it only works for your app. After the startActivityForResult(intent, requestImageCapture) is executed you are no longer in your app. You are in whatever camera app you select. Your app loses access to the camera and the Camera app gets it.

    The flash now can be controlled for the Camera app. The camera app probably has controls for flash.

    If you want to enable the flash and take a photo you'll have to create your own camera app. You can do it from scratch following this guide or you can use a camera library like Fotoapparat or material-camera