Monday 7 February 2022

Capture photos in android without opening camera

 



activity_main.xml

<?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">


    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:weightSum="2"

        android:layout_margin="10dp">


        <Button

            android:id="@+id/btn_front"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="Front Camera"

            android:layout_marginEnd="10dp" />


        <Button

            android:id="@+id/btn_back"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            android:text="Back Camera" />

    </LinearLayout>


    <ImageView

        android:id="@+id/iv_image"

        android:layout_width="250dp"

        android:layout_height="250dp"

        android:layout_centerInParent="true"/>


</RelativeLayout>


MainActivity.java

package com.surabhiglobal.example;


import android.Manifest;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.SurfaceTexture;

import android.hardware.Camera;

import android.net.Uri;

import android.os.Bundle;

import android.provider.Settings;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.ImageView;


import androidx.appcompat.app.AppCompatActivity;


import com.karumi.dexter.Dexter;

import com.karumi.dexter.MultiplePermissionsReport;

import com.karumi.dexter.PermissionToken;

import com.karumi.dexter.listener.PermissionRequest;

import com.karumi.dexter.listener.multi.MultiplePermissionsListener;


import java.util.List;


public class MainActivity extends AppCompatActivity {


    private Button btn_front, btn_back;

    private String TAG = MainActivity.class.getName();

    private ImageView iv_image;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        btn_front = findViewById(R.id.btn_front);

        btn_back = findViewById(R.id.btn_back);

        iv_image = findViewById(R.id.iv_image);


        btn_front.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                requestAppPermissions("1");

            }

        });


        btn_back.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                requestAppPermissions("0");

            }

        });

    }


    private void requestAppPermissions(String type) {


        Dexter.withActivity(MainActivity.this)

                .withPermissions(

                        Manifest.permission.CAMERA)

                .withListener(new MultiplePermissionsListener() {

                    @Override

                    public void onPermissionsChecked(MultiplePermissionsReport report) {

                        if (report.areAllPermissionsGranted()) {

                            if (type.equals("0")) {

                                CaptureBackPhoto();

                            } else {

                                CaptureFrontPhoto();

                            }

                        }

                        // check for permanent denial of any permission

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            // permission is denied permenantly, navigate user to app settings

                            showSettingsDialog();

                        }

                    }


                    @Override

                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();

                    }


                })

                .onSameThread()

                .check();



    }


    private void showSettingsDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        builder.setTitle("Need Permissions");

        builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");

        builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

                openSettings();

            }

        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            @Override

            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();

            }

        });

        builder.show();


    }


    private void openSettings() {

        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);

        Uri uri = Uri.fromParts("package", getPackageName(), null);

        intent.setData(uri);

        startActivityForResult(intent, 101);

    }



    private void CaptureFrontPhoto() {


        Log.d(TAG, "Preparing to take photo");

        Camera camera = null;


        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();


        int frontCamera = 1;

        //int backCamera=0;


        Camera.getCameraInfo(frontCamera, cameraInfo);


        try {

            camera = Camera.open(frontCamera);

            camera.enableShutterSound(false);

        } catch (RuntimeException e) {

            Log.d(TAG, "Camera not available: " + 1);

            camera = null;

            //e.printStackTrace();

        }

        try {

            if (null == camera) {

                Log.d(TAG, "Could not get camera instance");

            } else {

                Log.d(TAG, "Got the camera, creating the dummy surface texture");

                try {

                    camera.setPreviewTexture(new SurfaceTexture(0));

                    camera.startPreview();

                } catch (Exception e) {

                    Log.d(TAG, "Could not set the surface preview texture");

                    e.printStackTrace();

                }

                camera.takePicture(null, null, new Camera.PictureCallback() {


                    @Override

                    public void onPictureTaken(byte[] data, Camera camera) {


                        try {

                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

                            iv_image.setImageBitmap(bmp);


                        } catch (Exception e) {

                            System.out.println(e.getMessage());

                        }


                        camera.release();

                    }

                });

            }


        } catch (Exception e) {

            camera.release();

        }

    }


    private void CaptureBackPhoto() {


        Log.d(TAG, "Preparing to take photo");

        Camera camera = null;


        try {

            camera = Camera.open();

            camera.enableShutterSound(false);

        } catch (RuntimeException e) {

            Log.d(TAG, "Camera not available: " + 1);

            camera = null;

            //e.printStackTrace();

        }

        try {

            if (null == camera) {

                Log.d(TAG, "Could not get camera instance");

            } else {

                Log.d(TAG, "Got the camera, creating the dummy surface texture");

                try {

                    camera.setPreviewTexture(new SurfaceTexture(0));

                    camera.startPreview();

                } catch (Exception e) {

                    Log.d(TAG, "Could not set the surface preview texture");

                    e.printStackTrace();

                }

                camera.takePicture(null, null, new Camera.PictureCallback() {


                    @Override

                    public void onPictureTaken(byte[] data, Camera camera) {


                        try {

                            Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);


                            iv_image.setImageBitmap(bmp);


                        } catch (Exception e) {

                            System.out.println(e.getMessage());

                        }


                        camera.release();

                    }

                });

            }


        } catch (Exception e) {

            camera.release();

        }

    }

}


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.surabhiglobal.example">


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

    <uses-feature android:name="android.hardware.camera" />


    <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/Theme.ForegroundServiceExample">


        <activity

            android:name=".MainActivity"

            android:configChanges="orientation|screenSize">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>


build.gradle (app level file)

plugins {

    id 'com.android.application'

}

android {

    compileSdkVersion 30

    buildToolsVersion "30.0.3"


    defaultConfig {

        applicationId "com.surabhiglobal.example"

        minSdkVersion 17

        targetSdkVersion 30

        versionCode 1

        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'

        }

    }

    compileOptions {

        sourceCompatibility JavaVersion.VERSION_1_8

        targetCompatibility JavaVersion.VERSION_1_8

    }

}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'

    implementation 'com.google.android.material:material:1.3.0'

    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'

    testImplementation 'junit:junit:4.13.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.2'

    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

    //add this dependency

    implementation 'com.karumi:dexter:4.2.0'

}

1 comment:

  1. Hi, I am exactly same things to capture the image by using front camera(without opening a camera). It was working perfectly till now but suddenly app start showing a black screen for fraction of second while capturing the image from front camera.
    Nothing is showing in error log or console logs.
    Do you have any idea about this?

    ReplyDelete

Alarm Manager Example in Android