// Step 1: Add the necessary permissions to your AndroidManifest.xml file
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
// Step 2: Add the following code to your Activity or Fragment
// Import necessary packages
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
// Request code for camera permission
private val CAMERA_PERMISSION_REQUEST_CODE = 100
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Step 3: Check if the camera permission is granted
if (ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) != PackageManager.PERMISSION_GRANTED
) {
// Step 4: Request camera permission if not granted
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
CAMERA_PERMISSION_REQUEST_CODE
)
} else {
// Step 5: Permission already granted, open the camera
openCamera()
}
}
// Step 6: Handle the result of the permission request
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Step 7: Permission granted, open the camera
openCamera()
} else {
// Step 8: Permission denied, show a message
Toast.makeText(
this,
"Camera permission is required to use the camera.",
Toast.LENGTH_SHORT
).show()
}
}
}
// Step 9: Open the camera
private fun openCamera() {
// Example: Open the camera using an Intent
val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE)
}
// Step 10: Handle the result of the camera capture
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
// Handle the captured image or video here
// For example, you can get the image from the data intent
val image = data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(image)
}
}
}