javaandroidkotlinandroid-cameraandroid-camerax

camera X Cancelled by another startFocusAndMetering


I'm implementing a custom camera using cameraX library. I'm working on focusing and I did below things

viewFinder.setOnTouchListener { v, event ->
            return@setOnTouchListener when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    true
                }
                MotionEvent.ACTION_UP -> {
                   // The below code is for focusing 

                    val factory = SurfaceOrientedMeteringPointFactory(
                        viewFinder.width.toFloat(),
                        viewFinder.height.toFloat()
                    )
                    val point = factory.createPoint(event.x, event.y)
                    try {
                        val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
                            .apply {
                                disableAutoCancel() //focus only when the user tap the preview
                            }.build()

                        val future = cameraControl?.startFocusAndMetering(action)
                        future?.addListener(Runnable {
--->line 66                 val result = future?.get()
                            println("log result ---> $result")
                        }, cameraExecutor)

                    } catch (e: CameraInfoUnavailableException) {
                        println("log error ---> $e")
                    }
                    true
                }
                else -> false // Unhandled event.
            }
        }

Now, It is some what focusing the point I touched and it's not too accurate but it's ok. And while focusing after 5 to 6 times the app was crashing and closing.

FATAL EXCEPTION: pool-2-thread-1
...
...
java.lang.Error: java.util.concurrent.ExecutionException: androidx.camera.core.CameraControl$OperationCanceledException: Cancelled by another startFocusAndMetering()
...
...
...MainActivity$onCreate$2$1.run(MainActivity.kt:66)

I'm not getting why it's crashing and it is not frequently crashing. Sometimes it will crash and some times not.

Edit 1 :-

I got to know that when I tap focus multiple times this is happening. So, before start of focusing I need to clear the previous focus if in progress. But, how to clear previous focus I'm not getting.

Edit 2 :-

I tried this cameraControl?.cancelFocusAndMetering(), I just put it at first line of try block. but still problem exists.


Solution

  • I just removed This block

    future?.addListener(Runnable {
              val result = future?.get()
              println("log result ---> $result")
           }, cameraExecutor)
    
    

    and it's working fine. But I don't know is it right or wrong.

    If anyone knows? please answer. currently I'm marking this as answer as it worked.