DEV Community

Cover image for Everything is just a scan way! Integration of Huawei Scan Kit in Books Applications
HMS Community
HMS Community

Posted on

Everything is just a scan way! Integration of Huawei Scan Kit in Books Applications

Introduction

In this article, I will be integrating Huawei Scan Kit in an Application. Huawei Scan Kit scans and parses all major 1D and 2D Barcodes as well as generates barcode which helps you to quickly build barcode scanning functions into your apps. Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and can scan a very small barcode in the same way. It works even in suboptimal situations, such as under dim lighting or when the barcode is reflective, dirty, blurry, or printed on a cylindrical surface. This leads to a higher scanning success rate, and an improved user experience.

React Native

React Native helps you to create real and exciting mobile apps with the help of JavaScript only, which is supportable for both android and iOS platforms.
Just code once, and the React Native apps are available for both iOS and Android platforms which helps to save development time.
React Native is a framework that builds a hierarchy of UI components to build the JavaScript code.
It uses the same fundamental UI building blocks as regular iOS and Android apps.

Requirements

  1. Any operating system (MacOS, Linux and Windows).
  2. Must have a Huawei phone with HMS 4.0.2.300 or later.
  3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
  4. Minimum API Level 21 is required.
  5. Required EMUI 9.0.0 and later version devices.

Integrate HMS Dependencies

  • First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.

  • Create a project in android studio, refer Creating an Android Studio Project.

  • Generate a SHA-256 certificate fingerprint.

  • To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
    Or use cmd as explained in SHA256 CODE

  • Create an App in AppGallery Connect.

  • Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
    Image description

  • Enter SHA-256 certificate fingerprint and click Save, as follows.
    Image description

React Native Project Preparation

  • Environment set up, refer below link.
    https://reactnative.dev/docs/environment-setup

  • Create project using below command.
    react-native init project name

  • Download Plugin Using NPM.
    To integrate the plugin, ensure that the preparation step is completed and download the plugin using the following command.
    npm i @hmscore/react-native-hms-scan

  • Open settings.gradle located under the project-dir > android directory and add

include ':react-native-hms-scan'
project(':react-native-hms-scan').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-scan/android')
Enter fullscreen mode Exit fullscreen mode
  • Open build.gradle file which is located under project.dir > android > app directory. Configure build dependencies.
dependencies {
    ...
    implementation project(":react-native-hms-scan")
    ...
}
Enter fullscreen mode Exit fullscreen mode
  • Add following in the MainApplication file
import com.huawei.hms.rn.scan.RNHMSScanPackage;

List<ReactPackage> getPackages() {
          List<ReactPackage> packages = new PackageList(this).getPackages();
          packages.add(new RNHMSScanPackage());
          return packages;
Enter fullscreen mode Exit fullscreen mode
  • Add below permissions to Android.manifest file.
<p><uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
p>

Enter fullscreen mode Exit fullscreen mode

Development

  • Request the permissions in the code dynamically.
import ScanPlugin from '@hmscore/react-native-hms-scan';
//Call requestCameraAndStoragePermission API.
ScanPlugin.Permission.requestCameraAndStoragePermission()
    .then((res) => console.log("Result:", res));

Enter fullscreen mode Exit fullscreen mode
  • Check whether the required permissions are enabled before scanning a barcode.
//Call hasCameraAndStoragePermission API.
ScanPlugin.Permission.hasCameraAndStoragePermission()
    .then((res) => console.log("Result:", res));
Enter fullscreen mode Exit fullscreen mode
  • Generate Barcode
ScanPlugin.Utils.buildBitmap({
              content: this.state.content,
              type: this.state.type,
              width: this.state.width,
              height: this.state.height,
              margin: this.state.margin,
              color: this.state.color,
              backgroundColor: this.state.backgroundColor,
            })
              .then((res) => {
                this.setState({showImage: true});
                this.setState({base64ImageData: res});
              })
Enter fullscreen mode Exit fullscreen mode
  • Decode Bitmap
ScanPlugin.Utils.decodeWithBitmap({
              data: barcode_images.barcode,
              scanType: ScanPlugin.ScanType,
              additionalScanTypes: [],
            })
              .then((res) =>
                this.setState({
                  decodesBitmap: [...this.state.decodesBitmap, res],
                }),
              )                this.setState({base64ImageData: res});
Enter fullscreen mode Exit fullscreen mode
  • The process of using Scan Kit in Default View mode as follows:

• Check whether the app has the camera access and file read permissions.
• If the app has the required permissions, call the startDefaultView API from Utils module of the Scan Kit React Native Plugin to bring up the scanning UI.
• Check whether the scanning UI is successfully displayed.
• Obtain the scanning result based on the scanning status.

  • Construct a DefaultViewRequest object.

The parameters are as follows:

import ScanPlugin from '@hmscore/react-native-hms-scan';
let defaultViewRequest = {
    scanType: ScanPlugin.ScanType.All,
    additionalScanTypes: [],
}
Enter fullscreen mode Exit fullscreen mode
  • Call the startDefaultView API with the request object to bring up the scanning UI and obtain the scanning result of Default View which is a ScanResponse object.
ScanPlugin.Utils.startDefaultView(defaultViewRequest)
  .then((res) => console.log(res)) 
  .catch((e) => console.log(e))
Enter fullscreen mode Exit fullscreen mode
  • Construct a CustomizedViewRequest object in order to customize the scanning UI.
ScanPlugin.CustomizedView.startCustomizedView({
              scanType: ScanPlugin.ScanType,
              additionalScanTypes: [],
              rectHeight: 200,
              rectWidth: 200,
              continuouslyScan: true,
              isFlashAvailable: false,
              flashOnLightChange: false,
              isGalleryAvailable: false,
            })
              .then((res) =>
                this.setState({
                  decodesCustom: [...this.state.decodesCustom, res],
                }),
              )
Enter fullscreen mode Exit fullscreen mode

Testing

Run the android App using the below command.
react-native run-android

Result

Image description

Image description

Image description

Tips and Tricks

  1. Check supported 13 barcode formats here.
  2. Only add configurations for Scan Kit to support required formats of barcode as this will improve the scanning speed.
  3. HMS react native plugin does not support Expo CLI and only support React Native CLI

Conclusion

In this article, we have learnt that how to integrate scan kit into the app, quickly build barcode scanning functions into your apps. Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and can scan a very small barcode in the same way.

Reference

Scan Kit: Documentation
Scan Kit: Training Video

Top comments (0)