Overview

HUAWEI Scan Kit scans and parses all major 1D and 2D barcodes and generates QR codes, helping you quickly build barcode scanning functions into your apps.

HUAWEI Scan Kit automatically detects, magnifies, and identifies barcodes from a distance, and is also able to scan a very small barcode in the same way. HUAWEI Scan Kit 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.

What You Will Create

In this codelab, you will create a barcode scanning app that uses the Customized View mode.

What You Will Learn

Hardware Requirements

  1. A computer with Android Studio installed for app development
  2. Android 4.4 (SDK version 19) or later

Software Requirements

  1. Android Studio
  2. Java JDK (1.8 or later)

If you need to officially release an app that integrates HUAWEI Scan Kit, please refer to Preparations for Integrating HUAWEI HMS Core to complete preparations.
To verify this codelab demo, you can use settings in the Sample Code. Therefore, you can skip this step.

Sample Code Download

If you are using Android Studio, you can integrate your HMS SDK by using the Maven repository. Before you start developing an app, integrate the HMS SDK into your Android Studio first.

1. Obtaining the Configuration File

  1. Sign in to AppGallery Connect and select My apps. Find your app from the list and click the link under Android App in the Mobile phone column.
  2. Go to Develop > Overview > App information. Click agconnect-services.json to download the configuration file.
  3. Copy the agconnect-services.json file to the app's root directory.

2. Adding Build Dependencies

  1. Open the build.gradle file in the app directory.
  2. Go to allprojects > repositories and configure the Maven repository address for the HMS SDK.
    allprojects { repositories { google() jcenter() maven {url 'http://developer.huawei.com/repo/'} } }
  3. Go to buildscript > dependencies and add dependency configurations.
    buildscript{ dependencies { classpath 'com.huawei.agconnect:agcp:1.2.0.300' } }
  4. Configure build dependencies and replace {version} with the actual SDK version number, for example, implementation 'com.huawei.hms:scan:1.1.3.300'.
    dependencies{ implementation 'com.huawei.hms:scan:{version}' }
  5. Add the AppGallery Connect plug-in dependency to the file header. (The configuration in step 2.3 is complete.)
    apply plugin: 'com.huawei.agconnect'
  6. Synchronize the project. Open the modified build.gradle file again. You will find a Sync Now link in the upper right corner of the page. Click Sync Now and wait until synchronization is complete. If an error occurs, check your network connection and the configurations in the build.gradle file.

Before calling HUAWEI Scan Kit, declare required permissions in the manifest file. Android provides two scanning permissions: CAMERA (camera permission) and READ_EXTERNAL_STORAGE (file reading permission).

In AndroidManifest.xml, add the following:

<!--Camera permission--> <uses-permission android:name="android.permission.CAMERA" /> <!--File reading permission--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" />

After declaring permissions in the manifest file, you need to dynamically request the permissions in the code. In MainActivity.java, add the following:

public void newViewBtnClick(View view) { // DEFINED_CODE is customized for receiving the permission verification result. ActivityCompat.requestPermissions( this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, DEFINED_CODE); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) { return; } if (requestCode == DEFINED_CODE) { // Display the barcode scanning view. this.startActivityForResult(new Intent(this, DefinedActivity.class), REQUEST_CODE_SCAN); } }

Note: If you use sample code in which permissions have been applied for, you can ignore this section.

HUAWEI Scan Kit provides four call modes. For details about the differences between the four modes, please refer to the Development Guide. In this codelab, Customized View is used as the example to implement the scanning capability.

1. Customize the elements on the scanning view.

Customize elements on the scanning view as required, such as the barcode scanning box and prompt. For details, please refer to the Development Guide.

2. Implement camera scanning.

To scan barcodes using the camera in the customized activity, add the following to the app/src/main/java/com/example/scankitdemo/DefinedActivity.java file in the sample code:

// Import all dependencies suggested by Android Studio. private RemoteView remoteView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_defined); //1.get screen density to caculate viewfinder's rect DisplayMetrics dm = getResources().getDisplayMetrics(); float density = dm.density; //2.get screen size mScreenWidth = getResources().getDisplayMetrics().widthPixels; mScreenHeight = getResources().getDisplayMetrics().heightPixels; int scanFrameSize = (int) (SCAN_FRAME_SIZE * density); //3.caculate viewfinder's rect,it's in the middle of the layout //set scanning area(Optional, rect can be null,If not configure,default is in the center of layout) Rect rect = new Rect(); rect.left = mScreenWidth / 2 - scanFrameSize / 2; rect.right = mScreenWidth / 2 + scanFrameSize / 2; rect.top = mScreenHeight / 2 - scanFrameSize / 2; rect.bottom = mScreenHeight / 2 + scanFrameSize / 2; //initialize RemoteView instance, and set calling back for scanning result remoteView = new RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.ALL_SCAN_TYPE).build(); remoteView.onCreate(savedInstanceState); remoteView.setOnResultCallback(new OnResultCallback() { @Override public void onResult(HmsScan[] result) { if (result != null && result.length > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) { Intent intent = new Intent(); intent.putExtra(SCAN_RESULT, result[0]); setResult(RESULT_OK, intent); DefinedActivity.this.finish(); } } }); // Add the defined RemoteView to the page layout. FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); FrameLayout frameLayout = findViewById(R.id.rim); frameLayout.addView(remoteView, params); }

To add RemoteView lifecycle management, add the following to the app/src/main/java/com/example/scankitdemo/DefinedActivity.java file in the sample code:

@Override protected void onStart() { super.onStart(); remoteView.onStart(); } @Override protected void onResume() { super.onResume(); remoteView.onResume(); } @Override protected void onPause() { super.onPause(); remoteView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); remoteView.onDestroy(); } @Override protected void onStop() { super.onStop(); remoteView.onStop(); }

3. Process the scanning result.

To process the barcode scanning result in MainActivity, add the following to the app/src/main/java/com/example/scankitdemo/MainActivity.java file in the sample code:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //Receive result super.onActivityResult(requestCode, resultCode, data); if (resultCode != RESULT_OK || data == null) { return; } if (requestCode == REQUEST_CODE_SCAN) { HmsScan hmsScan = data.getParcelableExtra(DefinedActivity.SCAN_RESULT); if (hmsScan != null && !TextUtils.isEmpty(hmsScan.getOriginalValue())) { Toast.makeText(MainActivity.this, hmsScan.getOriginalValue(), Toast.LENGTH_SHORT).show(); } } }

Click to run the project you have created in Android Studio to generate an APK. Then install the APK on the test phone. The following figures show the running UIs.

Entry view:

Scanning view in Customized View mode:

Scanning result view:

Well done. You have successfully completed this codelab and learned how to:

  1. Integrate HUAWEI Scan Kit.
  2. Use the Customized View mode of HUAWEI Scan Kit to scan barcodes.

For more information about HUAWEI Scan Kit, please visit our official website. If you encounter any problem during the development, see the FAQs.

For more information, please click the following links:

  1. Development Guide
  2. API Reference

You can download the source code in github.com/Huawei/Consumer/tree/master/Codelabs/ScanKit-CustomizedView

You can also click the button below to download the source code.

Download full source code

Code copied