How To Use And Configure CameraX In Android Applications

CameraX is another API or library that have made Android application developer’s life and work much easier for camera integration.

Introduction of CameraX has dramatically reduced both the effort and total number of lines of code required. Different feature implementation like zoom, auto focus, color balancing and others, which initially required great amount of effort and work, can now be easily integrated in any camera application.

Background

In this article I will discuss some simple steps and configurations that you will have to do for integration of CameraX in any Android application.

How to integrate CameraX API

First, you will have to add some permissions and features requests in your AndroidManifest.xml file.

<!-- Add these somewhere in your AndroidManifest.xml file -->
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />

uses-features lines will help Google’s Playstore to show your application only for devices with these features. And uses-permission will help your application to request access to different device hardware and OS features, in our case it is device camera.

Add CameraX dependencies

dependencies {
...
implementation "androidx.camera:camera-camera2:1.0.0-beta04"
implementation "androidx.camera:camera-lifecycle:1.0.0-beta04"
implementation "androidx.camera:camera-view:1.0.0-alpha11"
...
}

Although, these are still beta and alpha versions for now. But, still much better and effort less as compare to custom camera classes written on top of old Google camera and camera2 libraries. You can find latest versions and updates for CameraX here. Now sync your project to let Gradle update and download all dependencies.

Update activity layout

<androidx.camera.view.PreviewView
android:id="@+id/preview_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

If you are missing any dependency or gradle is not able to sync correctly. You might get an error on adding this view in your layout. In case of an error, please check error log for your application.

Update activity class

First, let’s get required permissions. you will have to call a static function in your activity’s onCreate function.

// this -> It a reference to your Activity Class
// allNeededPermissions -> A String[] array
// PERMISSION_REQUESTS -> A String constant, used as a request code to this function.
ActivityCompat.requestPermissions(
this, allNeededPermissions, PERMISSION_REQUESTS);

You will also have to Override and implement onRequestPermissionsResult function to verify and validate if all requested permissions have been granted by user. Please check for this online or in my GitHub repository for this project.

Now declare two class level variables to hold Camera Provider and Preview objects.

// You can name these differently
// But I find it easy to name as per Class name
@Nullable
private ProcessCameraProvider cameraProvider;
@Nullable
private Preview previewUseCase;

After doing this you will have to initialize and configure ViewModelProvider of androidx.lifecycle library. Android’s ViewModel providers are designed and built to hold and manage UI related data and help you to run, manage and resource intensive tasks asynchronously. And androidx.lifecycle.ViewModelProvider also help you to focus on your logic by taking care of all orientation and screen rotation changes automatically. I have used it in many different use cases that include reading data from Room persistence library, reading data from a CSV or JSON file, etc. And I am sure you can come up with many different scenarios yourself.

Here is the code snippet to initialize and bind ViewModelProvider for your camera provider and preview.

new ViewModelProvider(
this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()))
.get(CameraXViewModel.class)
.getProcessCameraProvider()
.observe(
this,
provider -> {
cameraProvider = provider;
});

Android CameraX API also provide utility functions to handle all life-cycle events. You can use these function to bind your camera object with your activity to let CameraX handle all view life-cycle and layout events including initialize, destroy, orientation change, etc. This is how you can do this.

previewUseCase = new Preview.Builder().build();
previewUseCase.setSurfaceProvider(binding.previewView.createSurfaceProvider());
// bindToLifecycle accept three parameters
// 1. LifecycleOwner which is our activity in this case
// 2. CameraSelector object which help you to
// initialize/bind on of the device's lenses.
// 3. Preview object to handle live feed or
// camera preview
cameraProvider.bindToLifecycle(BarcodeScannerActivity.this, cameraSelector, previewUseCase);

If you have successfully granted all required permissions to use and access device camera in your application, you should be able to see camera feed or preview in your application activity now. In case of any issue please check your error log or refer to sample code in GitHub repository.

This will bring us to end of our Android CameraX how-to guide. You can check complete code sample here on a GitHub repository.

Also don’t forget to share your valuable feedback and suggestions for this article. And if you have enjoyed reading this article and it was of any help, please share it with others to help them as well.

You can also see list of all of my guides and tutorials here. I hope to see you soon in another guide or tutorial some other time.

Allah Hafiz.

This guide was first appeared on the Zeeshan Elahi’s website at zeeshanelahi.com.

I am a son, husband, father, brother, friend, software engineering professional and fitness enthusiast. I love reading, writing, vlogging and sharing knowledge.