How to click a camera programmatically in Android?


This example demonstrates how to

Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_above="@id/imageView"
   android:layout_centerInParent="true"
   android:layout_marginBottom="10dp"
   android:text="Click the below button to take photo from camera"
   android:textAlignment="center"
   android:textColor="@android:color/holo_purple"
   android:textSize="16sp"
   android:textStyle="bold" />
<ImageView
   android:id="@+id/imageView"
   android:layout_width="match_parent"
   android:layout_height="630dp"
   android:layout_above="@id/btnCaptureImage"
   android:layout_marginTop="16dp"
   android:scaleType="centerCrop"
   android:src="@drawable/ic_baseline_image_24" />
<Button
   android:id="@+id/btnCaptureImage"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_alignParentBottom="true"
   android:text="Capture Image" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.Manifest
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
   lateinit var button: Button
   private lateinit var imageView: ImageView
   lateinit var imageUri: Uri
   private val permissionCode = 1000
   private val imageCaptureCode = 1001
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      imageView = findViewById(R.id.imageView)
      button = findViewById(R.id.btnCaptureImage)
      button.setOnClickListener {
         ActivityCompat.requestPermissions(
            this,
            arrayOf(Manifest.permission.CAMERA),
            permissionCode
         )
         if (ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
         ) != PackageManager.PERMISSION_GRANTED
         ) {
            openCamera()
         } else {
            PackageManager.PERMISSION_DENIED
         }
      }
   }
   private fun openCamera() {
      val values = ContentValues()
      values.put(MediaStore.Images.Media.TITLE, "New Picture")
      values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
      imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)!!
      val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
      cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
      startActivityForResult(cameraIntent, imageCaptureCode)
   }
   override fun onRequestPermissionsResult(
   requestCode: Int,
   permissions: Array<String?>,
   grantResults: IntArray
   ) {
      when (requestCode) {
         permissionCode -> {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               openCamera()
            } else {
               Toast.makeText(this, "Permission denied...", Toast.LENGTH_SHORT).show()
            }
         }
      }  
   }
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      if (resultCode == RESULT_OK) {
         imageView.setImageURI(imageUri);
      }
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <uses-permission android:name="android.permission.CAMERA" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

NOTE: TRY THIS IS REAL DEVICE FOR BETTER RESULTS

Updated on: 21-Jul-2020

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements