Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to preview the camera on Android CameraX

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

How to do Android CameraX camera preview, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Preface

The goal is very simple, use CameraX to open the camera preview, real-time display on the interface. See if CameraX works as well as Google says. First press the simplest to display the preview.

Introduce dependency

Some configurations of module gradle, using Android SDK version 31, with databinding enabled

Apply plugin: 'com.android.application'apply plugin:' kotlin-android'apply plugin: 'kotlin-android-extensions'apply plugin:' kotlin-kapt'android {compileSdkVersion 31 buildToolsVersion "31.0.0" defaultConfig {minSdkVersion 21 targetSdkVersion 31} dataBinding {enabled = true}}

Introduce CameraX dependency (the CameraX core library is implemented in camera2), currently mainly using the 1.1.0-alpha11 version

Dependencies {implementation "androidx.camera:camera-core:1.1.0-alpha11" implementation "androidx.camera:camera-camera2:1.1.0-alpha11" implementation "androidx.camera:camera-lifecycle:1.1.0-alpha11" implementation "androidx.camera:camera-view:1.0.0-alpha31" implementation "androidx.camera:camera-extensions:1.0.0-alpha31"}

Using version 1.0.2 of the CameraX core library will report an error and the getOrCreateInstance method cannot be found.

??? Bug "NoSuchMethodError getOrCreateInstance"

````logCrashHandler: In thread: Thread [main,5,main] UncaughtException detected: java.lang.NoSuchMethodError: No static method getOrCreateInstance (Landroid/content/Context;) Lcom/google/common/util/concurrent/ListenableFuture; in class Landroidx/camera/core/CameraX Or its super classes (declaration of 'androidx.camera.core.CameraX' appears in / data/app/com.rustfisher.tutorial2020-1/base.apk) at androidx.camera.lifecycle.ProcessCameraProvider.getInstance (ProcessCameraProvider.java:149) at com.rustfisher.tutorial2020.camera.SimplePreviewXAct.onCreate (SimplePreviewXAct.java:36) at android.app.Activity.performCreate (Activity.java:6161) at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1112) at android.app.ActivityThread.performLaunchActivity ( ActivityThread.java:2507) at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2640) at android.app.ActivityThread.access$800 (ActivityThread.java:182) at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1493) at android.os.Handler.dispatchMessage (Handler.java:111) at android.os.Looper.loop (Looper.java:194) at android.app.ActivityThread.main (ActivityThread.java:5682) at java.lang.reflect.Method.invoke (Native Method) at java.lang.reflect.Method.invoke (Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:963) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:758) ```permission

Need to apply for android.permission.CAMERA permission dynamically

This article skips the place where you apply for permission dynamically.

Interface

CameraX intimately prepares androidx.camera.view.PreviewView for developers.

Put it in a FrameLayout with the following act_simple_preivew_x.layout

Turn on preview

Turn on camera preview in activity

/ / SimplePreviewXAct.javaimport android.os.Bundle;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.camera.core.Camera;import androidx.camera.core.CameraSelector;import androidx.camera.core.Preview;import androidx.camera.lifecycle.ProcessCameraProvider;import androidx.core.content.ContextCompat;import androidx.databinding.DataBindingUtil;import androidx.lifecycle.LifecycleOwner;import com.google.common.util.concurrent.ListenableFuture;// import com.rustfisher.tutorial2020.R;// import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding Import java.util.concurrent.ExecutionException;public class SimplePreviewXAct extends AppCompatActivity {private ActSimplePreivewXBinding mBinding; private ListenableFuture cameraProviderFuture; @ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); mBinding = DataBindingUtil.setContentView (this, R.layout.act_simple_preivew_x); cameraProviderFuture = ProcessCameraProvider.getInstance (this); cameraProviderFuture.addListener (()-> {try {ProcessCameraProvider cameraProvider = cameraProviderFuture.get () BindPreview (cameraProvider);} catch (ExecutionException | InterruptedException e) {/ / No processing here}}, ContextCompat.getMainExecutor (this);} void bindPreview (@ NonNull ProcessCameraProvider cameraProvider) {Preview preview = new Preview.Builder () .build () CameraSelector cameraSelector = new CameraSelector.Builder () .roomLensFacing (CameraSelector.LENS_FACING_BACK) .build (); preview.setSurfaceProvider (mBinding.previewView.getSurfaceProvider ()); Camera camera = cameraProvider.bindToLifecycle (this, cameraSelector, preview);}}

Note that we are using androidx.appcompat.app.AppCompatActivity here

To get ProcessCameraProvider, use the ProcessCameraProvider.getInstance method to get a cameraProviderFuture.

Remove the ProcessCameraProvider (cameraProvider) after the cameraProviderFuture is complete.

To turn on the preview, build a Preview through Preview.Builder. Use CameraSelector to select the rear camera.

The SurfaceProvider for Preview is provided by androidx.camera.view.PreviewView in layout.

After the cameraProvider.bindToLifecycle is bound, start the camera preview

Run the test

Run it to the phone, open the Activity and you can see the camera preview. The aspect ratio of the image is normal and there is no stretching.

Glory EMUI 3.1 Lite,Android 5.1 is running normally

Redmi 9A MIUI 12.5.1 stable version, Android 10 running normally

One plus 5dyadic H2OS 10.0.3 Android 10 is running normally.

Add switch

Add 2 buttons in layout to control the camera switch.

Replace the root layout with LinearLayout

Modify the bindPreview method to first check whether the incoming ProcessCameraProvider is empty

Private void bindPreview (ProcessCameraProvider cameraProvider) {if (cameraProvider = = null) {Toast.makeText (getApplicationContext (), "no camera", Toast.LENGTH_SHORT) .show (); return;} Preview preview = new Preview.Builder () .build (); CameraSelector cameraSelector = new CameraSelector.Builder () .roomLensfacing (CameraSelector.LENS_FACING_BACK) .build (); preview.setSurfaceProvider (mBinding.previewView.getSurfaceProvider ()) Camera camera = cameraProvider.bindToLifecycle (this, cameraSelector, preview);}

Modified part of the activity code

Import android.os.Bundle;import android.widget.Toast;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.camera.core.Camera;import androidx.camera.core.CameraSelector;import androidx.camera.core.Preview;import androidx.camera.lifecycle.ProcessCameraProvider;import androidx.core.content.ContextCompat;import androidx.databinding.DataBindingUtil;import com.google.common.util.concurrent.ListenableFuture;// import com.rustfisher.tutorial2020.R;// import com.rustfisher.tutorial2020.databinding.ActSimplePreivewXBinding;import java.util.concurrent.ExecutionException Public class SimplePreviewXAct extends AppCompatActivity {private ActSimplePreivewXBinding mBinding; private ListenableFuture mCameraProviderFuture; private ProcessCameraProvider mCameraProvider; private boolean mRunning = false; @ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); mBinding = DataBindingUtil.setContentView (this, R.layout.act_simple_preivew_x); mCameraProviderFuture = ProcessCameraProvider.getInstance (this) MCameraProviderFuture.addListener (()-> {try {mCameraProvider = mCameraProviderFuture.get ();} catch (ExecutionException | InterruptedException e) {/ / No processing}}, ContextCompat.getMainExecutor (this)) MBinding.start.setOnClickListener (v-> {if (mCameraProvider! = null & &! mRunning) {bindPreview (mCameraProvider);}}); mBinding.end.setOnClickListener (v-> {mCameraProvider.unbindAll (); mRunning = false;}) } private void bindPreview (ProcessCameraProvider cameraProvider) {if (cameraProvider = = null) {Toast.makeText (getApplicationContext (), "No camera", Toast.LENGTH_SHORT) .show (); return;} Preview preview = new Preview.Builder () .build () CameraSelector cameraSelector = new CameraSelector.Builder () .roomLensFacing (CameraSelector.LENS_FACING_BACK) .build (); preview.setSurfaceProvider (mBinding.previewView.getSurfaceProvider ()); Camera camera = cameraProvider.bindToLifecycle (this, cameraSelector, preview); mRunning = true;}}

Don't bind the lifecycle immediately after you get the mCameraProvider.

If you want to turn on preview, call bindPreview (mCameraProvider). Record that the camera has now turned on preview mRunning = true.

If you want to stop previewing, unbind the lifecycle mCameraProvider.unbindAll (). This method needs to be called in the main thread.

After running, you can use the button to control the camera preview switch. The height of the PreviewView is a little smaller than before (giving some room to the button).

But the aspect ratio of the video is normal and has not been stretched. Under the default configuration, there is also the function of autofocus.

Judging from the simple preview of turning on the camera, CameraX simplifies the work of developers. PreviewView is provided, and developers do not need to customize SurfaceView or TextureView. In the real-time preview, the camera can focus automatically.

After reading the above, do you know how to preview the camera on Android CameraX? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report