PDF417 / pdf417-android

PDF417 and QR code scanning SDK for Android
www.pdf417.mobi
Apache License 2.0
182 stars 80 forks source link

PDF417.mobi SDK for Android

Build Status

PDF417.mobi SDK for Android enables you to perform scans of various barcodes in your app. You can integrate the SDK into your app simply by following the instructions below and your app will be able to scan and process data from the following barcode standards:

Using PDF417.mobi in your app requires a valid license key. You can obtain a trial license key by registering to Microblink dashboard. After registering, you will be able to generate a license key for your app. The license key is bound to package name of your app, so please make sure you enter the correct package name when asked.

For more information on how to integrate PDF417.mobi SDK into your app read the instructions below. Make sure you read the latest Release notes for most recent changes and improvements.

Table of contents

Android PDF417.mobi integration instructions

The package contains Android Archive (AAR) that contains everything you need to use the PDF417.mobi library. Besides AAR, the package also contains a sample project that contains following modules:

The source code of all sample apps is given to you to show you how to perform integration of PDF417.mobi SDK into your app. This source code and all of the resources are at your disposal. You can use these sample apps as a basis for creating your own app, or you can copy/paste the code and/or resources from sample apps into your app and use them as you wish without even asking for permission.

PDF417.mobi is supported in Android SDK version 16 (Android 4.1) or later.

The library contains one activity: BarcodeScanActivity. It is responsible for camera control and recognition. You can also create your own scanning UI - you just need to embed RecognizerRunnerView into your activity and pass activity's lifecycle events to it and it will control the camera and recognition process. For more information, see Embedding RecognizerRunnerView into custom scan activity.

Quick Start

Quick start with the sample app

  1. Open Android Studio.
  2. In Quick Start dialog choose Import project (Eclipse ADT, Gradle, etc.).
  3. In File dialog select Pdf417MobiDemo folder.
  4. Wait for the project to load. If Android studio asks you to reload project on startup, select Yes.

SDK integration

Adding PDF417.mobi dependency

In your build.gradle, add PDF417.mobi maven repository to repositories list

repositories {
    maven { url 'https://maven.microblink.com' }
}

Add PDF417.mobi as a dependency and make sure transitive is set to true

dependencies {
    implementation('com.microblink:pdf417.mobi:8.0.0@aar') {
        transitive = true
    }
}

Importing Javadoc

Android studio 3.0 should automatically import javadoc from maven dependency. If that doesn't happen, you can do that manually by following these steps:

  1. In Android Studio project sidebar, ensure project view is enabled
  2. Expand External Libraries entry (usually this is the last entry in project view)
  3. Locate pdf417.mobi-8.0.0 entry, right click on it and select Library Properties...
  4. A Library Properties pop-up window will appear
  5. Click the second + button in bottom left corner of the window (the one that contains + with little globe)
  6. Window for defining documentation URL will appear
  7. Enter following address: https://pdf417.github.io/pdf417-android/
  8. Click OK

Performing your first scan

  1. First you'll need to create an account at Microblink dashboard where you can generate a free trial license key for your app. License is bound to package name of your app, so please make sure you enter the correct package name when asked.

    Download your licence file and put it in your application's assets folder. Make sure to set the license key before using any other classes from the SDK, otherwise you will get a runtime exception.

    We recommend that you extend Android Application class and set the license in [onCreate callback](https://developer.android.com/reference/android/app/Application.html#onCreate()) like this:

    public class MyApplication extends Application {
        @Override
        public void onCreate() {
            MicroblinkSDK.setLicenseFile("path/to/license/file/within/assets/dir", this);
        }
    }
  2. In your main activity, create recognizer objects that will perform image recognition, configure them and put them into RecognizerBundle object. You can see more information about available recognizers and RecognizerBundle here.

    For example, to scan PDF417 2D barcode, configure your recognizer like this:

    public class MyActivity extends Activity {
        private Pdf417Recognizer mRecognizer;
        private RecognizerBundle mRecognizerBundle;
    
        @Override
        protected void onCreate(Bundle bundle) {
            super.onCreate(bundle);
    
            // setup views, as you would normally do in onCreate callback
    
            // create Pdf417Recognizer
            mRecognizer = new Pdf417Recognizer();
    
            // bundle recognizers into RecognizerBundle
            mRecognizerBundle = new RecognizerBundle(mRecognizer);
        }
    }
  3. Start recognition process by creating BarcodeUISettings and calling ActivityRunner.startActivityForResult:

    // method within MyActivity from previous step
    public void startScanning() {
        // Settings for BarcodeScanActivity
        BarcodeUISettings settings = new BarcodeUISettings(mRecognizerBundle);
    
        // tweak settings as you wish
    
        // Start activity
        ActivityRunner.startActivityForResult(this, MY_REQUEST_CODE, settings);
    }
  4. onActivityResult will be called in your activity after scanning is finished, here you can get the scanning results.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == MY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // load the data into all recognizers bundled within your RecognizerBundle
                mRecognizerBundle.loadFromIntent(data);
    
                // now every recognizer object that was bundled within RecognizerBundle
                // has been updated with results obtained during scanning session
    
                // you can get the result by invoking getResult on recognizer
                Pdf417Recognizer.Result result = mRecognizer.getResult();
                if (result.getResultState() == Recognizer.Result.State.Valid) {
                    // result is valid, you can use it however you wish
                }
            }
        }
    }

    For more information about available recognizers and RecognizerBundle, see RecognizerBundle and available recognizers.

Device requirements

Android Version

PDF417.mobi requires Android 4.1 (API level 16) or newer. For best performance and compatibility, we recommend at least Android 5.0.

Camera

Camera video preview resolution also matters. In order to perform successful scans, camera preview resolution must be at least 480p. Note that camera preview resolution is not the same as video recording resolution. For example, Sony Xperia Go supports 720p video recording but preview resolution is only 320p - PDF417.mobi won't work on that device.

Processor architecture

PDF417.mobi is distributed with ARMv7, ARM64, x86 and x86_64 native library binaries.

PDF417.mobi is a native library, written in C++ and available for multiple platforms. Because of this, PDF417.mobi cannot work on devices with obscure hardware architectures. We have compiled PDF417.mobi native code only for the most popular Android ABIs.

Even before setting the license key, you should check if the PDF417.mobi is supported on the current device (see next section: Compatibility check). Attempting to call any method from the SDK that relies on native code, such as license check, on a device with unsupported CPU architecture will crash your app.

If you are combining PDF417.mobi library with other libraries that contain native code into your application, make sure you match the architectures of all native libraries.

For example, if a third party library has got only ARMv7 and ARM64 versions, you must use exactly ARMv7 and ARM64 versions of PDF417.mobi with that library, but not x86. Using these architectures will crash your app at the initialization step because JVM will try to load all its native dependencies in the same preferred architecture and will fail with UnsatisfiedLinkError.

For more information, see Processor architecture considerations section.

Compatibility check

Here's how you can check whether the PDF417.mobi is supported on the device:

// check if PDF417.mobi is supported on the device,
RecognizerCompatibilityStatus status = RecognizerCompatibility.getRecognizerCompatibilityStatus(this);
if (status == RecognizerCompatibilityStatus.RECOGNIZER_SUPPORTED) {
    Toast.makeText(this, "PDF417.mobi is supported!", Toast.LENGTH_LONG).show();
} else if (status == RecognizerCompatibilityStatus.NO_CAMERA) {
    Toast.makeText(this, "PDF417.mobi is supported only via Direct API!", Toast.LENGTH_LONG).show();
} else if (status == RecognizerCompatibilityStatus.PROCESSOR_ARCHITECTURE_NOT_SUPPORTED) {
    Toast.makeText(this, "PDF417.mobi is not supported on current processor architecture!", Toast.LENGTH_LONG).show();
} else {
    Toast.makeText(this, "PDF417.mobi is not supported! Reason: " + status.name(), Toast.LENGTH_LONG).show();
}

Some recognizers require camera with autofocus. If you try using them on a device that doesn't support autofocus, you will get an error. To prevent that, you can check whether a recognizer requires autofocus by calling its requiresAutofocus method.

If you already have an array of recognizers, you can easily filter out recognizers that require autofocus from array using the following code snippet:

Recognizer[] recArray = ...;
if(!RecognizerCompatibility.cameraHasAutofocus(CameraType.CAMERA_BACKFACE, this)) {
    recArray = RecognizerUtils.filterOutRecognizersThatRequireAutofocus(recArray);
}

PDF417.mobi SDK integration levels

You can integrate PDF417.mobi into your app in four different ways, depending on your use case and customisation needs:

  1. Built-in activities (UISettings) - SDK handles everything and you just need to start our built-in activity and handle result, customisation options are limited
  2. Built-in fragment (RecognizerRunnerFragment) - reuse scanning UX from our built-in activities in your own activity
  3. Custom UX (RecognizerRunnerView) - SDK handles camera management while you have to implement completely custom scanning UX
  4. Direct Api (RecognizerRunner) - SKD only handles recognition while you have to provide it with the images, either from camera or from a file

Built-in activities (UISettings)

UISettings is a class that contains all the necessary settings for SDK's built-in scan activities. It configures scanning activity behaviour, strings, icons and other UI elements. As shown in the first scan example, you should use ActivityRunner to start the scan activity configured by UISettings.

We provide multiple UISettings classes specialised for different scanning scenarios. Each UISettings object has properties which can be changed via appropriate setter methods. For example, you can customise camera settings with setCameraSettings metod.

All available UISettings classes are listed here.

Built-in fragment (RecognizerRunnerFragment)

If you want to reuse our built-in activity UX inside your own activity, use RecognizerRunnerFragment. Activity that will host RecognizerRunnerFragment must implement ScanningOverlayBinder interface. Attempting to add RecognizerRunnerFragment to activity that does not implement that interface will result in ClassCastException.

The ScanningOverlayBinder is responsible for returning non-null implementation of ScanningOverlay - class that will manage UI on top of RecognizerRunnerFragment. It is not recommended to create your own ScanningOverlay implementation, use one of our implementations listed here instead.

Here is the minimum example for activity that hosts the RecognizerRunnerFragment:

public class MyActivity extends AppCompatActivity implements RecognizerRunnerFragment.ScanningOverlayBinder {
    private Pdf417Recognizer mRecognizer;
    private RecognizerBundle mRecognizerBundle;
    private BarcodeOverlayController mScanOverlay;
    private RecognizerRunnerFragment mRecognizerRunnerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate();
        setContentView(R.layout.activity_my_activity);
        mScanOverlay = createOverlay();
        if (null == savedInstanceState) {
            // create fragment transaction to replace R.id.recognizer_runner_view_container with RecognizerRunnerFragment
            mRecognizerRunnerFragment = new RecognizerRunnerFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.recognizer_runner_view_container, mRecognizerRunnerFragment);
            fragmentTransaction.commit();
        } else {
            // obtain reference to fragment restored by Android within super.onCreate() call
            mRecognizerRunnerFragment = (RecognizerRunnerFragment) getSupportFragmentManager().findFragmentById(R.id.recognizer_runner_view_container);
        }
    }

    @Override
    @NonNull
    public ScanningOverlay getScanningOverlay() {
        return mScanOverlay;
    }

    private BarcodeOverlayController createOverlay() {
        // create Pdf417Recognizer
        mRecognizer = new Pdf417Recognizer();

        // bundle recognizers into RecognizerBundle
        mRecognizerBundle = new RecognizerBundle(mRecognizer);

        BarcodeUISettings settings = new BarcodeUISettings(mRecognizerBundle);

        return settings.createOverlayController(this, mScanResultListener);
    }

    private final ScanResultListener mScanResultListener = new ScanResultListener() {
        @Override
        public void onScanningDone(@NonNull RecognitionSuccessType recognitionSuccessType) {
            // pause scanning to prevent new results while fragment is being removed
            mRecognizerRunnerFragment.getRecognizerRunnerView().pauseScanning();

            // now you can remove the RecognizerRunnerFragment with new fragment transaction
            // and use result within mRecognizer safely without the need for making a copy of it

            // if not paused, as soon as this method ends, RecognizerRunnerFragments continues
            // scanning. Note that this can happen even if you created fragment transaction for
            // removal of RecognizerRunnerFragment - in the time between end of this method
            // and beginning of execution of the transaction. So to ensure result within mRecognizer
            // does not get mutated, ensure calling pauseScanning() as shown above.
        }
        @Override
        public void onUnrecoverableError(@NonNull Throwable throwable) {
        }
    };

}

Please refer to sample apps provided with the SDK for more detailed example and make sure your host activity's orientation is set to nosensor or has configuration changing enabled (i.e. is not restarted when configuration change happens). For more information, check scan orientation section.

Custom UX with RecognizerRunnerView

This section discusses how to embed RecognizerRunnerView into your scan activity and perform scan.

  1. First make sure that RecognizerRunnerView is a member field in your activity. This is required because you will need to pass all activity's lifecycle events to RecognizerRunnerView.
  2. It is recommended to keep your scan activity in one orientation, such as portrait or landscape. Setting sensor as scan activity's orientation will trigger full restart of activity whenever device orientation changes. This will provide very poor user experience because both camera and PDF417.mobi native library will have to be restarted every time. There are measures against this behaviour that are discussed later.
  3. In your activity's onCreate method, create a new RecognizerRunnerView, set RecognizerBundle containing recognizers that will be used by the view, define CameraEventsListener that will handle mandatory camera events, define ScanResultListener that will receive call when recognition has been completed and then call its create method. After that, add your views that should be layouted on top of camera view.
  4. Pass in your activity's lifecycle using setLifecycle method to enable automatic handling of lifeceycle events.

Here is the minimum example of integration of RecognizerRunnerView as the only view in your activity:

public class MyScanActivity extends AppCompatActivity {
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 42;
    private RecognizerRunnerView mRecognizerRunnerView;
    private Pdf417Recognizer mRecognizer;
    private RecognizerBundle mRecognizerBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // create Pdf417Recognizer
        mRecognizer = new Pdf417Recognizer();

        // bundle recognizers into RecognizerBundle
        mRecognizerBundle = new RecognizerBundle(mRecognizer);
        // create RecognizerRunnerView
        mRecognizerRunnerView = new RecognizerRunnerView(this);

        // set lifecycle to automatically call recognizer runner view lifecycle methods
        mRecognizerRunnerView.setLifecycle(getLifecycle());

        // associate RecognizerBundle with RecognizerRunnerView
        mRecognizerRunnerView.setRecognizerBundle(mRecognizerBundle);

        // scan result listener will be notified when scanning is complete
        mRecognizerRunnerView.setScanResultListener(mScanResultListener);
        // camera events listener will be notified about camera lifecycle and errors
        mRecognizerRunnerView.setCameraEventsListener(mCameraEventsListener);

        setContentView(mRecognizerRunnerView);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // changeConfiguration is not handled by lifecycle events so call it manually
        mRecognizerRunnerView.changeConfiguration(newConfig);
    }

    private final CameraEventsListener mCameraEventsListener = new CameraEventsListener() {
        @Override
        public void onCameraPreviewStarted() {
            // this method is from CameraEventsListener and will be called when camera preview starts
        }

        @Override
        public void onCameraPreviewStopped() {
            // this method is from CameraEventsListener and will be called when camera preview stops
        }

        @Override
        public void onError(Throwable exc) {
            /**
             * This method is from CameraEventsListener and will be called when
             * opening of camera resulted in exception or recognition process
             * encountered an error. The error details will be given in exc
             * parameter.
             */
        }

        @Override
        @TargetApi(23)
        public void onCameraPermissionDenied() {
            /**
             * Called in Android 6.0 and newer if camera permission is not given
             * by user. You should request permission from user to access camera.
             */
            requestPermissions(new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA_REQUEST_CODE);
            /**
             * Please note that user might have not given permission to use
             * camera. In that case, you have to explain to user that without
             * camera permissions scanning will not work.
             * For more information about requesting permissions at runtime, check
             * this article:
             * https://developer.android.com/training/permissions/requesting.html
             */
        }

        @Override
        public void onAutofocusFailed() {
            /**
             * This method is from CameraEventsListener will be called when camera focusing has failed.
             * Camera manager usually tries different focusing strategies and this method is called when all
             * those strategies fail to indicate that either object on which camera is being focused is too
             * close or ambient light conditions are poor.
             */
        }

        @Override
        public void onAutofocusStarted(Rect[] areas) {
            /**
             * This method is from CameraEventsListener and will be called when camera focusing has started.
             * You can utilize this method to draw focusing animation on UI.
             * Areas parameter is array of rectangles where focus is being measured.
             * It can be null on devices that do not support fine-grained camera control.
             */
        }

        @Override
        public void onAutofocusStopped(Rect[] areas) {
            /**
             * This method is from CameraEventsListener and will be called when camera focusing has stopped.
             * You can utilize this method to remove focusing animation on UI.
             * Areas parameter is array of rectangles where focus is being measured.
             * It can be null on devices that do not support fine-grained camera control.
             */
        }
    };

    private final ScanResultListener mScanResultListener = new ScanResultListener() {
        @Override
        public void onScanningDone(@NonNull RecognitionSuccessType recognitionSuccessType) {
            // this method is from ScanResultListener and will be called when scanning completes
            // you can obtain scanning result by calling getResult on each
            // recognizer that you bundled into RecognizerBundle.
            // for example:

            Pdf417Recognizer.Result result = mRecognizer.getResult();
            if (result.getResultState() == Recognizer.Result.State.Valid) {
                // result is valid, you can use it however you wish
            }

            // Note that mRecognizer is stateful object and that as soon as
            // scanning either resumes or its state is reset
            // the result object within mRecognizer will be changed. If you
            // need to create a immutable copy of the result, you can do that
            // by calling clone() on it, for example:

            Pdf417Recognizer.Result immutableCopy = result.clone();

            // After this method ends, scanning will be resumed and recognition
            // state will be retained. If you want to prevent that, then
            // you should call:
            mRecognizerRunnerView.resetRecognitionState();
            // Note that reseting recognition state will clear internal result
            // objects of all recognizers that are bundled in RecognizerBundle
            // associated with RecognizerRunnerView.

            // If you want to pause scanning to prevent receiving recognition
            // results or mutating result, you should call:
            mRecognizerRunnerView.pauseScanning();
            // if scanning is paused at the end of this method, it is guaranteed
            // that result within mRecognizer will not be mutated, therefore you
            // can avoid creating a copy as described above

            // After scanning is paused, you will have to resume it with:
            mRecognizerRunnerView.resumeScanning(true);
            // boolean in resumeScanning method indicates whether recognition
            // state should be automatically reset when resuming scanning - this
            // includes clearing result of mRecognizer
        }
    };  

}

Scan activity's orientation

If activity's screenOrientation property in AndroidManifest.xml is set to sensor, fullSensor or similar, activity will be restarted every time device changes orientation from portrait to landscape and vice versa. While restarting activity, its onPause, onStop and onDestroy methods will be called and then new activity will be created anew. This is a potential problem for scan activity because in its lifecycle it controls both camera and native library - restarting the activity will trigger both restart of the camera and native library. This is a problem because changing orientation from landscape to portrait and vice versa will be very slow, thus degrading a user experience. We do not recommend such setting.

For that matter, we recommend setting your scan activity to either portrait or landscape mode and handle device orientation changes manually. To help you with this, RecognizerRunnerView supports adding child views to it that will be rotated regardless of activity's screenOrientation. You add a view you wish to be rotated (such as view that contains buttons, status messages, etc.) to RecognizerRunnerView with addChildView method. The second parameter of the method is a boolean that defines whether the view you are adding will be rotated with device. To define allowed orientations, implement OrientationAllowedListener interface and add it to RecognizerRunnerView with method setOrientationAllowedListener. This is the recommended way of rotating camera overlay.

However, if you really want to set screenOrientation property to sensor or similar and want Android to handle orientation changes of your scan activity, then we recommend to set configChanges property of your activity to orientation|screenSize. This will tell Android not to restart your activity when device orientation changes. Instead, activity's onConfigurationChanged method will be called so that activity can be notified of the configuration change. In your implementation of this method, you should call changeConfiguration method of RecognizerView so it can adapt its camera surface and child views to new configuration.

Direct API

This section will describe how to use direct API to recognize android Bitmaps and java Strings without the need for camera. You can use direct API anywhere from your application, not just from activities.

Image recognition performance highly depends on the quality of the input images. When our camera management is used (scanning from a camera), we do our best to get camera frames with the best possible quality for the used device. On the other hand, when Direct API is used, you need to provide high-quality images without blur and glare for successful recognition.

Using Direct API for recognition of Android Bitmaps and custom camera frames

  1. First, you need to obtain reference to RecognizerRunner singleton using getSingletonInstance.
  2. Second, you need to initialize the recognizer runner.
  3. After initialization, you can use singleton to process Android bitmaps or images that are built from custom camera frames. Currently, it is not possible to process multiple images in parallel.
  4. When you want to delete all cached data from multiple recognitions, for example when you want to scan other document and/or restart scanning, you need to reset the recognition state.
  5. Do not forget to terminate the recognizer runner singleton after usage (it is a shared resource).

Here is the minimum example of usage of direct API for recognizing android Bitmap:

public class DirectAPIActivity extends Activity {
    private RecognizerRunner mRecognizerRunner;
    private Pdf417Recognizer mRecognizer;
    private RecognizerBundle mRecognizerBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate();
        // initialize your activity here
        // create Pdf417Recognizer
        mRecognizer = new Pdf417Recognizer();

        // bundle recognizers into RecognizerBundle
        mRecognizerBundle = new RecognizerBundle(mRecognizer);

        try {
            mRecognizerRunner = RecognizerRunner.getSingletonInstance();
        } catch (FeatureNotSupportedException e) {
            Toast.makeText(this, "Feature not supported! Reason: " + e.getReason().getDescription(), Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        mRecognizerRunner.initialize(this, mRecognizerBundle, new DirectApiErrorListener() {
            @Override
            public void onRecognizerError(Throwable t) {
                Toast.makeText(DirectAPIActivity.this, "There was an error in initialization of Recognizer: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // start recognition
        Bitmap bitmap = BitmapFactory.decodeFile("/path/to/some/file.jpg");
        mRecognizerRunner.recognizeBitmap(bitmap, Orientation.ORIENTATION_LANDSCAPE_RIGHT, mScanResultListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRecognizerRunner.terminate();
    }

    private final ScanResultListener mScanResultListener = new ScanResultListener() {
        @Override
        public void onScanningDone(@NonNull RecognitionSuccessType recognitionSuccessType) {
            // this method is from ScanResultListener and will be called
            // when scanning completes
            // you can obtain scanning result by calling getResult on each
            // recognizer that you bundled into RecognizerBundle.
            // for example:

            Pdf417Recognizer.Result result = mRecognizer.getResult();
            if (result.getResultState() == Recognizer.Result.State.Valid) {
                // result is valid, you can use it however you wish
            }
        }
    };

}

ScanResultListener.onScanningDone method is called for each input image that you send to the recognition. You can call RecognizerRunner.recognize* method multiple times with different images of the same document for better reading accuracy until you get a successful result in the listener's onScanningDone method. This is useful when you are using your own or third-party camera management.

Using Direct API for String recognition (parsing)

Some recognizers support recognition from String. They can be used through Direct API to parse given String and return data just like when they are used on an input image. When recognition is performed on String, there is no need for the OCR. Input String is used in the same way as the OCR output is used when image is being recognized.

Recognition from String can be performed in the same way as recognition from image, described in the previous section.

The only difference is that one of the RecognizerRunner singleton methods for recognition from string should be called:

Understanding DirectAPI's state machine

Direct API's RecognizerRunner singleton is a state machine that can be in one of 3 states: OFFLINE, READY and WORKING.

Using Direct API while RecognizerRunnerView is active

Both RecognizerRunnerView and RecognizerRunner use the same internal singleton that manages native code. This singleton handles initialization and termination of native library and propagating recognizers to native library. It is possible to use RecognizerRunnerView and RecognizerRunner together, as internal singleton will make sure correct synchronization and correct recognition settings are used. If you run into problems while using RecognizerRunner in combination with RecognizerRunnerView, let us know!

Available activities and overlays

BarcodeUISettings

BarcodeUISettings launches activity that uses BasicOverlayController with UI best suited for performing scanning of various barcodes.

Translation and localization

Strings used within built-in activities and overlays can be localized to any language. If you are using RecognizerRunnerView (see this chapter for more information) in your custom scan activity or fragment, you should handle localization as in any other Android app. RecognizerRunnerView does not use strings nor drawables, it only uses assets from assets/microblink folder. Those assets must not be touched as they are required for recognition to work correctly.

However, if you use our built-in activities or overlays, they will use resources packed within LibPdf417Mobi.aar to display strings and images on top of the camera view. We have already prepared strings for several languages which you can use out of the box. You can also modify those strings, or you can add your own language.

To use a language, you have to enable it from the code:

Adding new language

PDF417.mobi can easily be translated to other languages. The res folder in LibPdf417Mobi.aar archive has folder values which contains strings.xml - this file contains english strings. In order to make e.g. croatian translation, create a folder values-hr in your project and put the copy of strings.xml inside it (you might need to extract LibPdf417Mobi.aar archive to access those files). Then, open that file and translate the strings from English into Croatian.

Changing strings in the existing language

To modify an existing string, the best approach would be to:

  1. Choose a language you want to modify. For example Croatian ('hr').
  2. Find strings.xml in folder res/values-hr of the LibPdf417Mobi.aar archive
  3. Choose a string key which you want to change. For example: <string name="MBBack">Back</string>
  4. In your project create a file strings.xml in the folder res/values-hr, if it doesn't already exist
  5. Create an entry in the file with the value for the string which you want. For example: <string name="MBBack">Natrag</string>
  6. Repeat for all the string you wish to change

Handling processing events with RecognizerRunner and RecognizerRunnerView

Processing events, also known as Metadata callbacks are purely intended for giving processing feedback on UI or to capture some debug information during development of your app using PDF417.mobi SDK. For that reason, built-in activities and fragments handle those events internally. If you need to handle those events yourself, you need to use either RecognizerRunnerView or RecognizerRunner.

Callbacks for all events are bundled into the MetadataCallbacks object. Both RecognizerRunner and RecognizerRunnerView have methods which allow you to set all your callbacks.

We suggest that you check for more information about available callbacks and events to which you can handle in the javadoc for MetadataCallbacks class.

Please note that both those methods need to pass information about available callbacks to the native code and for efficiency reasons this is done at the time setMetadataCallbacks method is called and not every time when change occurs within the MetadataCallbacks object. This means that if you, for example, set QuadDetectionCallback to MetadataCallbacks after you already called setMetadataCallbacks method, the QuadDetectionCallback will not be registered with the native code and you will not receive its events.

Similarly, if you, for example, remove the QuadDetectionCallback from MetadataCallbacks object after you already called setMetadataCallbacks method, your app will crash with NullPointerException when our processing code attempts to invoke the method on removed callback (which is now set to null). We deliberately do not perform null check here because of two reasons:

Remember, each time you make some changes to MetadataCallbacks object, you need to apply those changes to to your RecognizerRunner or RecognizerRunnerView by calling its setMetadataCallbacks method.

Recognizer concept and RecognizerBundle

This section will first describe what is a Recognizer and how it should be used to perform recognition of the images, videos and camera stream. Next, we will describe how RecognizerBundle can be used to tweak the recognition procedure and to transfer Recognizer objects between activities.

RecognizerBundle is an object which wraps the Recognizers and defines settings about how recognition should be performed. Besides that, RecognizerBundle makes it possible to transfer Recognizer objects between different activities, which is required when using built-in activities to perform scanning, as described in first scan section, but is also handy when you need to pass Recognizer objects between your activities.

List of all available Recognizer objects, with a brief description of each Recognizer, its purpose and recommendations how it should be used to get best performance and user experience, can be found here .

The Recognizer concept

The Recognizer is the basic unit of processing within the PDF417.mobi SDK. Its main purpose is to process the image and extract meaningful information from it. As you will see later, the PDF417.mobi SDK has lots of different Recognizer objects that have various purposes.

Each Recognizer has a Result object, which contains the data that was extracted from the image. The Result object is a member of corresponding Recognizer object and its lifetime is bound to the lifetime of its parent Recognizer object. If you need your Result object to outlive its parent Recognizer object, you must make a copy of it by calling its method clone().

Every Recognizer is a stateful object, that can be in two states: idle state and working state. While in idle state, you can tweak Recognizer object's properties via its getters and setters. After you bundle it into a RecognizerBundle and use either RecognizerRunner or RecognizerRunnerView to run the processing with all Recognizer objects bundled within RecognizerBundle, it will change to working state where the Recognizer object is being used for processing. While being in working state, you cannot tweak Recognizer object's properties. If you need to, you have to create a copy of the Recognizer object by calling its clone(), then tweak that copy, bundle it into a new RecognizerBundle and use reconfigureRecognizers to ensure new bundle gets used on processing thread.

While Recognizer object works, it changes its internal state and its result. The Recognizer object's Result always starts in Empty state. When corresponding Recognizer object performs the recognition of given image, its Result can either stay in Empty state (in case Recognizer failed to perform recognition), move to Uncertain state (in case Recognizer performed the recognition, but not all mandatory information was extracted), move to StageValid state (in case Recognizer successfully scanned one part/side of the document and there are more fields to extract) or move to Valid state (in case Recognizer performed recognition and all mandatory information was successfully extracted from the image).

As soon as one Recognizer object's Result within RecognizerBundle given to RecognizerRunner or RecognizerRunnerView changes to Valid state, the onScanningDone callback will be invoked on same thread that performs the background processing and you will have the opportunity to inspect each of your Recognizer objects' Results to see which one has moved to Valid state.

As already stated in section about RecognizerRunnerView, as soon as onScanningDone method ends, the RecognizerRunnerView will continue processing new camera frames with same Recognizer objects, unless paused. Continuation of processing or resetting recognition will modify or reset all Recognizer objects's Results. When using built-in activities, as soon as onScanningDone is invoked, built-in activity pauses the RecognizerRunnerView and starts finishing the activity, while saving the RecognizerBundle with active Recognizer objects into Intent so they can be transferred back to the calling activities.

RecognizerBundle

The RecognizerBundle is wrapper around Recognizers objects that can be used to transfer Recognizer objects between activities and to give Recognizer objects to RecognizerRunner or RecognizerRunnerView for processing.

The RecognizerBundle is always constructed with array of Recognizer objects that need to be prepared for recognition (i.e. their properties must be tweaked already). The varargs constructor makes it easier to pass Recognizer objects to it, without the need of creating a temporary array.

The RecognizerBundle manages a chain of Recognizer objects within the recognition process. When a new image arrives, it is processed by the first Recognizer in chain, then by the second and so on, iterating until a Recognizer object's Result changes its state to Valid or all of the Recognizer objects in chain were invoked (none getting a Valid result state). If you want to invoke all Recognizers in the chain, regardless of whether some Recognizer object's Result in chain has changed its state to Valid or not, you can allow returning of multiple results on a single image.

You cannot change the order of the Recognizer objects within the chain - no matter the order in which you give Recognizer objects to RecognizerBundle, they are internally ordered in a way that provides best possible performance and accuracy. Also, in order for PDF417.mobi SDK to be able to order Recognizer objects in recognition chain in the best way possible, it is not allowed to have multiple instances of Recognizer objects of the same type within the chain. Attempting to do so will crash your application.

Passing Recognizer objects between activities

Besides managing the chain of Recognizer objects, RecognizerBundle also manages transferring bundled Recognizer objects between different activities within your app. Although each Recognizer object, and each its Result object implements Parcelable interface, it is not so straightforward to put those objects into Intent and pass them around between your activities and services for two main reasons:

Although the first problem can be easily worked around by making a copy of the Result and transfer it independently, the second problem is much tougher to cope with. This is where, RecognizerBundle's methods saveToIntent and loadFromIntent come to help, as they ensure the safe passing of Recognizer objects bundled within RecognizerBundle between activities according to policy defined with method setIntentDataTransferMode:

List of available recognizers

This section will give a list of all Recognizer objects that are available within PDF417.mobi SDK, their purpose and recommendations how they should be used to get best performance and user experience.

Frame Grabber Recognizer

The FrameGrabberRecognizer is the simplest recognizer in PDF417.mobi SDK, as it does not perform any processing on the given image, instead it just returns that image back to its FrameCallback. Its Result never changes state from Empty.

This recognizer is best for easy capturing of camera frames with RecognizerRunnerView. Note that Image sent to onFrameAvailable are temporary and their internal buffers all valid only until the onFrameAvailable method is executing - as soon as method ends, all internal buffers of Image object are disposed. If you need to store Image object for later use, you must create a copy of it by calling clone.

Also note that FrameCallback interface extends Parcelable interface, which means that when implementing FrameCallback interface, you must also implement Parcelable interface.

This is especially important if you plan to transfer FrameGrabberRecognizer between activities - in that case, keep in mind that the instance of your object may not be the same as the instance on which onFrameAvailable method gets called - the instance that receives onFrameAvailable calls is the one that is created within activity that is performing the scan.

Success Frame Grabber Recognizer

The SuccessFrameGrabberRecognizer is a special Recognizer that wraps some other Recognizer and impersonates it while processing the image. However, when the Recognizer being impersonated changes its Result into Valid state, the SuccessFrameGrabberRecognizer captures the image and saves it into its own Result object.

Since SuccessFrameGrabberRecognizer impersonates its slave Recognizer object, it is not possible to give both concrete Recognizer object and SuccessFrameGrabberRecognizer that wraps it to same RecognizerBundle - doing so will have the same result as if you have given two instances of same Recognizer type to the RecognizerBundle - it will crash your application.

This recognizer is best for use cases when you need to capture the exact image that was being processed by some other Recognizer object at the time its Result became Valid. When that happens, SuccessFrameGrabber's Result will also become Valid and will contain described image. That image can then be retrieved with getSuccessFrame() method.

PDF417 recognizer

The Pdf417Recognizer is recognizer specialised for scanning PDF417 2D barcodes. This recognizer can recognize only PDF417 2D barcodes - for recognition of other barcodes, please refer to BarcodeRecognizer.

This recognizer can be used in any context, but it works best with the BarcodeScanActivity, which has UI best suited for barcode scanning.

Barcode recognizer

The BarcodeRecognizer is recognizer specialised for scanning various types of barcodes. This recognizer should be your first choice when scanning barcodes as it supports lots of barcode symbologies, including the PDF417 2D barcodes, thus making PDF417 recognizer possibly redundant, which was kept only for its simplicity.

As you can see from javadoc, you can enable multiple barcode symbologies within this recognizer, however keep in mind that enabling more barcode symbologies affects scanning performance - the more barcode symbologies are enabled, the slower the overall recognition performance. Also, keep in mind that some simple barcode symbologies that lack proper redundancy, such as Code 39, can be recognized within more complex barcodes, especially 2D barcodes, like PDF417.

This recognizer can be used in any context, but it works best with the BarcodeScanActivity, which has UI best suited for barcode scanning.

Embedding PDF417.mobi inside another SDK

You need to ensure that the final app gets all resources required by PDF417.mobi. At the time of writing this documentation, Android does not have support for combining multiple AAR libraries into single fat AAR. The problem is that resource merging is done while building application, not while building AAR, so application must be aware of all its dependencies. There is no official Android way of "hiding" third party AAR within your AAR.

This problem is usually solved with transitive Maven dependencies, i.e. when publishing your AAR to Maven you specify dependencies of your AAR so they are automatically referenced by app using your AAR. Besides this, there are also several other approaches you can try:

Processor architecture considerations

PDF417.mobi is distributed with ARMv7, ARM64, x86 and x86_64 native library binaries.

ARMv7 architecture gives the ability to take advantage of hardware accelerated floating point operations and SIMD processing with NEON. This gives PDF417.mobi a huge performance boost on devices that have ARMv7 processors. Most new devices (all since 2012.) have ARMv7 processor so it makes little sense not to take advantage of performance boosts that those processors can give. Also note that some devices with ARMv7 processors do not support NEON instruction sets, most popular being those based on NVIDIA Tegra 2. Since these devices are old by today's standard, PDF417.mobi does not support them. For the same reason, PDF417.mobi does not support devices with ARMv5 (armeabi) architecture.

ARM64 is the new processor architecture that most new devices use. ARM64 processors are very powerful and also have the possibility to take advantage of new NEON64 SIMD instruction set to quickly process multiple pixels with a single instruction.

x86 and x86_64 architectures are used on very few devices today, most of them are manufactured before 2015, like Asus Zenfone 4 and they take about 1% of all devices, according to the Device catalog on Google Play Console. Some x86 and x86_64 devices have ARM emulator, but running the PDF417.mobi on the emulator will give a huge performance penalty.

There are some issues to be considered:

LibPdf417Mobi.aar archive contains ARMv7, ARM64, x86 and x86_64 builds of the native library. By default, when you integrate PDF417.mobi into your app, your app will contain native builds for all these processor architectures. Thus, PDF417.mobi will work on ARMv7, ARM64, x86 and x86_64 devices and will use ARMv7 features on ARMv7 devices and ARM64 features on ARM64 devices. However, the size of your application will be rather large.

Reducing the final size of your app

We recommend that you distribute your app using App Bundle. This will defer apk generation to Google Play, allowing it to generate minimal APK for each specific device that downloads your app, including only required processor architecture support.

Using APK splits

If you are unable to use App Bundle, you can create multiple flavors of your app - one flavor for each architecture. With gradle and Android studio this is very easy - just add the following code to build.gradle file of your app:

android {
  ...
  splits {
    abi {
      enable true
      reset()
      include 'x86', 'armeabi-v7a', 'arm64-v8a', 'x86_64'
      universalApk true
    }
  }
}

With that build instructions, gradle will build four different APK files for your app. Each APK will contain only native library for one processor architecture and one APK will contain all architectures. In order for Google Play to accept multiple APKs of the same app, you need to ensure that each APK has different version code. This can easily be done by defining a version code prefix that is dependent on architecture and adding real version code number to it in following gradle script:

// map for the version code
def abiVersionCodes = ['armeabi-v7a':1, 'arm64-v8a':2, 'x86':3, 'x86_64':4]

import com.android.build.OutputFile

android.applicationVariants.all { variant ->
    // assign different version code for each output
    variant.outputs.each { output ->
        def filter = output.getFilter(OutputFile.ABI)
        if(filter != null) {
            output.versionCodeOverride = abiVersionCodes.get(output.getFilter(OutputFile.ABI)) * 1000000 + android.defaultConfig.versionCode
        }
    }
}

For more information about creating APK splits with gradle, check this article from Google.

After generating multiple APK's, you need to upload them to Google Play. For tutorial and rules about uploading multiple APK's to Google Play, please read the official Google article about multiple APKs.

Removing processor architecture support

If you won't be distributing your app via Google Play or for some other reasons want to have single APK of smaller size, you can completely remove support for certain CPU architecture from your APK. This is not recommended due to consequences.

To keep only some CPU architectures, for example armeabi-v7a and arm64-v8a, add the following statement to your android block inside build.gradle:

android {
    ...
    ndk {
        // Tells Gradle to package the following ABIs into your application
        abiFilters 'armeabi-v7a', 'arm64-v8a'
    }
}

This will remove other architecture builds for all native libraries used by the application.

To remove support for a certain CPU architecture only for PDF417.mobi, add the following statement to your android block inside build.gradle:

android {
    ...
    packagingOptions {
        exclude 'lib/<ABI>/libPdf417Mobi.so'
    }
}

where <ABI> represents the CPU architecture you want to remove:

You can also remove multiple processor architectures by specifying exclude directive multiple times. Just bear in mind that removing processor architecture will have side effects on performance and stability of your app. Please read this for more information.

Consequences of removing processor architecture

Combining PDF417.mobi with other native libraries

If you are combining PDF417.mobi library with other libraries that contain native code into your application, make sure you match the architectures of all native libraries. For example, if third party library has got only ARMv7 and x86 versions, you must use exactly ARMv7 and x86 versions of PDF417.mobi with that library, but not ARM64. Using these architectures will crash your app at initialization step because JVM will try to load all its native dependencies in same preferred architecture and will fail with UnsatisfiedLinkError.

Troubleshooting

Integration difficulties

In case of problems with SDK integration, first make sure that you have followed integration instructions. If you're still having problems, please contact us at help.microblink.com.

Licensing issues

If you are getting "invalid license key" error or having other license-related problems (e.g. some feature is not enabled that should be or there is a watermark on top of camera), first check the ADB logcat. All license-related problems are logged to error log so it is easy to determine what went wrong.

When you have to determine what is the license-relate problem or you simply do not understand the log, you should contact us help.microblink.com. When contacting us, please make sure you provide following information:

Keep in mind: Versions 8.0.0 and above require an internet connection to work under our new License Management Program.

We’re only asking you to do this so we can validate your trial license key. Data extraction still happens offline, on the device itself. Once the validation is complete, you can continue using the SDK in offline mode (or over a private network) until the next check.

Other problems

If you are having problems with scanning certain items, undesired behaviour on specific device(s), crashes inside PDF417.mobi or anything unmentioned, please do as follows:

FAQ and known issues

After switching from trial to production license I get InvalidLicenseKeyException when I construct specific Recognizer object

Each license key contains information about which features are allowed to use and which are not. This exception indicates that your production license does not allow using of specific Recognizer object. You should contact support to check if provided license is OK and that it really contains all features that you have purchased.

I get InvalidLicenseKeyException with trial license key

Whenever you construct any Recognizer object or any other object that derives from Entity, a check whether license allows using that object will be performed. If license is not set prior constructing that object, you will get InvalidLicenseKeyException. We recommend setting license as early as possible in your app, ideally in onCreate callback of your Application singleton.

When my app starts, I get exception telling me that some resource/class cannot be found or I get ClassNotFoundException

This usually happens when you perform integration into Eclipse project and you forget to add resources or native libraries into the project. You must alway take care that same versions of both resources, assets, java library and native libraries are used in combination. Combining different versions of resources, assets, java and native libraries will trigger crash in SDK. This problem can also occur when you have performed improper integration of PDF417.mobi SDK into your SDK. Please read how to embed PDF417.mobi inside another SDK.

When my app starts, I get UnsatisfiedLinkError

This error happens when JVM fails to load some native method from native library If performing integration into Android studio and this error happens, make sure that you have correctly combined PDF417.mobi SDK with third party SDKs that contain native code. If this error also happens in our integration sample apps, then it may indicate a bug in the SDK that is manifested on specific device. Please report that to our support team.

I've added my callback to MetadataCallbacks object, but it is not being called

Make sure that after adding your callback to MetadataCallbacks you have applied changes to RecognizerRunnerView or RecognizerRunner as described in this section.

I've removed my callback to MetadataCallbacks object, and now app is crashing with NullPointerException

Make sure that after removing your callback from MetadataCallbacks you have applied changes to RecognizerRunnerView or RecognizerRunner as described in this section.

In my onScanningDone callback I have the result inside my Recognizer, but when scanning activity finishes, the result is gone

This usually happens when using RecognizerRunnerView and forgetting to pause the RecognizerRunnerView in your onScanningDone callback. Then, as soon as onScanningDone happens, the result is mutated or reset by additional processing that Recognizer performs in the time between end of your onScanningDone callback and actual finishing of the scanning activity. For more information about statefulness of the Recognizer objects, check this section.

I am using built-in activity to perform scanning and after scanning finishes, my app crashes with IllegalStateException stating Data cannot be saved to intent because its size exceeds intent limit.

This usually happens when you use Recognizer that produces image or similar large object inside its Result and that object exceeds the Android intent transaction limit. You should enable different intent data transfer mode. For more information about this, check this section. Also, instead of using built-in activity, you can use RecognizerRunnerFragment with built-in scanning overlay.

After scanning finishes, my app freezes

This usually happens when you attempt to transfer standalone Result that contains images or similar large objects via Intent and the size of the object exceeds Android intent transaction limit. Depending on the device, you will get either TransactionTooLargeException, a simple message BINDER TRANSACTION FAILED in log and your app will freeze or your app will get into restart loop. We recommend that you use RecognizerBundle and its API for sending Recognizer objects via Intent in a more safe manner (check this section for more information). However, if you really need to transfer standalone Result object (e.g. Result object obtained by cloning Result object owned by specific Recognizer object), you need to do that using global variables or singletons within your application. Sending large objects via Intent is not supported by Android.

Scanning with a camera works better than a recognition of images by using the Direct API

When automatic scanning of camera frames with our camera management is used (provided camera overlays or direct usage of RecognizerRunnerView), we use a stream of video frames and send multiple images to the recognition to boost reading accuracy. Also, we perform frame quality analysis and combine scanning results from multiple camera frames. On the other hand, when you are using the Direct API with a single image per document side, we cannot combine multiple images. We do our best to extract as much information as possible from that image. In some cases, when the quality of the input image is not good enough, for example, when the image is blurred or when glare is present, we are not able to successfully read the document.

I am getting a ‘Network required’ error when I'm on a private network

Online trial licenses require a public network access for validation purposes. See Licensing issues.

Additional info

PDF417.mobi SDK size

You can find PDF417.mobi SDK size report for all supported ABIs here.

API reference

Complete API reference can be found in Javadoc.

Contact

For any other questions, feel free to contact us at help.microblink.com.