digitalmidges
digitalmidges

Reputation: 856

Android - Camera X - How to check if device has a Front Camera CameraX.LensFacing.FRONT

I'm working with Camera X for the first time and I can't find a way to check if a device has a front or rear camera in runtime...

I only need to use the preview I'm not capturing images so i can't use a button for it..

private var lensFacing = CameraX.LensFacing.FRONT

 val viewFinderConfig = PreviewConfig.Builder().apply {
            setLensFacing(lensFacing)
            setTargetAspectRatio(screenAspectRatio)
            setTargetRotation(viewFinder.display.rotation)
        }.build()

How can I make sure that the app won't crash if the user device has no Front camera? Thanks in advance!

Upvotes: 2

Views: 4555

Answers (1)

LaurentP22
LaurentP22

Reputation: 606

Check if the device supports at least one camera with the specified lens facing:

version 1.0.0-alpha06:

val hasFrontCamera = CameraX.hasCameraWithLensFacing(CameraX.LensFacing.FRONT)

EDIT :

version >= 1.0.0-alpha07:

From https://developer.android.com/jetpack/androidx/releases/camera:

hasCamera() previously provided by the CameraX class call are now available via the ProcessCameraProvider

override fun onCreate(savedInstanceState: Bundle?) {
    cameraProviderFuture = ProcessCameraProvider.getInstance(this);
}

cameraProviderFuture.addListener(Runnable {
    val cameraProvider = cameraProviderFuture.get()
    try {
        var hasCamera = cameraProvider.hasCamera(CameraSelector.DEFAULT_FRONT_CAMERA)
    } catch (e: CameraInfoUnavailableException) {
        e.printStackTrace()
    }
}, ContextCompat.getMainExecutor(this))

Upvotes: 12

Related Questions