Android CameraX Tutorial in Java (Example)

0
73

The official CameraX tutorial is in kotlin. All other tutorials about cameraX available on the internet are written in Kotlin. I was able to convert the cameraX implementation codes to java. Follow the below step to set it up.

1: Add Permission to Manifest

 <uses-permission android:name=”android.permission.CAMERA” />

 

2. Add CameraX Dependencies to Build.gradle file (App Level)

 
def camerax_version = "1.0.0-beta05"
implementation "androidx.camera:camera-core:$camerax_version"
implementation "androidx.camera:camera-camera2:${camerax_version}"
implementation "androidx.camera:camera-lifecycle:${camerax_version}"
implementation"androidx.camera:camera-view:1.0.0-alpha12"
implementation "androidx.camera:camera-extensions:1.0.0-alpha12"

 

3. Open activity_main.xml file and add the below code

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</RelativeLayout> 

 

4. Open MainActivity.java and add the below code

private void bindCameraUseCases() {
    DisplayMetrics metrics = new DisplayMetrics();
    binding.viewFinder.getDisplay().getRealMetrics(metrics);
    // Get screen metrics used to setup camera for full screen resolution


    Log.e(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}");

    int screenAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels);
    Log.e(TAG, "Preview aspect ratio: $screenAspectRatio");

    int rotation = binding.viewFinder.getDisplay().getRotation();

    // Bind the CameraProvider to the LifeCycleOwner
    CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_FRONT).build();

    final ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(getContext());

    cameraProviderFuture.addListener(new Runnable() {
        @Override
        public void run() {
            try {

                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                Preview preview = new Preview.Builder().setTargetAspectRatio(screenAspectRatio)
                        // Set initial target rotation
                        .setTargetRotation(rotation).build();


                cameraProvider.unbindAll();

                try {
                    // A variable number of use-cases can be passed here -
                    // camera provides access to CameraControl & CameraInfo
                    camera = cameraProvider.bindToLifecycle(getActivity(), cameraSelector, preview);

                    // Attach the viewfinder's surface provider to preview use case
                    preview.setSurfaceProvider(binding.viewFinder.createSurfaceProvider());
                } catch (Exception exc) {
                    Log.e(TAG, "Use case binding failed", exc);
                }

            } catch (ExecutionException | InterruptedException e) {
                // No errors need to be handled for this Future.
                // This should never be reached.
            }
        }
    }, ContextCompat.getMainExecutor(getActivity()));
}




private int aspectRatio(int width, int height) {
    double previewRatio = Math.max(width, height) / Math.min(width, height);
    if (Math.abs(previewRatio - RATIO_4_3_VALUE) <= Math.abs(previewRatio - RATIO_16_9_VALUE)) {
        return AspectRatio.RATIO_4_3;
    }
    return AspectRatio.RATIO_16_9;
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here