CodexBloom - Programming Q&A Platform

implementing Handling Camera Permissions in Android 14 When Using CameraX

πŸ‘€ Views: 43 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-16
android camerax permissions kotlin

I'm stuck on something that should probably be simple..... I'm working with a frustrating scenario while trying to implement camera functionality in my Android app using CameraX. Although I have declared the necessary permissions in the `AndroidManifest.xml`, I'm still getting a `SecurityException` when I attempt to access the camera. My app targets Android 14, and I understand that there have been some changes regarding runtime permissions. Here's what I've done so far: In my `AndroidManifest.xml`, I have the following permissions: ```xml <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` Before trying to open the camera, I'm making sure to check for permissions like this: ```kotlin private fun checkCameraPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_REQUEST_CODE) } else { startCamera() // This is where I start the camera } } ``` I've overridden `onRequestPermissionsResult` to handle the user's response, and I'm calling `checkCameraPermissions()` when the activity starts. However, even after granting the permissions, I still receive the `SecurityException` when I call `startCamera()`. Here’s how I set up the camera: ```kotlin private fun startCamera() { val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener({ val cameraProvider = cameraProviderFuture.get() val preview = Preview.Builder().build().also { it.setSurfaceProvider(viewFinder.surfaceProvider) } val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA try { cameraProvider.unbindAll() // Unbind use cases before rebinding cameraProvider.bindToLifecycle(this, cameraSelector, preview) } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } ``` When I try to run this code, I get the following behavior in the logcat: ``` E/CameraX: Use case binding failed java.lang.SecurityException: Permission denied: need CAMERA permission to use this feature ``` I’ve tried explicitly checking for the permission again in `startCamera()`, but it still throws the exception. Is there something I might be missing with the new permission model in Android 14, or is there a different scenario at play? Any insights or suggestions would be greatly appreciated! Any ideas what could be causing this? I'm coming from a different tech stack and learning Kotlin. What's the correct way to implement this?