Tutorial

Scanning QR-code with Android

noras noras |

Tags: #Android #Java

This article will be about how integrate the possibility of scanning QR-code(or bar-codes) in your android application. Having the possibility to scan QR-codes (or bar-codes) is always a nice plus to your Android application.

Some use it a way for sharing information from one device to another like business card (contact sharing), while other use it for easier data input like wifi authentication, product scanning and URL scanning.  Some new applications also use QR-code scanning for adding friends and sharing stories.

Note that their are tons of libraries that can be used, however this article aims to provide a fast copy/paste solution  for anyone.

Adding the libraries and dependencies

In app level build.gradle

repositories {
    jcenter()

    maven { url 'https://jitpack.io' }
    maven { url 'https://maven.google.com' }

}

dependencies {
...
    compile 'me.dm7.barcodescanner:zbar:1.9'
...
}

ScanActivity.java

 


import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.util.Arrays;

import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;

public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
    private static final int CAMERA_CODE = 1;
    private ZBarScannerView mScannerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        askForPermission(android.Manifest.permission.CAMERA, CAMERA_CODE);
    }

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(ScanActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(ScanActivity.this, permission)) {
                ActivityCompat.requestPermissions(ScanActivity.this, new String[]{permission}, requestCode);
            } else {
                ActivityCompat.requestPermissions(ScanActivity.this, new String[]{permission}, requestCode);
            }
        } else {

            setupCameraScanner();
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {

        if (requestCode == CAMERA_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission granted, setup camera
                setupCameraScanner();
            } else {
                // permission denied!

                Toast.makeText(this, "Permission required", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void setupCameraScanner() {
        if (mScannerView == null) {
            FrameLayout scanFrame = (FrameLayout) findViewById(R.id.scan_preview);
            mScannerView = new ZBarScannerView(this);
            mScannerView.setFormats(Arrays.asList(BarcodeFormat.QRCODE));
            scanFrame.addView(mScannerView);

            mScannerView.setResultHandler(this);
            mScannerView.startCamera();          // Start camera
        }
    }

    @Override
    public void handleResult(Result rawResult) {

        Log.d("result",rawResult.getContents());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mScannerView != null) {
            mScannerView.resumeCameraPreview(this);          // Resume camera
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mScannerView != null) {
            mScannerView.stopCamera();           // Stop camera on pause
        }
    }
}

activity_scan.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ScanActivity">
<FrameLayout
    android:id="@+id/scan_preview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>
</android.support.constraint.ConstraintLayout>

Triggering the scan activity

  startActivity(new Intent(this,ScanActivity.class));

Do more

For a deeper dive you can check this github repo https://github.com/dm77/barcodescanner

Next

The next article will be about how to create QR-codes in your android application to open the possibility of data sharing between multiple devices and make use of the scanner I’ve just presented.

Update: you can find how to create Qr-codes in android here Creating QR-codes in Android


About the author

noras

"Senior Software Engineer. MSc in Computer systems and Networks with big interest in security. Loves to play with Android code and does security research for fun and profit. Speaks 4 languages and codes in much more."

Related articles

Tags: #Android #Java




Copyright © 2019 - nindoda.com