0
0
Android Kotlinmobile~20 mins

Camera access in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Camera Access Screen
This screen allows the user to open the device camera and take a photo. The photo is then displayed on the screen.
Target UI
-------------------------
| Camera Access Screen   |
|-----------------------|
| [Open Camera Button]   |
|                       |
| [Photo will appear here]|
|                       |
-------------------------
Add a button labeled 'Open Camera' that opens the device camera when tapped.
Request camera permission at runtime if not already granted.
Display the captured photo below the button after taking a picture.
Handle permission denial gracefully with a message.
Starter Code
Android Kotlin
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

    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 {
            // TODO: Check permission and open camera
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
Android Kotlin
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.

Final Result
Completed Screen
-------------------------
| Camera Access Screen   |
|-----------------------|
| [Open Camera Button]   |
|                       |
| [Captured photo shown] |
|                       |
-------------------------
User taps 'Open Camera' button.
If permission not granted, app asks for camera permission.
If permission granted, camera app opens.
User takes a photo and confirms.
Photo thumbnail appears below the button.
If permission denied, a message 'Camera permission denied' shows.
Stretch Goal
Add a button to save the captured photo to the device gallery.
💡 Hint
Use MediaStore.Images.Media.insertImage() method to save the bitmap.