Search code examples
androidandroid-camerax

How to instantiate CameraControl on Android CameraX (1.0.0-alpha07)


When using camerax_version = "1.0.0-alpha06" I could instantiale the camera controller using :

CameraControl cameraControl = CameraX.getCameraControl(CameraX.LensFacing.BACK);

But with camerax_version = "1.0.0-alpha07", the function CameraX.getCameraControl is not any more recognized.

How can I instantiate CameraControl ?


Solution

  • Version 1.0.0-alpha07 changed the way CameraX is initialized quite a lot. In order to obtain a CameraControl object, you have to get a Camera object first. A Camera is returned from a ProcessCameraProvider.bindToLifecycle() method. Basically what you need to do is:

    (If you have already configured your project with the new API, just skip to the last point)

    1. Implement CameraXConfig.Provider in your Application class and provide the default Camera2Config value:
    class MyApp : Application(), CameraXConfig.Provider {
        override fun getCameraXConfig(): CameraXConfig = Camera2Config.defaultConfig(this)
    }
    
    1. Obtain an instance of ProcessCameraProvider:
    val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
    cameraProviderFuture.addListener(Runnable {
        cameraProvider = cameraProviderFuture.get()
        ...
    }, ContextCompat.getMainExecutor(context))
    

    3. Bind CameraX UseCases and CameraSelector to a lifecycle using the ProcessCameraProvider instance and get Camera and CameraControl objects:

    // CameraSelector is also a new thing
    val cameraSelector = CameraSelector.Builder().apply {
        requireLensFacing(lensFacing)
    }.build()
    
    val preview = ...
    val imageCapture = ...
    val imageAnalysis = ...
    
    val camera = cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview, imageCapture, imageAnalysis)
    val cameraControl = camera.cameraControl
    

    Check Camera-Core Version 1.0.0-alpha07 API changes for any additional references.