Skip to content

Commit 473f189

Browse files
committed
update android webview sample & readme;
1 parent 5c03269 commit 473f189

File tree

13 files changed

+305
-569
lines changed

13 files changed

+305
-569
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
# Hello-world for WebView - Dynamsoft Barcode Reader Sample
2+
3+
This sample demonstrates how to use the [Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/overview/) JS Edition in Android.
4+
5+
If you want to learn how to use the Android Edition SDK in javascript, you can check [Android WebView Barcode Scanning](https://github.com/Dynamsoft/barcode-reader-mobile-samples/tree/main/android/JavaScript/WebViewBarcodeScanning).
6+
7+
## Get Started
8+
9+
### 1. Get your web page ready
10+
11+
Follow this [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/?ver=latest#building-your-own-page) and build your page, including importing the SDK and initializing the certificate, etc.
12+
13+
Then you can define some functions according to your needs, like the code below, we will use it later:
14+
15+
```javascript
16+
async function startScanner() {
17+
let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
18+
await scanner.setUIElement(document.getElementById('div-ui-container'));
19+
await scanner.show();
20+
}
21+
```
22+
23+
Don't forget to load this page using webview in your Android project.
24+
25+
### 2. Add DBRWebViewHelper
26+
27+
Copy the file 'DBRWebViewHelper.java' in the sample to your Android project.
28+
29+
This file provides a class: `DBRWebViewHelper`, which will make it very convenient to let the javascript code in your WebView use DBR Android by providing some methods.
30+
31+
```java
32+
DBRWebViewHelper dbrWebViewHelper = new DBRWebViewHelper();
33+
```
34+
35+
### 3. Pollute your WebView
36+
37+
Class `DBRWebViewHelper` provides a method `pollute`, which will inject a global variable `DBR_Android` into the javascript code in your WebView.
38+
39+
```java
40+
// public void pollute(WebView webview)
41+
dbrWebViewHelper.pollute(mWebView);
42+
```
43+
44+
The variable is an object that has some methods to communicate with native code, you can call them directly like this:
45+
46+
```javascript
47+
// e.g. callback after decoding, this will execute our corresponding java code in DBRWebViewHelper
48+
scanner.onUniqueRead = (txt, result) => {
49+
const format = result.barcodeFormatString;
50+
window.DBR_Android.onUniqueRead(format + " " + txt)
51+
};
52+
```
53+
54+
## Customize DBRWebViewHelper
55+
56+
**Notice: when you change variables or methods, you should modify both native code and JS code to avoid errors.**
57+
58+
### 1. Rename the variable to be injected
59+
60+
The name is set in the method `pollute`, just change the string value.
61+
62+
```java
63+
mWebView.addJavascriptInterface(new WebAppInterface(), "e.g. DBR_Android");
64+
```
65+
66+
### 2. Change the methods to be injected
67+
68+
All methods are defined in the `WebAppInterface` class in 'DBRWebViewHelper.java', you can add methods you need, or delete and modify them.
69+
70+
```java
71+
// e.g.
72+
public class WebAppInterface {
73+
WebAppInterface() {}
74+
75+
@JavascriptInterface
76+
public void onUniqueRead(String result) {
77+
// your code here
78+
}
79+
@JavascriptInterface
80+
public void onWasmLoaded() {
81+
// your code here
82+
}
83+
}
84+
```
85+
86+
### 3. Execute JS code
87+
88+
`DBRWebViewHelper` has an `evaluateJavascript()` method, which executes javascript code through `WebView.evaluateJavascript()`, you can use it to complete the interaction like the following code.
89+
90+
```java
91+
public void stopScanner() {
92+
evaluateJavascript("stopScanner()");
93+
}
94+
```
95+
96+
Then, the following code will execute the function `startScanner()` we just defined in javascript code.
97+
98+
```java
99+
dbrWebViewHelper.startScanner();
100+
```

1.hello-world/14.read-video-webview/android/app/build.gradle

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ android {
77
buildToolsVersion "30.0.2"
88

99
defaultConfig {
10-
applicationId "com.dynamsoft.javascript.webviewbarcodescanning"
10+
applicationId "com.dynamsoft.javascript.readvideowebview"
1111
minSdkVersion 21
1212
targetSdkVersion 30
1313
versionCode 1
@@ -34,7 +34,6 @@ android {
3434
}
3535

3636
dependencies {
37-
implementation 'com.google.code.gson:gson:2.9.1'
3837
implementation 'com.dynamsoft:dynamsoftcameraenhancer:2.3.10@aar'
3938
implementation 'com.dynamsoft:dynamsoftbarcodereader:9.6.11@aar'
4039
implementation 'androidx.appcompat:appcompat:1.2.0'

1.hello-world/14.read-video-webview/android/app/src/main/AndroidManifest.xml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dynamsoft.javascript.webviewbarcodescanning">
2+
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dynamsoft.javascript.readvideowebview">
33

44
<uses-permission android:name="android.permission.INTERNET" />
55
<application
@@ -9,7 +9,7 @@
99
android:label="@string/app_name"
1010
android:roundIcon="@mipmap/logodbr"
1111
android:supportsRtl="true"
12-
android:theme="@style/Theme.WebViewBarcodeScanning">
12+
android:theme="@style/Theme.ReadVideoWebView">
1313
<activity
1414
android:name=".MainActivity"
1515
android:exported="true">

1.hello-world/14.read-video-webview/android/app/src/main/assets/index.html

Lines changed: 52 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,123 +1,68 @@
1-
<!doctype html>
1+
<!DOCTYPE html>
22
<html lang="en">
33

44
<head>
5-
<meta charset="UTF-8">
6-
<meta http-equiv="X-UA-Compatible" content="IE=edge">
7-
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
8-
<script src="./js/BridgeInitializer.js"></script>
9-
<title>Android WebView Sample</title>
5+
<meta charset="utf-8">
6+
<meta name="viewport" content="width=device-width,initial-scale=1.0">
7+
<meta name="description" content="Quickly read barcodes with Dynamsoft Barcode Reader from a live camera stream.">
8+
<meta name="keywords" content="camera based barcode reading">
9+
<link rel="canonical" href="https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/14.read-video-webview.html">
10+
<title>Dynamsoft Barcode Reader Sample - Read Video WebView(Android)</title>
1011
</head>
1112

12-
<body style="margin: 0;">
13-
<header style="text-align: center; height: 100px; line-height: 100px;">
14-
<h1 style="margin: 0;">Android WebView</h1>
15-
</header>
16-
<hr style="margin: 0;">
17-
<div class="container" style="margin-top: 300px; padding: 0 10px; text-align: center; position: relative;">
18-
<i id="flash"
19-
style="position: absolute; top: -80px; width: 30px; height: 30px; left: calc(50% - 15px); display: none;">
20-
<svg viewBox="64 64 896 896" data-icon="funnel-plot" width="1em" height="1em" fill="currentColor"
21-
aria-hidden="true" focusable="false" class="" style="color: #fe8e14; font-size: 30px;">
22-
<path
23-
d="M880.1 154H143.9c-24.5 0-39.8 26.7-27.5 48L349 607.4V838c0 17.7 14.2 32 31.8 32h262.4c17.6 0 31.8-14.3 31.8-32V607.4L907.7 202c12.2-21.3-3.1-48-27.6-48zM603.4 798H420.6V650h182.9v148zm9.6-226.6l-8.4 14.6H419.3l-8.4-14.6L334.4 438h355.2L613 571.4zM726.3 374H297.7l-85-148h598.6l-85 148z">
24-
</path>
25-
</svg>
26-
</i>
27-
<button id="start" style="margin: 5px 0;">Start Scan</button>
28-
<button id="stop" style="margin: 5px 0; display: none;">Stop Scan</button>
29-
<h4 id="results"></h4>
30-
<hr>
31-
<span>Choose the Formats to Detect: </span>
32-
<form id="chooseBarcodeFormats">
33-
<input type="checkbox" id="OneD" name="barcodeFormat" value="BF_ONED" checked>
34-
<label for="OneD"> 1D </label><br />
35-
<input type="checkbox" id="QR" name="barcodeFormat" value="BF_QR_CODE" checked>
36-
<label for="QR"> QR Code </label><br />
37-
<input type="checkbox" id="PDF417" name="barcodeFormat" value="BF_PDF417">
38-
<label for="PDF417"> PDF 417 </label><br />
39-
<input type="checkbox" id="Datamatrix" name="barcodeFormat" value="BF_DATAMATRIX">
40-
<label for="Datamatrix"> DataMatrix </label> <br />
41-
</form>
42-
<span>Expected barcode count per frame: </span>
43-
<input type="range" min="1" max="20" step="1" id="expectedNumberBarcodes" value="1">
44-
<span id="expectedNumberBarcodesLabel">1</span>
13+
<body style="margin: 0;padding: 0;">
14+
<div id="UIElement" style="width: 100vw;height: 100vh;">
15+
<span id='lib-load' style='font-size:x-large' hidden>Loading Library...</span>
16+
<div id="div-ui-container" class="div-ui-container">
17+
<div class="dce-video-container"></div>
18+
</div>
4519
</div>
46-
20+
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/dbr.js"></script>
4721
<script>
48-
(async () => {
49-
// set the position of the CameraView
50-
// [marginLeft, marginTop, width, height] / px
51-
dbrWebViewBridge.setCameraUI([window.screen.width / 2 - 125, 125, 250, 250]);
52-
await updateBarcodeFormats();
53-
54-
dbrWebViewBridge.onBarcodeRead = results => {
55-
let resultText = "";
56-
JSON.parse(results).forEach(result => {
57-
resultText += result.barcodeText + " ";
58-
});
59-
document.getElementById("results").innerText = resultText;
60-
};
61-
})();
22+
/** LICENSE ALERT - README
23+
* To use the library, you need to first specify a license key using the API "license" as shown below.
24+
*/
6225

63-
let flashFlag = false;
64-
const startBtn = document.getElementById("start");
65-
const stopBtn = document.getElementById("stop");
66-
const flashBtn = document.getElementById("flash");
67-
const formatsForm = document.getElementById("chooseBarcodeFormats");
68-
const expectedRange = document.getElementById("expectedNumberBarcodes");
26+
Dynamsoft.DBR.BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9';
6927

70-
startBtn.addEventListener("click", () => {
71-
startBtn.style.display = "none";
72-
flashBtn.style.display = "inline-block";
73-
stopBtn.style.display = "inline-block";
74-
dbrWebViewBridge.startScanning();
75-
});
76-
stopBtn.addEventListener("click", () => {
77-
stopBtn.style.display = "none";
78-
flashBtn.style.display = "none";
79-
startBtn.style.display = "inline-block";
80-
dbrWebViewBridge.stopScanning();
81-
});
82-
flashBtn.addEventListener("click", () => {
83-
dbrWebViewBridge.switchFlashlight(!flashFlag);
84-
flashFlag = !flashFlag;
85-
});
86-
formatsForm.addEventListener("change", async () => {
87-
await updateBarcodeFormats();
88-
});
89-
expectedRange.addEventListener("change", async () => {
90-
let expectedVal = document.getElementById('expectedNumberBarcodes').value;
91-
document.getElementById('expectedNumberBarcodesLabel').innerText = expectedVal;
92-
const settings = await dbrWebViewBridge.getRuntimeSettings();
93-
settings.expectedBarcodesCount = parseInt(expectedVal);
94-
await dbrWebViewBridge.updateRuntimeSettings(settings);
95-
});
28+
/**
29+
* You can visit https://www.dynamsoft.com/customer/license/trialLicense?utm_source=github&product=dbr&package=js to get your own trial license good for 30 days.
30+
* Note that if you downloaded this sample from Dynamsoft while logged in, the above license key may already be your own 30-day trial license.
31+
* For more information, see https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/?ver=9.6.10&utm_source=github#specify-the-license or contact [email protected].
32+
* LICENSE ALERT - THE END
33+
*/
9634

97-
async function updateBarcodeFormats() {
98-
const EnumBarcodeFormat = await dbrWebViewBridge.getEnumBarcodeFormat();
99-
const settings = await dbrWebViewBridge.getRuntimeSettings();
100-
settings.barcodeFormatIds = EnumBarcodeFormat.BF_NULL;
101-
const checkboxes = document.querySelectorAll('input[name="barcodeFormat"]:checked');
102-
checkboxes.forEach((checkbox) => {
103-
switch (checkbox.value) {
104-
case "BF_ONED":
105-
settings.barcodeFormatIds |= EnumBarcodeFormat.BF_ONED;
106-
break;
107-
case "BF_QR_CODE":
108-
settings.barcodeFormatIds |= EnumBarcodeFormat.BF_QR_CODE;
109-
break;
110-
case "BF_PDF417":
111-
settings.barcodeFormatIds |= EnumBarcodeFormat.BF_PDF417;
112-
break;
113-
case "BF_DATAMATRIX":
114-
settings.barcodeFormatIds |= EnumBarcodeFormat.BF_DATAMATRIX;
115-
break;
35+
let pScanner = null;
36+
(async function () {
37+
try {
38+
await Dynamsoft.DBR.BarcodeReader.loadWasm();
39+
window.DBR_Android.onWasmLoaded();
40+
} catch (ex) {
41+
let errMsg;
42+
if (ex.message.includes("network connection error")) {
43+
errMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support ([email protected]) to acquire an offline license.";
44+
} else {
45+
errMsg = ex.message || ex;
11646
}
117-
});
118-
await dbrWebViewBridge.updateRuntimeSettings(settings);
47+
console.error(errMsg);
48+
alert(errMsg);
49+
}
50+
})();
51+
52+
async function startScanner() {
53+
let scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance());
54+
await scanner.setUIElement(document.getElementById('div-ui-container'));
55+
scanner.onUniqueRead = (txt, result) => {
56+
const format = result.barcodeFormatString;
57+
window.DBR_Android.onUniqueRead(format + " " + txt)
58+
};
59+
await scanner.show();
11960
}
12061

62+
async function stopScanner() {
63+
let scanner = await pScanner;
64+
scanner && scanner.hide();
65+
}
12166
</script>
12267
</body>
12368

0 commit comments

Comments
 (0)