Android

Android Camera

Android Camera

The Camera is a very useful functionality to capture images. In Android, you can add this functionality to your application by using MediaStore.ACTION_IMAGE_CAPTURE. To understand its working, you can refer to the example shown below:

The first thing you need to do is to create an application under a package com.firstapp.ashulakhwan.greatlearning

The next step is to modify its main file which can be found as src/MainActivity.java. Refer to the following code snippet for this file:

package com.firstapp.ashulakhwan.greatlearning;\

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {
   public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100;
   public static final String ALLOW_KEY = "Camera_Allowed";
   public static final String CAMERA_PREF = "Camera_Preference";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
         if (getFromPref(this, ALLOW_KEY)) {
            showSettingsAlert();
         } else if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.CAMERA)
            
            != PackageManager.PERMISSION_GRANTED) {
               
               if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                  Manifest.permission.CAMERA)) {
                  showAlert();
               } else {
                  ActivityCompat.requestPermissions(this,
                     new String[]{Manifest.permission.CAMERA},
                     MY_PERMISSIONS_REQUEST_CAMERA);
               }
            }
      } else {
         openCamera();
      }
      
   }
   public static void saveToPreferences(Context context, String key, Boolean allowed) {
      SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, 
         Context.MODE_PRIVATE);
      SharedPreferences.Editor prefsEditor = myPrefs.edit();
      prefsEditor.putBoolean(key, allowed);
      prefsEditor.commit();
   }
      
   public static Boolean getFromPref(Context context, String key) {
      SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, 
         Context.MODE_PRIVATE);
      return (myPrefs.getBoolean(key, false));
   }
      
   private void showAlert() {
      AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
      alertDialog.setTitle("Alert");
      alertDialog.setMessage("The application requires permission access.");
      
      alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Not allowed",
         new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               finish();
            }
      });
         
      alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "ALLOW",
         new DialogInterface.OnClickListener() {
         
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               ActivityCompat.requestPermissions(MainActivity.this,
               new String[]{Manifest.permission.CAMERA},
               MY_PERMISSIONS_REQUEST_CAMERA);
            }
      });
      alertDialog.show();
   }
      
   private void showSettingsAlert() {
      AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
      alertDialog.setTitle("Alert");
      alertDialog.setMessage("The application requires permission access.");
      alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Permission Denied",
         new DialogInterface.OnClickListener() {
         
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
            }
      });
         
      alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "SETTINGS",
         new DialogInterface.OnClickListener() {
                    
            public void onClick(DialogInterface dialog, int which) {
               dialog.dismiss();
               startInstalledAppDetailsActivity(MainActivity.this);
            }
      });
         
      alertDialog.show();
   }
      
   @Override
   public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
      switch (requestCode) {
         case MY_PERMISSIONS_REQUEST_CAMERA: {
            for (int i = 0, len = permissions.length; i < len; i++) {
               String permission = permissions[i];
            
               if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                  boolean 
                  showRationale = 
                     ActivityCompat.shouldShowRequestPermissionRationale(
                     this, permission);
                  
                  if (showRationale) {
                     showAlert();
                  } else if (!showRationale) {
             
                     saveToPreferences(MainActivity.this, ALLOW_KEY, true);
                  }
               }
            }
         }         
      }
   }
      
   @Override
   protected void onResume() {
      super.onResume();
   }
      
   public static void startInstalledAppDetailsActivity(final Activity context) {
      if (context == null) {
         return;
      }
         
      final Intent i = new Intent();
      i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
      i.addCategory(Intent.CATEGORY_DEFAULT);
      i.setData(Uri.parse("Package:" + context.getPackageName()));
      i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
      i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
      context.startActivity(i);
   }
      
   private void openCamera() {
      Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
      startActivity(intent);
   }
}

After that, you might need to modify its layout XML file with the name res/layout/activity_main.xml. The content for the files is shown below:

<?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" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
</RelativeLayout>

Next, you will be required to modify the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.firstapp.ashulakhwan.greatlearning" >
  <uses-permission android:name="android.permission.CAMERA" />
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/CustomTheme" >
      <activity
         android:name="com.firstapp.ashulakhwan.greatlearning"
         android:label="@string/app_name" >
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
     </activity>
   </application>
</manifest>

In the last step, you need to add permission for the Camera to use on your device and then run the application to verify the results. 
 

Top course recommendations for you

    Leap year program in Python
    1 hrs
    Beginner
    2.2K+ Learners
    4.45  (71)
    Prime Number in Java
    2 hrs
    Beginner
    2.6K+ Learners
    4.49  (55)
    Exception and File Handling with Python
    2 hrs
    Intermediate
    4.6K+ Learners
    4.35  (146)
    Heap Data Structure
    1 hrs
    Beginner
    2.2K+ Learners
    4.17  (165)
    Prime Number Program in Python
    1 hrs
    Beginner
    2.2K+ Learners
    4.19  (81)
    Python Uses
    1 hrs
    Beginner
    5.8K+ Learners
    4.33  (284)
    R Studio Basics
    1 hrs
    Beginner
    5.1K+ Learners
    4.53  (325)
    Class in java
    1 hrs
    Beginner
    7.4K+ Learners
    4.38  (319)
    Multithreading In Java
    2 hrs
    Intermediate
    5.9K+ Learners
    4.35  (425)