Integration Of Huawei Account Kit, Ads Kit and Scan Kit in Student Attendance Application in Android.

Thyfanney David
7 min readOct 10, 2021

--

Overview

Student Attendance application is an application that allows students to scan the QR code to take their attendance. This application is developed for the purpose of making recording attendance easier for both lecturers and students. In this article, we will show you the integration of Huawei Kits in the Student Attendance application that we had developed. In this application, we had integrated account kit, ads kit and scan kit.

Preparation

1) Register as a Huawei Developer and ensure your account is verified in order to use the HMS core kits.

2) Create an app in the AppGallery Connect.

3) Generate an SHA-256 certificate fingerprint for the application you are developing.

4) In the Manage APIs section, enable the required kits. (Account kit, Ads kit and Scan kit)

5) Download the agconnect-services.json file from App Information, copy and paste in your android project under application directory.

Integration:

1)In android studio, under build.gradle file, copy and paste the following code.

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.huawei.agconnect:agcp:1.5.0.300'
}
}

task clean(type: Delete) {
delete rootProject.buildDir

2) In the settings.gradle file for the project, add the following code.

dependencyResolutionManagement {

repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

repositories {

google()

mavenCentral()

jcenter() // Warning: this repository is going to shut down soon

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

}

}

3) Next, under application directory, in the build.gradle file, add the plugins and dependencies below. The versions may vary for each dependencies, therefore, you may refer to the https://developer.huawei.com/consumer/en/hms to get the latest versions of account kit, ads kit and scan kit provided.

plugins {

id 'com.android.application'

id 'com.huawei.agconnect'
}
dependencies {

implementation 'androidx.appcompat:appcompat:1.3.1'

implementation 'com.google.android.material:material:1.4.0'

implementation 'androidx.constraintlayout:constraintlayout:2.1.1'

testImplementation 'junit:junit:4.13.2'

androidTestImplementation 'androidx.test.ext:junit:1.1.3'

androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.huawei.hms:hwid:6.1.0.302'

implementation 'com.huawei.hms:ads-lite:13.4.47.302'

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

}

4) Sync the gradle file.

5) Next, in the AndroidManifest.xml, copy and paste the following code.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="MUSampleAccountApp.miki.com">

<!--check network permissions-->

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!--check wifi state-->

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<uses-permission android:name="android.permission.INTERNET" />

<uses-permission android:name="android.permission.CAMERA" />

<!--Read file permission-->

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<!--Using Features-->

<uses-feature android:name="android.hardware.camera" />

<uses-feature android:name="android.hardware.camera.autofocus" />

Implementation of Huawei Kits :

1) Integration of Huawei Account Kit and Ads Kit.

In this application, the user should be able to sign in using their Huawei Id and sign out by clicking the “Sign Out” button on the bottom of the screen. The type of ads format used in this application is a banner ads. The banner ads should appear on top of the screen. Below is the code for this function.

// AccountAuthService provides a set of APIs, including silentSignIn, getSignInIntent, and signOut.

private AccountAuthService mAuthService;



// Set HUAWEI ID sign-in authorization parameters.

private AccountAuthParams mAuthParam;



// Define the request code for signInIntent.

private static final int REQUEST_CODE_SIGN_IN = 1000;

private static final int DEFAULT_VIEW = 0x22;

private static final int REQUEST_CODE_SCAN = 0x01;

// Define the log flag.

private static final String TAG = "Account";

HuaweiIdAuthButton huaweiIdAuthButton;

private Button btn_signout;

TextView my_textView;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

huaweiIdAuthButton = findViewById(R.id.HuaweiIdAuthButton);

huaweiIdAuthButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

silentSignInByHwId();
}
});

btn_signout = findViewById(R.id.btn_signout);

btn_signout.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

signout();
}

});
}

private void silentSignInByHwId() {

// 1. Use AccountAuthParams to specify the user information to be obtained, including the user ID (OpenID and UnionID), email address, and profile (nickname and picture).

// 2. By default, DEFAULT_AUTH_REQUEST_PARAM specifies two items to be obtained, that is, the user ID and profile.

// 3. If your app needs to obtain the user's email address, call setEmail().

// 4. To support ID token-based HUAWEI ID sign-in, use setIdToken(). User information can be parsed from the ID token.

mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)

.setEmail()

.setIdToken()

.createParams();

// Use AccountAuthParams to build AccountAuthService.

mAuthService = AccountAuthManager.getService(this, mAuthParam);

// Sign in with a HUAWEI ID silently.

Task<AuthAccount> task = mAuthService.silentSignIn();

task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {

@Override

public void onSuccess(AuthAccount authAccount) {

// The silent sign-in is successful. Process the returned AuthAccount object to obtain the HUAWEI ID information.

dealWithResultOfSignIn(authAccount);
}
});

task.addOnFailureListener(new OnFailureListener() {

@Override

public void onFailure(Exception e) {

// The silent sign-in fails. Your app will call getSignInIntent() to show the authorization or sign-in screen.

if (e instanceof ApiException) {

ApiException apiException = (ApiException) e;

Intent signInIntent = mAuthService.getSignInIntent();

startActivityForResult(signInIntent, REQUEST_CODE_SIGN_IN);

}
}
});
}

/**

* Process the returned AuthAccount object to obtain the HUAWEI ID information.

*

*
@param authAccount AuthAccount object, which contains the HUAWEI ID information.

*/

private void dealWithResultOfSignIn(AuthAccount authAccount) {

Log.i(TAG, "idToken:" + authAccount.getIdToken());

Log.i(TAG, "Name:" + authAccount.getDisplayName());

Log.i(TAG, "Email:" + authAccount.getEmail());

// TODO: After obtaining the ID token, your app will send it to your app server if there is one. If you have no app server, your app will verify and parse the ID token locally.

huaweiIdAuthButton.setVisibility(View.GONE);

btn_signout.setVisibility(View.VISIBLE);

my_textView = findViewById(R.id.my_textView);

my_textView.setText(" Hi " + authAccount.getDisplayName() + " you successfully sign in");



//Banner Ads Code Start here

ConstraintLayout constraintLayout = findViewById(R.id.ad_frame);

BannerView bannerView = new BannerView(this);

bannerView.setAdId("testw6vs28auh3");

bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_360_57);

constraintLayout.addView(bannerView);

bannerView.setBannerRefresh(30);

// Create an ad request to load an ad.

AdParam adParam = new AdParam.Builder().build();

bannerView.loadAd(adParam);

//Banner Ads Code End here

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_CODE_SIGN_IN) {

Log.i(TAG, "onActivityResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);

Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);

if (authAccountTask.isSuccessful()) {

// The sign-in is successful, and the authAccount object that contains the HUAWEI ID information is obtained.

AuthAccount authAccount = authAccountTask.getResult();

dealWithResultOfSignIn(authAccount);

Log.i(TAG, "onActivityResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);

} else {

// The sign-in fails. Find the failure cause from the status code. For more information, please refer to the "Error Codes" section in the API Reference.

Log.e(TAG, "sign in failed : " + ((ApiException) authAccountTask.getException()).getStatusCode());
}
}

if (resultCode != RESULT_OK || data == null) {

return;

}
if (requestCode == REQUEST_CODE_SCAN) {

Object obj = data.getParcelableExtra(ScanUtil.RESULT);

if (obj instanceof HmsScan) {

if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {

Toast.makeText(this, ((HmsScan) obj).getOriginalValue(), Toast.LENGTH_SHORT).show();

}
return;
}
}
}

private void signout() {

Task<Void> signOutTask = mAuthService.signOut();

signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {

// Processing after the sign-out.

Log.i(TAG, "signOut complete");

my_textView.setText("You Successfully Sign Out");

huaweiIdAuthButton.setVisibility(View.VISIBLE);

btn_signout.setVisibility(View.GONE);

btn_scan.setVisibility(View.GONE);
}
});
}

2) Integration of Huawei Scan Kit.

To implement the scan kit, we can build a button so that user can interact with the button to use the scan kit. Below is the code for the button.

btn_scan = findViewById(R.id.btn_scan);

btn_scan.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

scanit();
}
});

In the OnActivityResult, on the MainActivity.java file, copy and paste the following code.

if (resultCode != RESULT_OK || data == null) {

return;
}

if (requestCode == REQUEST_CODE_SCAN) {

Object obj = data.getParcelableExtra(ScanUtil.RESULT);

if (obj instanceof HmsScan) {

if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {

Toast.makeText(this, ((HmsScan) obj).getOriginalValue(), Toast.LENGTH_SHORT).show();

}
return;
}

}

Below is the code in order for the button to work and use the scan kit.

private void scanit() {

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

this.requestPermissions(

new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},

DEFAULT_VIEW);
}

huaweiIdAuthButton.setVisibility(View.GONE);

btn_signout.setVisibility(View.VISIBLE);

btn_scan.setVisibility(View.VISIBLE);
}


@Override

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {

return;
}


if (requestCode == DEFAULT_VIEW) {

//After applying for permission, call the DefaultView scan code interface

ScanUtil.startScan(MainActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());

}

}

Output

User Interface for Student Attendance Application in Android
User Interface shown when the user successfully signed in the application
Camera scanner without the light
Camera scanner with light
User Interface shown when the user has log out the application

Conclusion

In this article, we have learned how to integrate Huawei Account kit, Ads kit and Scan kit in a simple student attendance application. The idea behind the development of this application is, student’s attendance should be able to be recorded easily via scanning the qr code using scan kit in this application. During the development of this application, Mekhi has taken the role of integrating the 3 kits, Syafiqah has taken the role of making the application prettier and Thyfanney is in charge of the article. Finally, there are definitely plenty of improvements can be done on this application and one of them is by developing a more user-friendly UI design to ease user’s navigation through the application as well as implementing more functions. Last but not least, we would also like to thank Mr. Nithin for all the lessons and guidance given throughout this HMS course.

--

--