Getting Started with CameraX

CameraX, launched at Google IO 19 , is a Jetpack support library, built to help us make camera app development easier. It provides a consistent and easy-to-use API surface that works across most Android devices, with backward-compatibility to Android 5.0 (API level 21).

Why CameraX is beneficial?

As per the documentation, CameraX has following primary benefits

  1. Consistence across the devices
  2. It provide new camera experience to the user

Create Android Project with minimum APL level 21.

defaultConfig {
applicationId "com.ankkumar.cameraxsampleapp"
minSdkVersion 21
targetSdkVersion 28

Add dependencies in app

implementation ""
implementation ""

Request Camera Permissions

In the manifest file

<uses-permission android:name="android.permission.CAMERA" />
import android.Manifest
import android.util.Size
import java.util.concurrent.TimeUnit
private const val REQUEST_CODE_PERMISSIONS = 881

private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)

Create and Implement view finder

  1. create view finder in activity_main.xml
private lateinit var viewFinder: TextureView
viewFinder = findViewById(

Implementing Image Capture

Write below code to capture image

// Every time the viewfinder is updated, recompute layout
preview.setOnPreviewOutputUpdateListener {

val parent = viewFinder.parent as ViewGroup
parent.addView(viewFinder, 0)

viewFinder.surfaceTexture = it.surfaceTexture
CameraX.bindToLifecycle(this, preview)
CameraX.bindToLifecycle(this, preview, imageCapture)

Analysing image capture

create a class called ImageAnalyzer as below

class ImageAnalyzer : ImageAnalysis.Analyzer {
override fun analyze(image: ImageProxy?, rotationDegrees: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.

// Setup image analysis pipeline that computes average pixel luminance
val analyzerConfig = ImageAnalysisConfig.Builder().apply {
// Use a worker thread for image analysis to prevent glitches
val analyzerThread = HandlerThread(
).apply { start() }
// In our analysis, we care more about the latest image than
// analyzing *every* image
Clap, share if you like it and follow for the updates.

Polyglot Fullstack Developer