package com.example.cameraaccess
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
class CameraAccessActivity : AppCompatActivity() {
private lateinit var openCameraButton: Button
private lateinit var photoImageView: ImageView
private val cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val imageBitmap = result.data?.extras?.get("data") as? Bitmap
if (imageBitmap != null) {
photoImageView.setImageBitmap(imageBitmap)
} else {
Toast.makeText(this, "Failed to capture image", Toast.LENGTH_SHORT).show()
}
}
}
private val requestPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
openCamera()
} else {
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera_access)
openCameraButton = findViewById(R.id.openCameraButton)
photoImageView = findViewById(R.id.photoImageView)
openCameraButton.setOnClickListener {
when {
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
openCamera()
}
else -> {
requestPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
}
}
private fun openCamera() {
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
cameraLauncher.launch(cameraIntent)
}
}This solution uses the modern Activity Result API to handle both permission requests and camera intent results.
When the user taps the 'Open Camera' button, the app checks if the camera permission is granted. If yes, it opens the camera. If not, it requests permission.
When the camera returns a photo, the app extracts the thumbnail bitmap from the intent extras and displays it in the ImageView below the button.
If permission is denied, a Toast message informs the user.