Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

Issues about implementing a preview for CameraX in Android Studio

I've tried to implement a preview for CameraX, but I've got two errors in my code, that I cannot solve:

  1. CameraSelector is not public in androidx.camera.core.CameraSelector. Cannot be accessed from outside package.

  2. Cannot resolve symbol 'previewView'

EDIT: I solved the problems, but I still don't get the preview. I did not mentioned before, but I inserted the permissions in the Android Manifest.

Here's my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PreviewView previewView = (PreviewView) findViewById(R.id.previewView);

        cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                Preview preview = new Preview.Builder().build();
                CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build(); 
                preview.setSurfaceProvider(previewView.createSurfaceProvider());     
                cameraProvider.unbindAll();
                cameraProvider.bindToLifecycle((LifecycleOwner)this, cameraSelector, preview);
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(this));

    }

}

Build.gradle (Module: app), inside dependencies section

def camerax_version = "1.0.0-beta07"
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-alpha14"

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</RelativeLayout>

I know that createSurfaceProvider() has been renamed to getSurfaceProvider() since Camera-View Version 1.0.0-alpha16, but when I try to call the last method Android Studio does not solve it.

And here's the logs (error)

2020-11-22 20:59:01.944 10830-10830/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2020-11-22 20:59:01.945 10830-10830/? E/Zygote: accessInfo : 1
2020-11-22 20:59:03.214 10830-10885/com.android.unipi.camerademo E/Camera_APM?:: [APM]APM's Thread is started
2020-11-22 20:59:03.216 10830-10885/com.android.unipi.camerademo E/Camera_APM?:: [APM] This app is forground app
2020-11-22 20:59:03.223 10830-10872/com.android.unipi.camerademo E/SequentialExecutor: Exception while executing runnable androidx.camera.camera2.internal.-$$Lambda$Camera2CameraImpl$_NFNV64YCFFY0Tn3VRiyE3Ss3S0@5d0b8a
    java.lang.SecurityException: validateClientPermissionsLocked:1145: Caller "com.android.unipi.camerademo" (PID 10188, UID 10830) cannot open camera "0" without camera permission
        at android.hardware.camera2.CameraManager.throwAsPublicException(CameraManager.java:855)
        at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:499)
        at android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:670)
        at android.hardware.camera2.CameraManager.openCamera(CameraManager.java:638)
        at androidx.camera.camera2.internal.compat.CameraManagerCompatApi28Impl.openCamera(CameraManagerCompatApi28Impl.java:70)
        at androidx.camera.camera2.internal.compat.CameraManagerCompat.openCamera(CameraManagerCompat.java:185)
        at androidx.camera.camera2.internal.Camera2CameraImpl.openCameraDevice(Camera2CameraImpl.java:871)
        at androidx.camera.camera2.internal.Camera2CameraImpl.openInternal(Camera2CameraImpl.java:236)
        at androidx.camera.camera2.internal.Camera2CameraImpl.tryAttachUseCases(Camera2CameraImpl.java:691)
        at androidx.camera.camera2.internal.Camera2CameraImpl.lambda$attachUseCases$10$Camera2CameraImpl(Camera2CameraImpl.java:649)
        at androidx.camera.camera2.internal.-$$Lambda$Camera2CameraImpl$_NFNV64YCFFY0Tn3VRiyE3Ss3S0.run(Unknown Source:4)
        at androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.workOnQueue(SequentialExecutor.java:230)
        at androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.run(SequentialExecutor.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: android.os.ServiceSpecificException: validateClientPermissionsLocked:1145: Caller "com.android.unipi.camerademo" (PID 10188, UID 10830) cannot open camera "0" without camera permission (code 1)
        at android.os.Parcel.createException(Parcel.java:1980)
        at android.os.Parcel.readException(Parcel.java:1934)
        at android.os.Parcel.readException(Parcel.java:1884)
        at android.hardware.ICameraService$Stub$Proxy.connectDevice(ICameraService.java:359)
        at android.hardware.camera2.CameraManager.openCameraDeviceUserAsync(CameraManager.java:463)
        at android.hardware.camera2.CameraManager.openCameraForUid(CameraManager.java:670)?
        at android.hardware.camera2.CameraManager.openCamera(CameraManager.java:638)?
        at androidx.camera.camera2.internal.compat.CameraManagerCompatApi28Impl.openCamera(CameraManagerCompatApi28Impl.java:70)?
        at androidx.camera.camera2.internal.compat.CameraManagerCompat.openCamera(CameraManagerCompat.java:185)?
        at androidx.camera.camera2.internal.Camera2CameraImpl.openCameraDevice(Camera2CameraImpl.java:871)?
        at androidx.camera.camera2.internal.Camera2CameraImpl.openInternal(Camera2CameraImpl.java:236)?
        at androidx.camera.camera2.internal.Camera2CameraImpl.tryAttachUseCases(Camera2CameraImpl.java:691)?
        at androidx.camera.camera2.internal.Camera2CameraImpl.lambda$attachUseCases$10$Camera2CameraImpl(Camera2CameraImpl.java:649)?
        at androidx.camera.camera2.internal.-$$Lambda$Camera2CameraImpl$_NFNV64YCFFY0Tn3VRiyE3Ss3S0.run(Unknown Source:4)?
        at androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.workOnQueue(SequentialExecutor.java:230)?
        at androidx.camera.core.impl.utils.executor.SequentialExecutor$QueueWorker.run(SequentialExecutor.java:172)?
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)?
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)?
        at java.lang.Thread.run(Thread.java:764)?

According to the logs, I don't insert camera permission, but I do that. Maybe I miss other permissions?

question from:https://stackoverflow.com/questions/65939600/issues-about-implementing-a-preview-for-camerax-in-android-studio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With the suggestions of Husayn and Shark I've solved the problem. Any device with Android 6 or higher version (API 23+) requires a runtime permission.

Check if the user has granted the camera permission. Otherwise, request that permission. Insert the following code inside the onCreate() method before calling CameraX code:

if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);
}

where CAMERA_REQUEST is a constant. Here's an example:

private static final int CAMERA_REQUEST = 100;

Then, it will appear a dialog, in which the user can allow or deny the permission. We can see the result with the following method:

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_REQUEST) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "CameraX permission granted", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "CameraX permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...