Barcode Scanner HTML5

Android WebView

This barcode scanner app uses an Android standard  WebView in the activity_main.xml layout. To load the HTML5 app, just call loadUrl() on the WebView providing a path to the main HTML file. Please notice that in this case the HTML5 app is stored inside the Android app, in the assets/ folder, but it can be moved anywhere.

mWebView = (WebView) findViewById(R.id.webView_main);
mWebView.loadUrl("file:///android_asset/www/index.html");

Please take a look at the function setupWebView() that contains the initialization and some useful configuration of the WebView.

JavaScript Interface

To expose Java objects and their methods on JavaScript, you need to specifically export Java objects on the WebView. To access the BarcodeManager from JS, this example provides a wrapper class around the original Datalogic  BarcodeManager to allow using intents transparently if configured so, but simply exposing the BarcodeManager would do:

mWebView.addJavascriptInterface(new BarcodeManagerWrapper(), "BarcodeManager");

On JavaScript side a new object happears at window.BarcodeManager. The name is the second argument of addJavascriptInterface(). This interface is unidirectional from JavaScript to Java, that is Java can't call any JavaScript function for the moment.

It is still missing a Java to JavaScript interface, for calling BarcodeManager callbacks. It is done evaluating JS code inside the WebView, please check the Utils.java file and the function callJsFunction.

Please notice that this solution can lead to security breaches if not done in a safe way.

public static void evalJs(WebView w, String js) {
    w.loadUrl("javascript:" + js);
}

HTML5 app

The main application is a standalone HTML web application that can run in any web browser (older I.E. not supported) and resides in assets/www/. The app is based on AngularJS (v1).

Please notice that CSS is written in SCSS, so please build it after any modification or use the already compiled version .css.

The Java-to-JavaScript interface consists of 4 callbacks called by BarcodeManager that have the same purpose of their Java homonyms:

onStart = function() { };

onStop = function() { };

onTimeout = function() { };

onRead = function(code, symbology) { };

From JavaScript you can call the following methods of BarcodeManager, as you would do in Java:

BarcodeManager.startDecode(timeout);
BarcodeManager.stopDecode();