HUAWEI Game Service Implementation : Events - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Game service provides a centralized place for you to manage game services and configure metadata for authorizing and authenticating your game. Using Huawei game service, developer can access range of capabilities to help develop your games more efficiently.
Features
1. Developers can promote their game efficiently and quickly.
2. Developers can easily build the foundation of game by implementing features like achievements and events.
3. Developers can perform in-depth operations tailored to their game and their users.
In this article, we will implement event feature provided by Huawei game service in Tic tac toe game.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisites
1. Developer has created an application on App Gallery Connect. Follow Creating an App.
2. Integrating app gallery connect SDK. Please refer to AppGallery Connect Service Getting Started.
3. Developer has integrated Huawei Account kit. Follow this tutorial to integrate account kit.
4. HUAWEI mobile phone with HMS Core 4.0.0.300 or later installed.
Setup:
1. Enable Huawei Game service in Manage APIS. Please refer to Service Enabling.
2. Add appgallery connect plug-in in app-level build.gradle
Code:
apply plugin: 'com.huawei.agconnect'
3. Add following dependencies in app-level build.gradle and click on Sync Now and wait till synchronization is done.
Code:
dependencies {
implementation 'com.huawei.hms:base:4.0.4.301'
implementation 'com.huawei.hms:hwid:4.0.4.300'
implementation 'com.huawei.hms:iap:4.0.4.300'
implementation 'com.huawei.hms:game:4.0.3.301'
}
Initialization
Once Initial set up is done, let’s implement Huawei game service in Tic tac toe game
1. Add the following code in onCreate() method of Application class.
Code:
public class GameServiceApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
HuaweiMobileServicesUtil.setApplication(this);
}
@Override
public void onTerminate() {
super.onTerminate();
}
}
2. To initialize the game
Code:
private void init() {
JosAppsClient appsClient = JosApps.getJosAppsClient(this, null);
appsClient.init();
Log.i(TAG, "initialization success");
}
Signin In
1. When app is launched, Huawei sign-in page is displayed.
2. User enters Huawei Huawei ID and password to sign in.
3. After a successful sign in, the app obtains player information corresponding to Huawei ID.
Please refer to this article for sign in implementation.
Game Events
The Game events allow developer to collect specific data generated by players and store them on Huawei game server for AppGallery connect. In this article, we will collect data pertaining to player win. Every time players win the match, we will store it in Huawei game server.
Creating an Event in AppGallery Connect
1. Sign in to AppGallery Connect and select My apps.
2. Select an app from the app list to create an event.
3. Click the Operate tab and go to Products > Game Event. Click Create.
4. Configure the event information and click Save.
5. Check your event ID on the event list and properly save the ID for event development.
Implementation of Event
1. To initialize EventsClient instance
Code:
EventsClient client = Games.getEventsClient(this, mAuthHuaweiId);
mAuthHuaweiId is obtained during sign in.
2. To submit the event
Code:
client.grow(eventId, growAmount);
eventId indicates the ID of the event which is generated while defining the event in AppGallery connect. In our app we will submit the event everytime players win the match.
The growAmount parameter specifies an increment amount of the event value.
To Obtain Events
Following code can be used to obtain the events.
Code:
Task<List<Event>> task = client.getEventList(forceReload);
forceReload is a Boolean type used to indicate whether to obtain data stored on the Huawei game server or locally cached data.
Following code shows how list of events are returned.
Code:
task.addOnSuccessListener(new OnSuccessListener<List<Event>>() {
@Override
public void onSuccess(List<Event> data) {
if (data == null) {
Log.w("Event", "event is null");
return;
}
for (Event event : data) {
Log.i("Event", "event id:" + event.getEventId());
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
if (e instanceof ApiException) {
String result = "errorCode:"
+ ((ApiException) e).getStatusCode();
Log.e("Event", result);
}
}
});
We will show the retrieved events list in recyclerview. Clicking on event list item will show details about the events.
Code:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final Event event = eventList.get(position);
final String eventId = event.getEventId();
Glide.with(context).load(event.getThumbnailUri()).into(holder.eventImage);
holder.eventName.setText(event.getName());
holder.eventAmonut.setText("value:"+event.getValue() + "#" + event.getLocaleValue());
holder.eventDes.setText(event.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.onItemClick(position);
}
});
holder.eventReport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBtnClickListener.reportEvent(eventId);
}
});
}
Screenshots
​ Summary
In this article, we understood initial setup and game event features of Huawei Game Service. In next article, we will discuss more features provided by Huawei Game service.
Source code can be downloaded from https://github.com/DTSE-India-Community/Huawei-Game-Service

How many days it will take to get data reflected in AGC.

Related

Body Weight Exercise Application Using HMS Awareness Kit

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202333898987840045&fid=0101187876626530001
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Huawei Awareness Kit provides our application to obtain information such as current time, location, behavior, audio device status, ambient light, weather, and nearby beacons. Using this information we can get an advantage over user's current situation more efficiently and can manipulate data for better user experience.
In this article, we will use weather information using HMS Awareness Kit for manipulating warm up exercise for user.
Demo
In the above demo, the warm up exercise for user will get change according to the weather condition. Here the weather condition is divided into two parts:
1) Outdoor warm up exercise: When the weather condition is normal such as sunny or not raining, then the warm up exercise will get change to running.
2) Inside warm up exercise: When the weather condition is abnormal such as raining or snow fall, then the warm up exercise will get change to invisible jumping rope, burpee and squats.
By this way we are providing user a better experience without avoiding any exercise due to certain condition. It’s a win-win situation for developers to not to lose any user due to bad user experience.
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) Create a project in android studio.
2) Get the SHA Key. For getting the SHA key we can refer to this article.
3) Create an app in the Huawei AppGallery connect.
4) Enable awareness kit setting in Manage APIs section.
5) Provide the SHA Key in App Information Section.
6) Provide storage location.
7) 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.
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file):
Code:
maven { url ‘http://developer.huawei.com/repo/’ }
9) Enter the below plugin in the app build.gradle file:
Code:
apply plugin: ‘com.huawei.agconnect’
10) Enter the below HMS Push kit dependencies in the dependencies section:
Code:
implementation ‘com.huawei.hms:awareness:1.0.6.301’
11) Enter the below permission in android manifest file
Code:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
12) Now Sync the gradle.
Weather Awareness
It is used for providing weather information such as current day or next seven days weather information of a specific device location. It does not support barrier information or function.
Code:
public void sendWeatherId(){
Awareness.getCaptureClient(this).getWeatherByDevice()
.addOnSuccessListener(new OnSuccessListener<WeatherStatusResponse>() {
@Override
public void onSuccess(WeatherStatusResponse weatherStatusResponse) {
WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
List<HourlyWeather> hourlyWeather = weatherStatus.getHourlyWeather();
Utility.setWeatherId(getApplicationContext(),hourlyWeather.get(1).getWeatherId());
if(Utility.getWeatherId(getApplicationContext())!=0){
goToValidPage();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e("TAG", "get Hourly weather failed");
}
});
}
The above code is used to get the weather information such as sunny, rain, cloudy etc. Using this information we will manipulate the warm up exercise and show user the list of exercise.
getWeatherByDevice
This method is used to obtain the weather information using the current location of a device. There are some restriction using this method:
1) The total number of capture API calls every 5 seconds cannot exceed 20
2) The total number of capture API calls every hour cannot exceed 1000
3) This function is available only on device with API level 24 or later
4) ACCESS_FINE_LOCATION permission is needed in android manifest file.
WeatherStatus
This is the main API where we will fetch the weather id. Using this id we will manipulate the exercise. This API contain five methods:
1) getAqi()
2) getWeatherSituation()
3) getDailyWeather()
4) getHourlyWeather()
5) getLiveInfo()
Here we will use getHourlyWeather to obtain weather information in the next 24 hours. The information will fetch weather ID, time, temperature and rainfall probability.
Opening YouTube Video in HMS devices
Code:
public static void watchYoutubeVideo(Context context, String id){
try {
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + id));
context.startActivity(webIntent);
} catch (ActivityNotFoundException ex) {
}
}
The Id here is YouTube Id.
CountDownTime
As the name implies to counts down the time specified in milliseconds.
Code:
mCountDownTimer = new CountDownTimer(TIMER_DURATION, TIMER_INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
txtTimer.setText("00:"+(millisUntilFinished / 1000 < 10 ? "0"+ millisUntilFinished / 1000 : String.valueOf(millisUntilFinished / 1000)));
mTimeRemaining = millisUntilFinished; // Saving timeRemaining in Activity for pause/resume of CountDownTimer.
}
@Override
public void onFinish() {
mCountDownTimer.cancel();
Intent intent = new Intent(ReadyActivity.this, CurrentWorkoutActivity.class);
startActivity(intent);
finish();
}
}.start();
Timer
In case user go for run we need to have a timer to capture the duration of its completion.
Code:
private void timer (){
Timer timer = new Timer();
countTimer = 0;
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
String s_time = String.format("%02d:%02d:%02d",
countTimer / 3600,
(countTimer % 3600) / 60,
countTimer % 60);
System.out.println("TIMER >>>" + s_time);
txtTimer.setText(s_time);
if (!pauseTimer) countTimer++;
}
});
}
}, 1000, 1000);
}
What we learn?
We learn how to manipulate data using HMS Weather Awareness Kit and also situation where we need the most.
GitHub
Very soon I am going to post the entire code on GitHub. So come back again to check it out.
For more reference
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/service-introduction-0000001050031140-V5
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/weather-awareness-0000001050121038-V5

AppGallery Auth service using Mobile Number [Android]

More information like this, you can visit HUAWEI Developer Forum​
Article Introduction
The following article describes the easiest way to obtain easy, secure, and efficient mobile phone number registration & sign-in using the AppGallery Auth service.
AppGallery Auth Service Introduction
AppGallery Connect provides a cloud-based auth service and SDKs to help you quickly build a secure and reliable user authentication system for your apps to verify user identity.
The AppGallery Connect auth service supports multiple authentication methods and is seamlessly integrated with other Serverless services to help you secure user data based on simple rules that you have defined.
In this article, we will cover just the mobile number authentication method in Android.
Integrating the Auth Service SDK
Before start using the AppGallery Auth Service, we must first integrate the Auth Service SDK by following the steps below :
Step 1:
Create an app in AppGallery Connect and integrate the AppGallery Connect SDK into your app. For details, please refer to AppGallery Connect Service Getting Started.
Step 2:
Add the Auth Service dependencies in the build.gradle file in the app directory (usually app/build.gradle).
Code:
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
Enabling Auth Service
we must also enable the Auth Service in AppGallery Connect by following the steps below :
Step 1:
Sign in to AppGallery Connect and select My projects.
Step 2:
Find your project from the project list and click the app for which you need to enable Auth Service on the project card.
Step 3:
Go to Build > Auth Service. If it is the first time that you use Authe Service, click Enable now in the upper right corner.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 4:
Click Enable in the row of Mobile number authentication mode to be enabled.
Step 5: (optional)
Configure the SMS template which supports multilingual configuration: Auth Service > settings > Verification code and notification template settings.
Coding
There're five major client-side methods:
SendOTP.
SignUp.
SignIn.
Get the current user.
SignOut.
SendOTP:
Used to apply for verification code for mobile number +[countryCode][phoneNumber]
Code:
private void sendOTP(){
VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
.action(ACTION_REGISTER_LOGIN) //ACTION_REGISTER_LOGIN/ACTION_RESET_PASSWORD
.sendInterval(30) // Minimum sending interval, which ranges from 30s to 120s.
.locale(Locale.getDefault()) // Optional. It indicates the language for sending a verification code.
.build();
Task<VerifyCodeResult> task = PhoneAuthProvider.requestVerifyCode(countryCode, phoneNumber, settings);
task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
@Override
public void onSuccess(VerifyCodeResult verifyCodeResult) {
// The verification code application is successful.
Log.i(TAG, "onSuccess: "+verifyCodeResult.toString());
}
}).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure: ");
}
});
}
SignUp:
Used to register a new user using a mobile number +[countryCode][phoneNumber]
Code:
private void signUp(){
PhoneUser phoneUser = new PhoneUser.Builder()
.setCountryCode(countryCode)//ex: 212
.setPhoneNumber(phoneNumber)//ex: 698841421
.setVerifyCode(OTP)//OTP sent via the sendOTP() method
.setPassword(null)
.build();
AGConnectAuth.getInstance().createUser(phoneUser)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
Log.i(TAG, "onSuccess SignUp: "+signInResult.toString());
// The user is registered and you can add any logic you want
// After that, the user has signed in by default.
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure SignUp: "+e.getMessage());
// there's an issue (the user already registered ...)
}
});
}
Note 1: Before registering the User, he must obtain the OTP using the sendOTP() method above.
Note 2: After the registration is successful, the user signs in automatically. no need to call the SignIn method.
Note 3: If the user is already registered, the onFailureListener will be triggered.
SignIn:
Used to sign-in the user after obtaining his credential from the AppGallery Connect server.
Code:
private void SignIn(){
AGConnectAuthCredential credential = PhoneAuthProvider.credentialWithVerifyCode(countryCode, phoneNumber, null , OTP);
AGConnectAuth.getInstance().signIn(credential)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// Obtain sign-in information.
Log.i(TAG, "onSuccess: login"+signInResult.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "onFailure: login"+e.getMessage());
}
});
}
Note: Before logging in, the user must obtain the OTP using the sendOTP() method above.
Get the current user:
This method is used to get the currently signed-in user.
Code:
private AGConnectUser getCurrentUser(){
return AGConnectAuth.getInstance().getCurrentUser();
}
SignOut:
This method is used to sign-out the currently signed-in user.
Code:
private void signOut(){
if(getCurrentUser()!=null)
AGConnectAuth.getInstance().signOut();
}
References
AppGallery Auth Service:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-auth-service-introduction
Conclusion
Integrating the AppGallery Auth service is the right choice to allow users to use mobile phone numbers to connect to your application securely, easily, and efficiently, without wasting much time and effort building the Auth functionality from scratch.
How to handle region based mobile numbers.
How can I implement a smart lock for passwords?
Thank you very much
Excellent guide, very intuitive, truly detailed and with all the information needed
How much time it takes for OTP to expire?
How much time it will take to integrate service completely ?
Interesting feature. It seems easy to integrate it.
Interesting, excellent guide

Make Users to Update Your Application with HMS

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
AppGalleryKit App and AppGalleryKit Game services allows to jointly operate the apps with Huawei and share revenue generated in the process. Developer will have access to Huawei’s diverse services including HUAWEI AppGallery connection, data reports, activity operations, and user operations to obtain more premium HUAWEI AppGallery resources in order to promotion purposes.
To enable AppGalleryKit App or AppGalleryKitGame operations, you need to sign the HUAWEI AppGallery Connect Distribution Service Agreement For Paid Apps with Huawei. For details about the joint operations process, please refer to Joint Operations Services at a Glance.
AppGalleryKit App and AppGalleryKit Game is a product concept derived from Account, Analytics, In-App Purchases and other kits. With AppGalleryKit App or AppGalleryKit Game, initializing the app, updating the app, implementing Account Kit is optional. But it is necessary to implementing In-App Purchases kit to use AppGalleryKit App or AppGalleryKit Game. Also it is advised that use Analytics Kit, Auth Service, Crash Service, A/B Testing and APM.
AppGalleryKitApp or AppGalleryKitGame is not pure kit integration. It is required for developers to sign AppGalleryKitApp or AppGalleryKitGame related agreements and they are derived from many features.
Initiliazing app, updating the app, Account Kit and In-App Purchases can be implemented seperately. These kits do not depend on AppGalleryKitApp or AppGalleryKitGame. But AppGalleryKitApp or AppGalleryKitGame depends on these kits.
Although we are not going to use AppGalleryKitApp or AppGalleryKit game, we can still use the update status of the application. In this article, we will check if there is an update in a demo app. Of course due to this app will not be in AppGallery market, there will not any update required.
In order to use this feature, first HMS Core is needed to be integrated to the project.
You can click this link to integrate HMS Core to your project.
Adding Dependency
After HMS Core is integrated, app-service library needs to be implemented.
Code:
implementation 'com.huawei.hms:appservice:{version}' // Currently version is 5.0.4.302
We will create a checkUpdate method and use it in onCreate. JosApps.getAppUpdateClient method, AppUpdateClient instance will be obtained. This object provides the methods related to app update. checkAppUpdate method, checks for app updates after the app is launched and initialized.
Java:
private void checkUpdate(){
AppUpdateClient client = JosApps.getAppUpdateClient(this);
client.checkAppUpdate(this, new UpdateCallBack(this));
}
We need to create a static class which is UpdateCallBack and it will implement CheckUpdateCallBack. CheckUpdateCallBack returns a result for checking for app updates. It requires onUpdateInfo, onMarketInstallInfo, onMarketStoreError and onUpdateStoreError methods are implemented.
in onUpdateInfo method, we can get status code, fail code, fail reason and other informations.
For more information you can click this link.
Code:
private static class UpdateCallBack implements CheckUpdateCallBack {
private final WeakReference<MainActivity> weakMainActivity;
private UpdateCallBack(MainActivity mainActivity) {
this.weakMainActivity = new WeakReference<>(mainActivity);
}
public void onUpdateInfo(Intent intent) {
if (intent != null) {
MainActivity mainActivity = null;
if (weakMainActivity.get() != null){
mainActivity = weakMainActivity.get();
}
int status = intent.getIntExtra(UpdateKey.STATUS, 100);
int rtnCode = intent.getIntExtra(UpdateKey.FAIL_CODE, 200);
String rtnMessage = intent.getStringExtra(UpdateKey.FAIL_REASON);
Serializable info = intent.getSerializableExtra(UpdateKey.INFO);
if (info instanceof ApkUpgradeInfo && mainActivity != null ) {
AppUpdateClient client = JosApps.getAppUpdateClient(mainActivity);
//Force Update option is selected as false.
client.showUpdateDialog(mainActivity, (ApkUpgradeInfo) info, false);
Log.i("AppGalleryKit", "checkUpdatePop success");
}
if(mainActivity != null) {
//status --> 3: constant value NO_UPGRADE_INFO, indicating that no update is available.
Log.i("AppGalleryKit","onUpdateInfo status: " + status + ", rtnCode: "
+ rtnCode + ", rtnMessage: " + rtnMessage);
}
}
}
@Override
public void onMarketInstallInfo(Intent intent) {
//onMarketInstallInfo
}
@Override
public void onMarketStoreError(int i) {
//onMarketStoreError
}
@Override
public void onUpdateStoreError(int i) {
//onUpdateStoreError
}
}
In this example, due to we do not have the application released in the market, we got a status code which is equal to 3. This indicates that for the application there is no upgrade needed.
For all status codes, you can check the below image.
For more details, you can check AppGalleryKit App and AppGalleryKit Game development guide links in reference section. Also you can download this demo application from the Github link.
Reference
AppGalleryKit App
AppGalleryKit Game
Github

【Integration Guide】 HUAWEI Account Kit Demo

In the previous post, we learned the advantages of Account Kit: one-click sign-in authorization in any scenario, secure and reliable services, and convenient integration, as well as giving apps access to the global HUAWEI ID base of potential users. A QR code is also provided at the end of the post for you to download the demo app to experience HUAWEI ID sign-in authorization. The demo has integrated three Account Kit APIs (four in total), and is easy to develop. In this article, we'll show you the demo development to get you familiar with Account Kit.
Before you start, use a browser to scan the QR code below to try the demo app.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
(Note: The app may collect relevant information for user statistics.)
Preparing for Demo Development​l Install Android Studio 3.5 or later.
l Install JDK 1.8 or later.
l Use SDK Platform 19 or later.
l Use Gradle 4.6 or later.
l If you haven't already, register as a developer on HUAWEI Developers.
l Download the sample code of the demo from GitHub.
Configuring the Running Environment (2 minutes)​1. Use Android Studio to open the demo project.
2. Go to File > Settings > Plugins > Marketplace, enter HMS Toolkit in the search box, and click Install. Note: HMS Toolkit must be version 5.2.0.300 or later.
For details, please refer to Installing HMS Toolkit.
3. Create a package and rename it to something like com.hxb.account in the project. Then, copy the code in the com.huawei.hms.accountsample package to your package, and change the value of package and applicationId to your package name. (Do not use the existing package name in the demo project because it is already registered on HUAWEI AppGallery.)
First, create a package. Move the MainActivity class to your package so that you can search for related files easily during the build.
Change package in the AndroidManifest.xml file to com.hxb.account.
Change applicationId in the build.gradle file to com.hxb.account.
4. Go to HMS > Configuration Wizard to check the environment configuration. If you have not signed in with a HUAWEI ID, Toolkit will first prompt you to do so.
On the Configuration Wizard page displayed, you are prompted that no app corresponding to the package name was detected under the signed-in HUAWEI ID.
Click Link to go to AppGallery Connect and create an app manually:
(a) Click Release.
(b) Click Add project.
(c) Create a project.
(d) Click Add app.
(e) Add the project.
After creating, go back to the Configuration Wizard page and click Retry. This time, the check will be successful.
5. Choose Account Kit.
On the Configuration Wizard page, click Add Kits and choose Account Kit.
The following page will be displayed.
6. Choose a certificate. You can choose Use Android debug certificate and click Generate to generate a certificate fingerprint, as shown in the following figure.
7. Click Next to automatically complete other configurations including toggling on the Account Kit switch in AppGallery Connect, configuring the signing certificate fingerprint, downloading the agconnect-services.json file to the project directory, configuring obfuscation scripts, and adding build dependencies and APK fingerprint required for integrating the Account SDK to the build.gradle file. Once these configurations are completed, the following page will be displayed. If you run into errors, please refer to the corresponding guide on the page.
Packaging and Testing the Demo on Remote Real Device Provided by Toolkit​After configuration, go to HMS > Cloud Debugging to package and test the demo app.
Select the desired device model.
Click Run to test the demo app.
Key Code for Demo Development​1. UI Design
Account Kit provides four main APIs for signing in, silently signing in, revoking authorization, and signing out. The demo app integrates the first three.
In the above figure, the Sign in with HUAWEI ID button is created with an encapsulated standard control. Please follow HUAWEI ID Sign-In Button Usage Rules when using the icon elements provided by Huawei.
Code:
<p style="line-height: 1.5em;"><com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android
:layout_width
="wrap_content"
android
:layout_height
="wrap_content"
/>
1. Key Code for APIs
(1) Sign-in
Use case: Account Kit, compliant with OAuth 2.0 and OpenID Connect, supports sign-in in two modes: authorization code (for apps with their own servers only) and ID token modes. Select the mode you need.
Code:
private void signIn() {
mAuthParam = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.createParams();
mAuthManager = AccountAuthManager.getService(AccountActivity.this, mAuthParam);
startActivityForResult(mAuthManager.getSignInIntent(), Constant.REQUEST_SIGN_IN_LOGIN);
}
As shown, setIdToken() means use the ID token mode for authorization. The other mode will show setAuthorizationCode() instead. Their difference will be described later. getSignInIntent() is the API for ID sign-in authorization.
Process the result after authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constant.REQUEST_SIGN_IN_LOGIN) {
// Successful sign-in.
// Obtain user information through parseAuthResultFromIntent.
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
AuthAccount authAccount = authAccountTask.getResult();
Log.i(TAG, authAccount.getDisplayName() + " signIn success ");
Log.i(TAG, "AccessToken:\n" + authAccount.getAccessToken());
Log.i(TAG, "OpenId:\n" + authAccount.getOpenId());
Log.i(TAG, "Email:\n" + authAccount.getEmail());
Log.i(TAG, "UnionId:\n" + authAccount.getUnionId());
// Download avatar by using AsyncTask.
NetService = new NetService(new URLPostHandler() {
@Override
public void PostHandler(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
textView.setText(authAccount.getDisplayName());
}
});
netService.execute(authAccount.getAvatarUriString());
} else {
Log.i(TAG, "signIn failed: " + ((ApiException)
authAccountTask.getException()).getStatusCode());
}
}
}
(2) Silent sign-in
Use case: Authorization is required only on first sign-in to your app using a HUAWEI ID. Subsequent sign-ins using the same HUAWEI ID do not require any authorization.
Code:
private void silentSignIn() {
Task<AuthAccount> task = mAuthManager.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthAccount>() {
@Override
public void onSuccess(AuthAccount authAccount) {
Log.i(TAG, "silentSignIn success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// If failed, use getSignInIntent.
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
signIn();
}
}
});
}
Call silentSignIn() to implement silent sign-in.
(3) Authorization revoking
Use case: To improve privacy security, users can unauthorize your app.
Code:
private void cancelAuthorization() {
Task<Void> task = mAuthManager.cancelAuthorization();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
imageView.setImageDrawable(null);
textView.setText("");
Log.i(TAG, "cancelAuthorization success");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.i(TAG, "cancelAuthorization failure:" + e.getClass().getSimpleName());
}
});
}
Call cancelAuthorization() to revoke authorization.
For more information about Account Kit, please visit:
l Development guide
l Codelab
l Video course (and the course for HMS Core 4.0.)
For more details, you can go to:
Our official website
Demo of Analytics Kit
Android SDK integration documentation
iOS SDK integration documentation
Web SDK integration documentation
Quick app SDK integration documentation
Checkout in forum

Integration of Huawei Account Kit and Analytics Kit in Android App KnowMyBoard Part -1

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we will learn how to integrate the Huawei Account kit and Analytics kit in KnowMyBoard application. This is the first part of the application where, we are using Huawei Account kit for user login and Analytics kit for analysis and custom events for application usage and behaviour. You may expect second part soon, where we are using Huawei Location kit and ML kit.
Huawei Account kit provides simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts details and wait for authorization. user can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their Huawei IDs.
Supported Devices
Huawei Analytics kit is a one-stop user behaviour analysis platform for products such as mobile apps, web apps, quick apps, quick games, and mini-programs. It offers scenario-specific data collection, management, analysis, and usage, helping enterprises achieve effective user acquisition, product optimization, precise operations, and business growth.
It is a one-stop digital, intelligent data analysis platform tailored to meet the needs of enterprises cross-departmental and cross-role personnel.
Supported Devices
Development Overview
You need to install Android Studio IDE and I assume that you have prior knowledge about the Android application development in java.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
Android phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software
HMS Core (APK) 4.X or later.
Integration process
Step 1: Create android project.
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
[/B][/B]
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.hms:hwid:6.4.0.301'
implementation 'com.huawei.hms:hianalytics:6.4.1.302'
[B][B]
Root level gradle dependencies
[/B][/B][/B]
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
[B][B][B]
Step 3: Add the below permissions in Android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Step 4: Create project and configure app in AppGallery.
Step 5: Download and add agconnect-services.json file in app directory of project.
Let's start coding
MainActivity.java
[/B]
public class MainActivity extends AppCompatActivity {
LoginViewModel loginViewModel;
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.setActivity(this);
// Enable SDK log recording.
HiAnalyticsTools.enableLog();
MyApplication.getAnalyticsInstance().setUserProfile("UserName","Test123");
loginViewModel = new LoginViewModel(getApplication());
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setLoginViewModel(loginViewModel);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
AuthAccount authAccount = authAccountTask.getResult();
UserData userData = new UserData();
userData.setAccessToken(authAccount.getAccessToken());
userData.setCountryCode(authAccount.getCountryCode());
userData.setDisplayName(authAccount.getDisplayName());
userData.setEmail(authAccount.getEmail());
userData.setFamilyName(authAccount.getFamilyName());
userData.setGivenName(authAccount.getGivenName());
userData.setIdToken(authAccount.getIdToken());
userData.setOpenId(authAccount.getOpenId());
userData.setUid(authAccount.getUid());
userData.setPhotoUriString(authAccount.getAvatarUriString());
userData.setUnionId(authAccount.getUnionId());
updateMessage("Welcome " + userData.getDisplayName());
} else {
// The sign-in failed.
Log.e("TAG", "sign in failed:" + ((ApiException) authAccountTask.getException()).getStatusCode());
updateMessage(getResources().getString(R.string.msg_signin_failed));
}
}
}
public void updateMessage(String msg) {
binding.txtMessage.setText(msg);
}
}
[B]
LoginViewModel.java
[/B][/B]
public class LoginViewModel extends AndroidViewModel {
private MyApplication app;
AccountAuthService service;
public String message = "Login required";
public LoginViewModel(@NonNull Application application) {
super(application);
app = (MyApplication) application;
}
public void loginClicked() {
AccountAuthParams authParams = new
AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
service = AccountAuthManager.getService(MyApplication.getActivity(), authParams);
MyApplication.getActivity().startActivityForResult(service.getSignInIntent(), 8888);
}
}
[B][B]
Result
Tricks and Tips
Makes sure that agconnect-services.json file added.
Make sure required dependencies are added
Make sure that service is enabled in AGC
Makes sure Analytics service is enable in AGC
Conclusion
In this article, we have learnt how to integrate Huawei Account kit, and Analytics kit Android application KnowMyBoard part-1. Account kit helps users to login quickly and conveniently sign in to apps with their Huawei IDs after granting initial access permission. Analytics kit helps in app analysis and user behaviour.
Thank you so much for reading. I hope this article helps you to understand the integration of Huawei Account kit and Analytics kit in Android application KnowMyBoard.
Reference
Account Kit- Training Video
Analytics Kit- Training Video
Checkout in forum

Categories

Resources