How to implement a simple barcode scan application on Android

Barcode scanning, especially QR code scans, are now widely used in various applications. This includes advertisements, newspapers, social networks, signage, and so on. The growth of QR codes is in large part due to the smartphone market’s booming growth. As a result, scanning technology tends to be more and more useful and important to businesses and consumers. In this article, we will take a glimpse on how to implement a simple barcode scan application on the Android platform.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Basic Steps to Implement an Android Barcode Application

The implementation of a barcode scan application mainly consists of two parts: invoking an Android camera and leveraging the ZXing barcode library, respectively.

Step 1: Get the image data of a barcode from an Android camera.

Step 2: Transfer the barcode image data into ZXing for barcode recognition.

Both Android and ZXing provide detailed APIs and sample code.

Avoiding common mistakes in using the Android camera

1. It’s important to make sure you enable proper permissions for the camera, to avoid user problems. To do this, set camera access permission in AndroidManifest.xml. Otherwise, users will get a permission error when they launch your application. Here’s the code to do it:

      <uses-permission android:name="android.permission.CAMERA" />
      <uses-feature android:name="android.hardware.camera" />
      <uses-feature android:name="android.hardware.camera.autofocus" />
2. Do not 100% trust your eyes to instantiate a Camera Object directly. The following code may help you distinguish which camera you want to use.
int frontId = 0, backId = 0;
CameraInfo cameraInfo = new CameraInfo();
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT) {
            	frontId = i;
            }
            else if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                backId = i 
            } 
}
Camera mCamera = Camera.open(backId);

3. To set camera parameters, it’s recommended you log out and check all your camera parameters in advance. This is a handy way to know your hardware.

Log.i("parameters", mCamera.getParameters().flatten());

Note: some of the camera parameters may not work on different devices, especially for some third-party API providers, such as Samsung. If you set some parameters that work for Google’s device, there is no guarantee that they definitely work for Samsung’s.

4. Now, implement the relevant callback function to obtain the image data.

private Camera.PreviewCallback mPreviewCallback = new Camera.PreviewCallback() {
		@Override
		public void onPreviewFrame(byte[] data, Camera camera) {		
			// TODO Auto-generated method stub
		}
	};

How to use ZXing

1. Install SVN software on your Windows/Mac. For windows users, TortoiseSVN is a good choice. It is free and comes with a GUI. Versions is an option for Mac users. It has a beautiful GUI, but it costs $59.

2. Create a directory named “ZXing”, and type in “svn checkout http://zxing.googlecode.com/svn/trunk/” to download ZXing source code.

D:\zxing>svn checkout http://zxing.googlecode.com/svn/trunk/

3. Import ZXing to your camera project, and transfer the data to ZXing for barcode recognition.

android_barcode

private Camera.PreviewCallback mPreviewCallback = new PreviewCallback() {

        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {
            // TODO Auto-generated method stub

        	if (mDialog.isShowing())
        		return;

        	LuminanceSource source = new PlanarYUVLuminanceSource(data, mWidth, mHeight, mLeft, mTop, mAreaWidth, mAreaHeight, false);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
              source));
            Result result;

            try {
				result = mMultiFormatReader.decode(bitmap, null);
				if (result != null) {
					mDialog.setTitle("Result");
					mDialog.setMessage(result.getText());
					mDialog.show();
				}
			} catch (NotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
    };

Source Code

https://github.com/yushulx/Android-Barcode-Reader

  • Asshameofthiscode

    The Code is full of errors. Do I have to fix them all before trying it? Might as well right my own code. MultiformatReader missing. mPreviewCallback error it’s full of errors Wow. I downloaded from git do you have a stable version?

  • http://www.dynamsoft.com Desmond Shaw

    What is your Android version? 4.x, 5.x or 6.x? Does other camera-related app work well on your device? Probably you need to add some new permissions or update Camera invoking APIs for your device.

  • Siti Fatimah

    Hi. Thank you very much for the tutorial. But in the end i have problem when clicking scan button. it says…can u help me?

    “Sorry the android camera encountered a problem. you may need to restart the device.”

  • http://www.dynamsoft.com/ Xiao Ling

    You can read the article – how to migrate projects to android studio. http://www.codepool.biz/migrate-projects-to-android-studio.html

  • gus gustafson

    Okay, I downloaded the git repository. But I am new to Android so I do not know how to open the barcode scanner in Android Studio.

    Any help appreciated.

  • http://www.dynamsoft.com/ Xiao Ling

    Thanks! You are right! It should be backId = i. As the blog manager, I’ve notified my colleague and corrected the error.

  • gus gustafson

    In “Avoiding common mistakes in using the Android camera”, paragraph 2, in the code fragment, at line 18, the statement

    backed = i

    should probably read

    backId = i

  • http://www.dynamsoft.com Desmond Shaw

    Hi, I only tested the QR code. If your app crashed at ZXing library, I suggest you can visit the ZXing official website to check what formats are supported.

  • shivi

    hello
    thank you for your code and representation about the barcode reader and yet it gives the desired result but it still throws runtime exception sometimes as its stuck in numberformat barcode so is that it does not support numberformat bar code?

  • shivi

    he

  • http://www.dynamsoft.com Desmond Shaw

    Have you debugged the code? What’s the return value from the ZXing detection method?

  • AndroidGeek

    Have download your code and tried but its not able to scan the barcode.Could you please help me how to scan it ?

    Thanks

  • http://www.kevingao.net/ Kevin(ex-employee)

    Yes. The app you mentioned is implemented by ZXing team.

  • cindy

    i ever used one barcode scanner for android

    https://play.google.com/store/apps/details?id=com.google.zxing.client.android&hl=en

    is it the same with that one you said ?