View external USB camera image on PreviewView in Android

157 Views Asked by At

Is there a way to pass SurfaceView as the SurfaceProvider for a Preview in Android?

I have two Fragments, each one has a PreviewView to display the Camera feed of the following Cameras on my Android device:

  1. DeviceFragment -> Displays built-in camera feed
  2. UsbCameraFragment -> Should display the attached USB device camera feed

PreviewView on Fragment #1 works just fine as I think it's meant to display the Device camera right away.

But PreviewView on Fragment #2, no matter what I do, won't display the USB Camera feed. It only displays the built-in Device camera feed. So, in order to be sure my USB Camera feed is working, I setup a SurfaceView on that Fragment et voilà, my USB feed is displayed correctly on that.

Is there a way to change the default behavior of PreviewView so it displays my USB camera instead of the Device's?

My final goal is to process the camera feed via the CameraProvider.bindToLifecycle() method. To achieve this, I created a Preview object and set PreviewView.getSurfaceProvider() as its surfaceProvider. But I can't achieve the same using a SurfaceView as it has no methods that return a surfaceProvider.

Here's a snippet of the method I created on my UsbCameraFragment that could help understanding:

private void bindCamera(ProcessCameraProvider cameraProvider) {
    ImageAnalysis imageAnalysis = imageAnalysisService.bindImageAnalysis(surfaceView); // I don't think it's relevant right now. Can share later if needed.
    Preview preview = new Preview.Builder().build();
    preview.setSurfaceProvider(previewView.getSurfaceProvider()); // Here's where I would like to use my SurfaceView OR parse it to PreviewView
    CameraSelector cameraSelector = new CameraSelector.Builder()
                    .requireLensFacing(CameraSelector.LENS_FACING_BACK).build();

    cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
}

NOTES:

  • Commenting out preview.setSurfaceProvider(previewView.getSurfaceProvider()); makes my SurfaceView be displayed and it doesn't get overlapped by the PreviewView
  • Keeping it as it, the SurfaceView is displayed for a brief second and then it gets overlapped by the Device Camera's image (rendered by the PreviewView)
  • I tried adding a filter to the CameraSelector object, but then I have another problem: The Usb Camera is not listed among all available cameras.
0

There are 0 best solutions below