Integration of HMS Account Kit and Ads Kit in My QR Code
Hi guys. In this article, I would like to share how I integrate HMS Account Kit and Ads Kit in my application.
Do you guys know what QR Code is? QR stands for “Quick Response.” While they may look simple, QR codes are capable of storing lots of data. But no matter how much they contain, when scanned, the QR code should allow the user to access information instantly, hence why it is called a Quick Response code.
In this project, My QR Code is focused on generating and scanning QR Code. This system will help people to generate QR code by adding some text and simply clicking the generate code button. Other than that, people can also scan QR Code by tapping the Scan QR Code button.
Basic features of My QR Code
A simple QR Code generator and scanner that provide features for you to generate and scan QR Code.
Huawei Kit in the Application
1. Account Kit
By applying Account Kit in this application, users can quickly and conveniently sign in to the apps with their HUAWEI IDs. When signing in to an app using a HUAWEI ID for the first time, a user needs to authorize the app. Then, the user can sign in to the app with one tap.
2. Ads Kit
Huawei Ads Kit provides unique advertising IDs that enable developers to operate easily with third-party advertising and tracking platforms while safeguarding user privacy for high-quality and targeted adverts in app.
Link to the Application
Development Environment
Android Studio
JDK version : 1.8 or later
SDL and Gradle:
- Multiple HMS Core Kits
- Performance: Wi-Fi networking, EMUI 10.1.0(P30 Pro), /EMUI 11.0.0(P40 Pro). Multilingual environment.
Prerequisite:
- Register to Huawei Developers to access HMS Core Kits
- Go to AppGallery Connect and create a project.
- Create SHA-256 Key for application
- Go to Manage API section and be sure to allow the required kit (Account Kits)
- Download and paste the agconnect.json file in the application under App Folder.
- To get the Ads, go to Publisher Service, click My Apps then click Add app and enter some information needed by Huawei.
Integration
1. In the project level of build.gradle, use this following code:
buildscript {
repositories {
google()
jcenter()
maven { url ‘https://developer.huawei.com/repo/' }
}dependencies {
classpath “com.android.tools.build:gradle:7.0.0”
classpath ‘com.huawei.agconnect:agcp:1.5.2.300’
classpath ‘com.huawei.agconnect:agcp:1.6.0.300’
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {url ‘https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
mlVersionCode = ‘1’
mlVersionName = ‘1.0’
}
if (null != System.getenv(‘mlVersionCode’) && (!System.getenv(‘mlVersionCode’).isEmpty())) {
ext.mlVersionCode = System.getenv(‘mlVersionCode’)
}
if (null != System.getenv(‘mlVersionName’) && (!System.getenv(‘mlVersionName’).isEmpty())) {
ext.mlVersionName = System.getenv(‘mlVersionName’)
}
apply plugin: ‘com.huawei.agconnect’
2. In the app level build.gradle, use this following code
plugins {
id ‘com.android.application’
id ‘com.huawei.agconnect’
}
android {
compileSdk 31
defaultConfig {
applicationId “com.example.myqrcode”
minSdk 21
targetSdk 31
versionCode rootProject.ext.mlVersionCode as int
versionName rootProject.ext.mlVersionName
testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
aaptOptions {
noCompress “tflite”, “mnn”, “cambricon”
cruncherEnabled false
useNewCruncher false
}
repositories {
flatDir {
dirs ‘libs’
}
}
}
dependencies {
implementation ‘androidx.appcompat:appcompat:1.3.1’
implementation ‘com.google.android.material:material:1.4.0’
implementation ‘androidx.constraintlayout:constraintlayout:2.1.0’
implementation ‘com.huawei.agconnect:agconnect-core:1.5.2.300’
implementation ‘androidmads.library.qrgenearator:QRGenearator:1.0.3’
implementation ‘com.huawei.hms:ads:3.4.47.302’
implementation ‘com.huawei.hms:hwid:6.0.1.300’
implementation (‘eu.livotov.labs.android:CAMView:2.0.1@aar’) {transitive=true}
testImplementation ‘junit:junit:4.+’
androidTestImplementation ‘androidx.test.ext:junit:1.1.3’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.4.0’
}
apply plugin: ‘com.huawei.agconnect’
3. In the settings.gradle, paste this code
dependencyResolutionManagement {
repositories {
google()
jcenter()
maven {url ‘https://developer.huawei.com/repo/'}
}
}
rootProject.name = “My QR Code”
include ‘:app’
4. In proguard-rules.pro under Gradle Scripts, copy and paste this code.
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keepattributes SourceFileLineNumberTable
-keep class com.hianalytics.android.**{*;}
5. In Android Manifest, add some permission needed
<uses-permission android:name=”android.permission.CAMERA” />
<uses-permission android:name=”android.permission.VIBRATE” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
<uses-permission android:name=”android.permission.ACCESS_WIFI_STATE” />
<uses-permission android:name=”android.permission.INTERNET” />
Account Kit Integration
First, you need to add the Huawei sign in button in the layout file before starting the integration.
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:id=”@+id/HuaweiIdAuthButton”
android:layout_width=”250dp”
android:layout_height=”wrap_content”
android:layout_alignParentStart=”true”
android:layout_alignParentEnd=”true”
android:layout_alignParentBottom=”true”
android:layout_marginStart=”79dp”
android:layout_marginEnd=”82dp”
android:layout_marginBottom=”185dp”
app:layout_constraintBottom_toBottomOf=”parent”
app:layout_constraintEnd_toEndOf=”parent”
app:layout_constraintStart_toStartOf=”parent”
app:layout_constraintTop_toTopOf=”parent” />
Next, copy and paste the below code in your activity class
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());
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”);}
@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()) {
AuthAccount authAccount = authAccountTask.getResult();
dealWithResultOfSignIn(authAccount);
Log.i(TAG, “onActivityResult of sigInInIntent, request code: “ + REQUEST_CODE_SIGN_IN);
} else {
Log.e(TAG, “sign in failed : “ + ((ApiException) authAccountTask.getException()).getStatusCode());
}
}
}
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);
}
});
Ads Kit Integration
Remember to add the BannerView to the XML layout file, and set hwads:adId to the ad unit ID and hwads:bannerSize to ad dimensions :
<com.huawei.hms.ads.banner.BannerView
android:id=”@+id/hw_banner_view”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
hwads:adId=”testw6vs28auh3"
hwads:bannerSize=”BANNER_SIZE_360_57"/>
Copy and paste the following code :
import com.huawei.hms.ads.AdParam;
import com.huawei.hms.ads.BannerAdSize;
import com.huawei.hms.ads.HwAds;
import com.huawei.hms.ads.banner.BannerView;
HwAds.init(this);
BannerView bottomBannerView = findViewById(R.id.hw_banner_view);
AdParam adParam = new AdParam.Builder().build();
bottomBannerView.loadAd(adParam);
BannerView bannerView = new BannerView(this);
bannerView.setAdId(“testw6vs28auh3”);
bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_360_57);
RelativeLayout rootView = findViewById(R.id.root_view);
rootView.addView(bannerView);
Conclusion
In conclusion, Huawei HMS Core Kits did provide our developers with lots of benefits in our application development. Thank you to Huawei and the guidance from our wonderful mentors, I have truly learned a lot of knowledge and experience in this course. Hope you liked this article and I hope you found it very useful in achieving what you want to develop. If you have any questions, feel free to ask in the comment section :)
Reference
1. Account Kit Documentation:
2. Ads Kit Documentation: