How do I open front camera programmatically on the Android platform?


Introduction

Many mobile applications specify the feature within it to capture the user's image through the front camera. We can get to see this type of feature in applications such as Snapchat, Instagram and others. In this article we will take a look on How to open front camera in our android application and display the captured image within our application.

Implementation of Front Camera in Android

We will be creating a simple application in which we will be displaying a simple text view to display the heading of our application. After that we will be displaying an image view to display the captured image. Then we will be displaying a button which we will be using to capture the image from the front camera. We will be following a step by step guide to implement addition of two numbers in Android.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Kotlin.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.kt file.

Step 3 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

   <!-- creating text view for displaying heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="20dp"
      android:gravity="center"
      android:text="Front Camera in Android"
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="#FF000000"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- creating an image view for displaying image-->
   <ImageView
      android:id="@+id/idIVImage"
      android:layout_width="match_parent"
      android:layout_height="300dp"
      android:layout_below="@id/idTVHeading"
      android:layout_margin="10dp"
      android:padding="3dp" />

   <!-- creating a button to capture image-->
   <Button
      android:id="@+id/idBtnCaptureImage"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idIVImage"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Capture Image"
      android:textAllCaps="false" />
</RelaiveLayout>

Explanation − In the above code we are creating a Relative layout as a root layout and inside that we are creating our text view to display a simple heading. After that we are creating an image view to display the captured image. Lastly we are displaying a button which we will be using to capture the image from the front camera.

Step 4 : Working with MainActivity.kt file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.kt to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.gtappdevelopers.androidapplication

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.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class MainActivity : AppCompatActivity() {

   // creating variable for buttons, image view on below line.
   lateinit var captureImageBtn: Button
   lateinit var imageView: ImageView

   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      
      // on below line initializing variables for buttons and image view.
      captureImageBtn = findViewById(R.id.idBtnCaptureImage)
      imageView = findViewById(R.id.idIVImage)
      
      // adding click listener for capture image button on below line.
      captureImageBtn.setOnClickListener {
         
         // on below line checking if permission is denied
         if (ContextCompat.checkSelfPermission(
            this@MainActivity,
            android.Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_DENIED
         ) {
            //on below line Requesting the camera permission
            ActivityCompat.requestPermissions(
               this@MainActivity,
               arrayOf(android.Manifest.permission.CAMERA),
               100
            )
         } else {
            // below method called when camera permission is already granted.
            // creating camera intent to capture image
            val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            // on below lien passing camera intent type as front camera.
            cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)
            // on below line starting activity for result.
            startActivityForResult(cameraIntent, 123)
         }
      }
   }
   // on below line calling on activity result to set to our image view.
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      
      // on below line comparing the request code
      if (requestCode == 123) {
         
         // on below line getting image bitmap from our data and setting it to image view.
         val image = data!!.extras!!["data"] as Bitmap?
         imageView.setImageBitmap(image)
      }
   }
   override fun onRequestPermissionsResult(
      requestCode: Int,
      permissions: Array<out String>,
      grantResults: IntArray
   ) {
      // on below line handling permissions when accepting.
      super.onRequestPermissionsResult(requestCode, permissions, grantResults)
      if (requestCode == 123) {
         
         // on below line checking if the permissions are granted.
         if (grantResults.size != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
         
            // on below line displaying toast message as permissions granted and opening our camera intent
            Toast.makeText(this, "Camera Permission Granted..", Toast.LENGTH_SHORT).show()
            val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)
            
            // on below line opening new activity.
            startActivityForResult(cameraIntent, 123)
         } else {
            
            // on below line displaying a toast message.
            Toast.makeText(this, "Camera Permission Denined..", Toast.LENGTH_SHORT).show()
         }
      }
   }

}

Explanation − In the above code firstly we are creating variables for image view, button. After that we are initializing our variables for image view and button inside our on create method with the id which we have given in our activity_main.xml file. After that we are adding an on click listener for our capture image button. Inside the on click method we are checking for the camera permissions. If the permissions are not granted then we are asking for the camera permission. If the permission is already granted then we are opening a camera intent to by passing the front camera to it to capture image using the front camera.

Then we are creating an onActivityResult method inside which we will get the image bitmap and set that image bitmap to our image view. After that we are creating one more method named as onRequestPermissionResult method. Inside this method we are again checking the camera permissions. If camera permissions are granted then we are opening our camera intent again. Else we are displaying toast message as camera permissions are denied.

Step 5 : Working with AndroidManifest.xml file

Navigate to AndroidManifest.xml file and add below permission for camera in it.

<uses-permission android:name="android.permission.CAMERA" />

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we learn How to access the front camera in android application programmatically and capture the image and display that image in the image view within our android application.

Updated on: 30-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements