Complete the code to request camera permission in an Android app.
ActivityCompat.requestPermissions(this, arrayOf([1]), 100)
To access the camera, you must request Manifest.permission.CAMERA.
Complete the code to check if camera permission is granted.
if (ContextCompat.checkSelfPermission(this, [1]) == PackageManager.PERMISSION_GRANTED) { // Permission granted }
You check for Manifest.permission.CAMERA to see if camera access is allowed.
Fix the error in the code to open the camera using an Intent.
val cameraIntent = Intent([1]) startActivityForResult(cameraIntent, 101)
To open the camera for taking pictures, use MediaStore.ACTION_IMAGE_CAPTURE.
Fill both blanks to handle the camera permission result in onRequestPermissionsResult.
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == [1]) {
if (grantResults.isNotEmpty() && grantResults[0] == [2]) {
// Permission granted
}
}
}The requestCode should match the one used when requesting permission (100). The grant result should be compared to PackageManager.PERMISSION_GRANTED to check if permission was granted.
Fill all three blanks to create a camera preview using CameraX in a Fragment.
val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(viewFinder.[1])
}
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(this, cameraSelector, preview, [2])
} catch(exc: Exception) {
Log.e("CameraX", "Use case binding failed", exc)
}
}, ContextCompat.getMainExecutor(requireContext()))
val imageCapture = ImageCapture.Builder().build()
// Use imageCapture to take pictures
// The blank [3] should be the variable name for imageCapture1. The preview's surface provider is set with surfaceProvider.
2. The imageCapture use case is passed to bindToLifecycle.
3. The variable imageCapture is used to take pictures.