Android Barcode Scanner with Dynamsoft Mobile Barcode SDK

Datetime:2016-08-22 23:23:59          Topic: Andrew Development           Share

Dynamsoft aims to make barcode SDK available for all mainstream platforms, including Windows , Linux , macOS , iOS, and Android . There are many developers devoted to developing mobile barcode scanner app for iOS and Android platforms. To expedite the developing work, some of them may rely on a powerful detection and recognition libraries, like Dynamsoft mobile barcode SDK. In this post, let’s take a glimpse of how to use  barcode SDK for Android to build Android barcode scanner with a few lines of code.

Android Barcode SDK

Download

Android Barcode Scanner

Open Android Studio and select File > New > New Project the menu option to create a new project with the template Empty Activity .

Import the AAR package DynamsoftBarcodeReader.aar , which is included in SDK, as a module:

Press F4 to open Project Structure and then add the dependent module:

Now, you can use Dynamsoft Barcode Reader in your Android project.

UI design

The app mainly consists of an About dialog, the Camera Preview layout, and a Setting view.

About Dynamsoft Android Barcode SDK:

Camera preview for scanning barcode:

Optional barcode types:

Configuration

Edit AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dynamsoft.demo.dynamsoftbarcodereaderdemo">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:screenOrientation="portrait"
            android:theme="@style/Theme.AppCompat.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BarcodeTypeActivity"></activity>
    </application>
</manifest>

To invoke camera API, you need to declare the permission and feature:

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

The main Activity has no action bar, therefore we can choose the following theme style:

android:theme="@style/Theme.AppCompat.NoActionBar"

The BarcodeTypeActivity is for selecting barcode types:

<activity android:name=".BarcodeTypeActivity"></activity>

Source Code Anatomy

Since from Android 6.0 (API level 23), you need to request permissions while the app is running. Here is the code for requesting the camera permission:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) !=  PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
            }
            else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAMERA);
            }
}

Initialize Dynamsoft Barcode Reader with a valid license:

BarcodeReader  mBarcodeReader = new BarcodeReader("<license>");

Open a camera and set its focus continuous:

private void openCamera()
{
        new Thread(new Runnable() {
            @Override
            public void run() {
                mCamera = getCameraInstance();

                if (mCamera != null) {
                    mCamera.setDisplayOrientation(90);
                    Camera.Parameters cameraParameters = mCamera.getParameters();
                    cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                    mCamera.setParameters(cameraParameters);
                }

                Message message = handler.obtainMessage(OPEN_CAMERA, 1);
                message.sendToTarget();
            }

        }).start();
}

Set preview callback and start the preview:

if (mCamera != null) {
                        mCamera.setPreviewCallback(MainActivity.this);
                        mSurfaceHolder.setCamera(mCamera);
                        Camera.Parameters p = mCamera.getParameters();
                        if (mFlashTextView.getText().equals("Flash on"))
                            p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);

                        mCamera.setParameters(p);
                        mSurfaceHolder.startPreview();
}

Switch the flash:

public void setFlash(View v) {

        if (mCamera != null) {
            Camera.Parameters p = mCamera.getParameters();
            String flashMode = p.getFlashMode();
            if (flashMode.equals(Camera.Parameters.FLASH_MODE_OFF)) {
                 p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                 mFlashImageView.setImageResource(R.mipmap.flash_on);
                 mFlashTextView.setText("Flash on");
            }
            else {
                 p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                 mFlashImageView.setImageResource(R.mipmap.flash_off);
                 mFlashTextView.setText("Flash off");
             }

            mCamera.setParameters(p);
            mCamera.startPreview();
        }
}

Implement Camera.PreviewCallback and read barcode in function onPreviewFrame :

@Override
public void onPreviewFrame(byte[] data, Camera camera) {

        if (mFinished && !mIsDialogShowing) {
            mFinished = false;

            Camera.Size size = camera.getParameters().getPreviewSize();

            mImageHeight = size.height;

            mBarcodeReader.readSingleAsync(data, size.width, size.height, mBarcodeFormat, new FinishCallback() {

                @Override

                public void onFinish(ReadResult readResult) {
                    Message message = handler.obtainMessage(READ_RESULT, readResult);
                    message.sendToTarget();
                }
            });
        }
}

Show About dialog:

public void showAbout(View v) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("About");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mIsDialogShowing = false;
            }
        });

        Spanned spanned = Html.fromHtml("<font color='#FF8F0D'><a href=\"http://www.dynamsoft.com\">Download Free Trial here</a></font><br/>");
        builder.setMessage(spanned);
        builder.create(R.layout.about, R.style.AboutDialog).show();
        mIsDialogShowing = true;
}

Start BarcodeTypeActivity to select barcode types:

Intent intent = new Intent(this, BarcodeTypeActivity.class);
intent.putExtra(BarcodeTypeActivity.BarcodeFormat, mBarcodeFormat);
startActivityForResult(intent, RC_BARCODE_TYPE);

Video

App Download

Install the app from Google Play .

Source Code

https://github.com/dynamsoft-dbr/Android-barcode-scanner





About List