Course

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

I recently created a barcode and 2D code scanner application for one of my clients. Before the release to CameraX dependency, we were using a custom camera class to preview camera image or feed on our display screen. Therefore, we decided to replace that custom class with CameraX in addition to ML Kit to remove dependency on any custom or third party libraries.

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

You will have to follow some simple steps to integrate CameraX features in any android application.

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

Now open your app-level build.gradle file and add these three dependencies in it.

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

After Gradle finish updating your project, just open your required activity layout file and add this small tag in it. Now adjust width and height properties according to your own layout. We wanted to cover it full screen, that’s why we set these to match_parent for both.

<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

After adding required previewview in your Layout file, you will have to go to your activity’s .java file and make few more changes to get camera permissions, initialize and bind camera preview with this previewview in your layout file.

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.

Here is a preview of final application.

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.

Image placeholder

Hi! I'm Zeeshan Elahi

I have compiled and prepared this content with love for people like me and you. And as you know it always take some time and extra cups of coffee to read, compile and prepare a course or manual. If you have like reading this content and want to say thanks, please consider supporting from more stuff like this.

2 Comments

  • Jaime

    August 28, 2020 at 12:53 am

    Hello,

    I downloaded the demo to study it, but I got stuck when you used this import:

    import com.zeeshanelahi.barcodescannerandcameraxdemo.databinding.ActivityBarcodeScannerBinding;

    Where is com.zeeshanelahi.barcodescannerandcameraxdemo.databinding defined?

    I have opened the project in Android Studio and try to find among all project files for “ActivityBarcodeScannerBinding” class or “databinding” package but they are nowhere. And even, Android Studio Intellisense does not list among the possible options. The curious thing, is that the code can be compiled successfully and run.

    Also, you use this code: “binding.previewView”. I know what you want to do with that instruction, but if I start a new project and copy all files, obviously previewView was not found because “binding” is undefined. And, “binding” is undefined because this declaration “private ActivityBarcodeScannerBinding binding;” cannot be made since “ActivityBarcodeScannerBinding” is also undefined.

    Can you explain that “magical” code, please?

    Thanks

    Reply

    • Zeeshan Elahi Author

      August 28, 2020 at 3:02 pm

      Hello,

      Thank you for reading this how-to guide and reaching me out to clear confusion.

      BTW, it’s very simple for someone, who has already read about and used Android View Binding feature.
      https://developer.android.com/topic/libraries/view-binding

      Please have a look at above link and do let me know if you still see any confusion.

      Thank you.

      Reply

Leave a comment

Your email address will not be published. Required fields are marked *

*

*