Open In App

How to Read QR Code using CAMView Library in Android?

Last Updated : 16 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

CAMView Library is a simple solution for accessing users’ device camera. By using this library we can access users’ cameras and use to perform so many functions of the camera such as scanning barcodes that are done by using a built-in ZXing decoding engine. This library contains a set of components that are ready to be put in your layout in order to give instant access to so many features. This library handles low-level routines such as camera, configuration, streaming, orientation, and many more. We just have to follow some basic steps to use this library. 

https://www.youtube.com/watch?v=5DEHmN4PmA0

Important Methods

Methods

Description

onScannerStarted() This method can be used when the scanner is started.
onScannerStopped() This method is called when the scanner is stopped. 
onScannerError() This method is used when the scanner gives some error.
onCodeScanned() This method is called when the scanner scans the data from the camera. 

Implementation of CAMView Library

Using this library we will create a simple QR Code scanning app that will scan data from QR code and display it in a TextView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Use CAMView Library in Android Apps

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency to build.gradle(Module:app)

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. 

implementation (‘eu.livotov.labs.android:CAMView:2.0.1@aar’) {transitive=true}

Now sync option will appear at the top right corner click on the sync now option. 

Step 3: Modify the strings.xml file

Below is the code for the strings.xml file.

XML




<resources>
    <string name="app_name">GFG APP</string>
    <string name="toggle_flash">Toggle Flash</string>
    <string name="action_settings">Settings</string>
    <string name="scanned_data">Scanned Data</string>
</resources>


Step 4: Add permission for the camera in the manifest file 
 We are adding a camera and vibrate permission in our manifest file. Navigate to the app > manifest to find AndroidManifest.xml. Below is the code snippet for AndroidManifest.xml

XML




<?xml version="1.0" encoding="utf-8"?>
    package="com.gtappdevelopers.camviewlibrary">
 
    <!--Permission for camera-->
    <uses-permission android:name="android.permission.CAMERA" />
    <!--Permission to vibrate-->
    <uses-permission android:name="android.permission.VIBRATE"/>
 
 
    <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.CamViewLibrary">
        <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>


Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.  

XML




<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--Frame layout is required as we are using camera view-->
    <!--Below is the scannerliveview which will scan QR code-->
    <eu.livotov.labs.android.camview.ScannerLiveView
        android:id="@+id/camview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <!--TextView to display the scanned data-->
    <TextView
        android:id="@+id/idTVscanned"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/white"
        android:padding="5dp"
        android:text="@string/scanned_data"
        android:textColor="@color/black" />
 
</FrameLayout>


Step 6: Working with the MainActivity.java file

Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 

Java




import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
 
import eu.livotov.labs.android.camview.ScannerLiveView;
import eu.livotov.labs.android.camview.scanner.decoder.zxing.ZXDecoder;
 
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.VIBRATE;
 
public class MainActivity extends AppCompatActivity {
    private ScannerLiveView camera;
    private TextView scannedTV;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // check permission method is to check that the
        // camera permission is granted by user or not.
        // request permission method is to request the
        // camera permission if not given.
        if (checkPermission()) {
            // if permission is already granted display a toast message
            Toast.makeText(this, "Permission Granted..", Toast.LENGTH_SHORT).show();
        } else {
            requestPermission();
        }
 
        // initialize scannerLiveview and textview.
        scannedTV = findViewById(R.id.idTVscanned);
        camera = (ScannerLiveView) findViewById(R.id.camview);
 
        camera.setScannerViewEventListener(new ScannerLiveView.ScannerViewEventListener() {
            @Override
            public void onScannerStarted(ScannerLiveView scanner) {
                // method is called when scanner is started
                Toast.makeText(MainActivity.this, "Scanner Started", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onScannerStopped(ScannerLiveView scanner) {
                // method is called when scanner is stopped.
                Toast.makeText(MainActivity.this, "Scanner Stopped", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onScannerError(Throwable err) {
                // method is called when scanner gives some error.
                Toast.makeText(MainActivity.this, "Scanner Error: " + err.getMessage(), Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onCodeScanned(String data) {
                // method is called when camera scans the
                // qr code and the data from qr code is
                // stored in data in string format.
                scannedTV.setText(data);
            }
        });
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        ZXDecoder decoder = new ZXDecoder();
        // 0.5 is the area where we have
        // to place red marker for scanning.
        decoder.setScanAreaPercent(0.8);
        // below method will set decoder to camera.
        camera.setDecoder(decoder);
        camera.startScanner();
    }
 
    @Override
    protected void onPause() {
        // on app pause the
        // camera will stop scanning.
        camera.stopScanner();
        super.onPause();
    }
 
    private boolean checkPermission() {
        // here we are checking two permission that is vibrate
        // and camera which is granted by user and not.
        // if permission is granted then we are returning
        // true otherwise false.
        int camera_permission = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
        int vibrate_permission = ContextCompat.checkSelfPermission(getApplicationContext(), VIBRATE);
        return camera_permission == PackageManager.PERMISSION_GRANTED && vibrate_permission == PackageManager.PERMISSION_GRANTED;
    }
 
 
    private void requestPermission() {
        // this method is to request
        // the runtime permission.
        int PERMISSION_REQUEST_CODE = 200;
        ActivityCompat.requestPermissions(this, new String[]{CAMERA, VIBRATE}, PERMISSION_REQUEST_CODE);
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        // this method is called when user
        // allows the permission to use camera.
        if (grantResults.length > 0) {
            boolean cameraaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            boolean vibrateaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
            if (cameraaccepted && vibrateaccepted) {
                Toast.makeText(this, "Permission granted..", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Permission Denied \n You cannot use app without providing permission", Toast.LENGTH_SHORT).show();
            }
        }
    }
}


Output: Run on a Real Device

Now run your app on a real device and scan some sample QR code and you will get to test the app. Make sure to allow camera permission on app launch. 

GitHub link for this project: https://github.com/ChaitanyaMunje/QR_Code_Scanner



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads