Friend Share, A new way to add friends featuring Huawei Scan Kit

Sanghati Mukherjee
6 min readJul 17, 2020

--

HUAWEI Scan Kit scans and parses all major 1D and 2D barcodes and generates QR codes, helps us quickly to build barcode scanning functions into our apps.

Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and also to scan a very small barcode in the same way. It works even in sub-optimal 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.

Scan Kit Use Case

  1. Ordering Food
  2. View Product Information
  3. Making Payments
  4. Registering For Events
  5. Connecting to WiFi networks
  6. Adding Contacts
  7. Opening Websites
  8. Finding Location

Scan Kit 13 Formats Barcode

  1. EAN-8
  2. EAN-13
  3. UPC-A
  4. UPC-E
  5. Codabar
  6. Code 39
  7. Code 93
  8. Code 128
  9. ITF
  10. QR code
  11. Data Matrix
  12. PDF417
  13. Aztec

In this article we will learn how to generate QR Code and add our friends into our contact list using Huawei Scan Kit.

Prerequisite

  1. Must have a Huawei Developer Account
  2. Must have a Huawei phone with HMS 4.0.0.300 or later
  3. Must have a laptop or desktop with Android Studio , Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.

Things need to be done

  1. First we need to create a project in android studio.
  2. Get the SHA Key. For getting the SHA key, refer to this article.
  3. Create an app in the Huawei app gallery connect.
  4. Provide the SHA Key in App Information Section.
  5. Provide storage location.
  6. After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the json file in the app folder of the android project.
  7. Copy and paste the below class path inside the dependencies of buildscript (project build.gradle file)
classpath 'com.huawei.agconnect:agcp:1.3.1.300'

8. Copy and paste the below maven url inside the repositories of buildscript and allprojects (project build.gradle file)

maven {url 'http://developer.huawei.com/repo/'}

9) Copy and paste the below plugin in the app build.gradle file dependencies section.

implementation 'com.huawei.hms:scan:1.1.3.301'

10) If the project is using progaurd, copy and paste the below code in the progaurd-rules.pro file.

-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}

11) The HUAWEI Ads SDK requires the following permissions:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Now sync the app.

In this demo, user will login with Huawei Id. After that user will edit profile and save it to generate QR code. Once QR code is generated user can download or share the code to his/her friends to add him/her in user list using this app. Now, if user wants to add his/her friends, then user needs to get friends QR code and scan the code to add in his/her list.

How to generate QR code?

  1. Required content to generate QR code.
JSONObject objContent = new JSONObject();
objContent.put("name", edtName.getText().toString());
objContent.put("phone", edtPhone.getText().toString());
objContent.put("email", edtEmail.getText().toString());
objContent.put("image",Utility.getUserImage(this));
String content = objContent.toString();

2. Need to set width and height, and specify the barcode format.

int type = HmsScan.QRCODE_SCAN_TYPE;
int width = 500;
int height = 500;

3. Need to initialize HmsBuildBitmapOption and set optional parameters.

The optional parameters are as follows:

a) setBitmapBackgroundColor(): Set the background color of a barcode. If we do not call this API, white is used by default.

b) setBitmapColor(): Set the barcode color. If we do not call this API, black is used by default.

c) setBitmapMargin(): Set the border width of a barcode. If we do not call this API, the default border width 1 is used.

HmsBuildBitmapOption options = new HmsBuildBitmapOption.Creator()
.setBitmapBackgroundColor(Color.WHITE)
.setBitmapColor(Color.BLACK)
.setBitmapMargin(3).create();

4. Need to call the buildBitmap API to generate a barcode.

Bitmap qrBitmap = ScanUtil.buildBitmap(content, type, width, height, options);

In this way, we can generate QR code. After generating the code we can download or share to anyone to add you in their friend list.

How to Scan QR code?

In this article, Customized View mode is used in order to scan QR Code. In Customized View mode, we do not need to worry about developing the scanning process or camera control. Scan Kit will do all these tasks for us. However, we need to design the scanning UI.

  1. Need to create a XML layout where we will design our scanning UI.
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:my_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- customize layout needed by scankit for camera preview -->
<FrameLayout
android:id="@+id/rim"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C0C0C0"></FrameLayout>
<!-- customize back button view -->
<ImageView
android:id="@+id/back_img"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentStart="true"
android:layout_marginStart="12dp"
android:layout_marginTop="4dp"
android:gravity="center"
android:padding="12dp"
android:src="@drawable/back" />
<!-- customize scanning mask -->
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:alpha="0.1"
android:background="#FF000000" />

<!-- customize scanning viewfinder -->
<ImageView
android:id="@+id/scan_view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:background="@drawable/scanningframe" />
</RelativeLayout>

We also need a scanning frame in the middle and set that scanning frame as background in scan_view_finder image as shown in the above code.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="3dp" android:color="#e1ffff"/>
<solid android:color="#1f00BCD4"/>
<corners android:radius="5dip"/>
<padding
android:left="2dp"
android:top="2dp"
android:right="2dp"
android:bottom="2dp" />
</shape>

2. Create a ScaningActivity class and get screen density to calculate viewfinder’s rect. Here SCAN_FRAME_SIZE is 300.

DisplayMetrics dm = getResources().getDisplayMetrics();
float density = dm.density;

mScreenWidth = getResources().getDisplayMetrics().widthPixels;
mScreenHeight = getResources().getDisplayMetrics().heightPixels;

int scanFrameSize = (int) (SCAN_FRAME_SIZE * density);

3. Calculate viewfinder’s rect, it is 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;

4. Bind the camera preview screen to the remote view and set the scanning area. In the preview stream, Scan Kit recognizes only the image in the scanning area. To better magnify the captured image, it is recommended that the scanning box be placed in the middle of the screen and it can be slightly smaller than the scanning area.

Now, initialize RemoteView instance, and set calling back for scanning result. Set the barcode formats we want Scan Kit to support. Here we have used ALL_SCAN_TYPE as format. This format will support for all codes.

RemoteView 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) {
//judge the result is effective
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);
ScanningActivity.this.finish();
}
}
});

5. Add remoteView to framelayout.

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
FrameLayout frameLayout = findViewById(R.id.rim);
frameLayout.addView(remoteView, params);

6. Manage remoteView lifecycle.

@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();
}

7. Check for camera and storage permission.

@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) {
//start your activity for scanning barcode
this.startActivityForResult(new Intent(this, ScanningActivity.class), REQUEST_CODE_SCAN);
}

}

8. Create onActivityResult method in order to get result after QR code is scanned and save the result in a list.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//receive result after your activity finished scanning
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || data == null) {
return;
}
if (requestCode == REQUEST_CODE_SCAN) {
HmsScan hmsScan = data.getParcelableExtra(ScanningActivity.SCAN_RESULT);
if (hmsScan != null && !TextUtils.isEmpty(hmsScan.getOriginalValue())) {

try {
JSONObject jsonObj = new JSONObject(hmsScan.getOriginalValue());
ArrayList<Friends> friendList = new ArrayList<>();
friendList.add(new Friends(jsonObj.get("name").toString(),jsonObj.get("phone").toString(),jsonObj.get("email").toString(),jsonObj.get("image").toString()));
friendsHelper.insertAllFriends(friendList);
showList();
} catch (JSONException e) {
e.printStackTrace();
}

}
}
}

Result

GitHub

Coming Soon…

More Information, refer the following URLs:

  1. https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/service-introduction-0000001050041994
  2. https://developer.huawei.com/consumer/en/codelab/ScanKit/index.html#0

--

--

Sanghati Mukherjee