Main navigation

Android QR Code Scanner App Tutorial Using ZXING Library

adsense

Adding Permissions and Dependencies for android QR code scanner app

Open your AndroidManifest.xml file and add the following permissions.

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

These uses-permissions tag tells the Android OS that our app will require access to CAMERA. Similarly uses-feature tells what features will be used in the app.
Open your App’s build.gradle file and add the following dependency.

	    compile 'me.dm7.barcodescanner:zxing:1.9'

Adding Functionality to Scan QR Code and Bar Code

Open QrCodeScannerActivity.java and declare the following imports variables. Please note that our activity implements the Interface ZXingScannerView.ResultHandler to be able to act as QR Code Scanner as well as Bar Code scanner.

QrCodeScannerActivity.java

package com.androidtutorialpoint.qrcodescanner;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import static android.Manifest.permission.CAMERA;

public class QrCodeScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {

    private static final int REQUEST_CAMERA = 1;
    private ZXingScannerView mScannerView;
      

The constant REQUEST_CAMERA is used while getting the permissions from the user to use the camera. ZXingScannerView provides the view to scan the QR code and Bar code as shown below.

Android QR Code Scanner App - Window
Next, in the onCreate() method add the following code.

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("onCreate", "onCreate");

        mScannerView = new ZXingScannerView(this);
        setContentView(mScannerView);
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();

            } else {
                requestPermission();
            }
        }
    }

We create a new ZXingScannerView by passing the context. Then set the conteent view to the same using the setContentView() method. To access the Camera, we need permissions.
Starting from Android 6.0( Android Marshmallow) we have to get the user permissions at the runtime. So the next few lines checks for the api version
We need to detect whether the app has the required permissions or not otherwise we need to request those from the user befor accessing the camera.

Add the following code which implements the requestPermission() and checkPermission() methods for the android QR Code Scanner app.

    private boolean checkPermission() {
        return ( ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA ) == PackageManager.PERMISSION_GRANTED);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CAMERA:
                if (grantResults.length > 0) {

                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted){
                        Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
                }else {
                        Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if (shouldShowRequestPermissionRationale(CAMERA)) {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                                    requestPermissions(new String[]{CAMERA},
                                                            REQUEST_CAMERA);
                                                }
                                            }
                                        });
                                return;
                            }
                        }
                    }
                }
                break;
        }
    }

    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new android.support.v7.app.AlertDialog.Builder(QrCodeScannerActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

For the first time, when the user installs the app, the app will request permission to use the Camera, on subsequent app runs we don’t need to provide any permission.

    @Override
    public void onResume() {
        super.onResume();

        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
            if (checkPermission()) {
                if(mScannerView == null) {
                    mScannerView = new ZXingScannerView(this);
                    setContentView(mScannerView);
                }
                mScannerView.setResultHandler(this);
                mScannerView.startCamera();
            } else {
                requestPermission();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mScannerView.stopCamera();
    }

We need to handle the onResume() and onDestroy() lifecycle methods for QRCodeScannerActivity. In the onResume() we check if the ScannerView is null or not, in case it is null we create a new one and then start the Camera to capture the QR Code using the startCamera() method. Similarly in the onDestroy() we release the Camera using the stopCamera().

To implement the ZXingScannerView.ResultHandler we need to implement the method handleResult(). This method contains the Logic to handle the Result of the scan from the android QR Scanner or the Bar Code scanner. Add the following code that will handle the result for you.

@Override
    public void handleResult(Result rawResult) {

        final String result = rawResult.getText();
        Log.d("QRCodeScanner", rawResult.getText());
        Log.d("QRCodeScanner", rawResult.getBarcodeFormat().toString());

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Scan Result");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mScannerView.resumeCameraPreview(QrCodeScannerActivity.this);
                    }
                });
                builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                      Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result));
                        startActivity(browserIntent);
                    }
                });
                builder.setMessage(rawResult.getText());
                AlertDialog alert1 = builder.create();
                alert1.show();
    }

On getting the result from the QR Code or Bar Code scan, this method will be called. We are logging the result to the LogCat as well as Showing a AlertDialog with the result of the scan and two buttons. Clicking on OK button will resume the Scanning. If you scanned the QR code for some website then you can open that website by clicking on the Visit button.

Now run your newly created Android QR Scanner app on an Actual Device, Point to a QR Code or a Bar Code and you will be amazed to see the result. You can downlaod the android QR Scanner app source code by clicking on the Download Now button.
Android Tutorial Point Download Now


What’s Next ??

We will soon cover more tutorials under Learn By Doing !! section to provide hand’s on experience. Thanks guys for reading. If you have any doubts or suggestion then please leave comments in the comments section below . Subscribe to our website for latest Android Tutorials. Also do Like our Facebook Page or Add us on Twitter.

Reader Interactions

Comments

    • Make sure that you have added the following in the library dependency in your app’s build.gradle file

      ‘me.dm7.barcodescanner:zxing:1.9’

  1. It doesn’t build. I followed the tutorial and the I just gave them my email address to download the project. It doesn’t build either. Moving on.

Leave a Reply

Advertisment ad adsense adlogger