android-studio
  1. android-studio-qr-bar-code-scanner

Android Studio QR/Bar Code Scanner

Syntax

To use the QR/Bar Code Scanner feature in Android Studio, you need to add the following dependency in your app's build.gradle file:

dependencies {
    implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}

Example

Here's an example code snippet that demonstrates how to use the QR/Bar Code Scanner in Android Studio:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CAMERA_PERMISSION = 100;

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

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        } else {
            scanCode();
        }
    }

    private void scanCode() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
        integrator.setPrompt("Scan a QR Code");
        integrator.setCameraId(0);
        integrator.setBeepEnabled(true);
        integrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);

        if (result != null) {
            if (result.getContents() == null) {
                Log.d("MainActivity", "Cancelled scan");
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Log.d("MainActivity", "Scanned");
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        }
    }

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

        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                scanCode();
            } else {
                Toast.makeText(this, "Camera permission required", Toast.LENGTH_LONG).show();
            }
        }
    }
}

Output

When you run the above example code, it will open the camera and scan for QR codes. Once a code is detected, it will show a toast message with the scanned content.

Explanation

In the above example code, we have used the "zxing-android-embedded" dependency to implement the QR/Bar Code Scanner functionality. The main logic is written inside the scanCode() method, which initializes the scanner with the required settings.

The onActivityResult() method is called when the scanning process is completed. It parses the scan result and shows a toast message with the content.

The onRequestPermissionsResult() method is called when the user grants permission for the camera. If the permission is granted, the scanCode() method is called to start the scanning process.

Use

The QR/Bar Code Scanner feature can be used in many applications, such as payment apps, ticketing apps, etc. It is especially useful when you need to scan a code and get the data quickly without typing.

Important Points

  • Make sure to request camera permission before starting the scanner
  • Set the desired barcode formats and camera ID before initiating the scan
  • Parse the scan result in the onActivityResult() method and handle accordingly

Summary

In this article, we have learned how to implement the QR/Bar Code Scanner feature in Android Studio. We have seen the example code and explained its functionality. This feature can be very useful in many types of applications and can significantly improve the user experience.

Published on: