You have likely seen user reviews complaining about how the online shopping experiences, in particular the inability to try on clothing items before purchase. Augmented reality (AR) enabled virtual try-on has resolved this longstanding issue, making it possible for users to try on items before purchase.
Virtual try-on allows the user to try on clothing, or accessories like watches, glasses, and makeup, virtually on their phone. Apps that offer AR try-on features empower their users to make informed purchases, based on which items look best and fit best, and therefore considerably improve the online shopping experience for users. For merchants, AR try-on can both boost conversion rates and reduce return rates, as customers are more likely to be satisfied with what they have purchased after the try-on. That is why so many online stores and apps are now providing virtual try-on features of their own.
When developing an online shopping app, AR is truly a technology that you can't miss. For example, if you are building an app or platform for watch sellers, you will want to provide a virtual watch try-on feature, which is dependent on real-time hand recognition and tracking. This can be done with remarkable ease in HMS Core AR Engine, which provides a wide range of basic AR capabilities, including hand skeleton tracking, human body tracking, and face tracking. Once you have integrated this tool kit, your users will be able to try on different watches virtually within your app before purchases. Better yet, the development process is highly streamlined. During the virtual try-on, the user's hand skeleton is recognized in real time by the engine, with a high degree of precision, and virtual objects are superimposed on the hand. The user can even choose to place an item on their fingertip! Next I will show you how you can implement this marvelous capability.
Demo
{
"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"
}
ImplementationAR Engine provides a hand skeleton tracking capability, which identifies and tracks the positions and postures of up to 21 hand skeleton points, forming a hand skeleton model.
Thanks to the gesture recognition capability, the engine is able to provide AR apps with fun, interactive features. For example, your app will allow users to place virtual objects in specific positions, such as on the fingertips or in the palm, and enable the virtual hand to perform intricate movements.
Now I will show you how to develop an app that implements AR watch virtual try-on based on this engine.
Integration ProcedureRequirements on the Development EnvironmentJDK: 1.8.211 or later
Android Studio: 3.0 or later
minSdkVersion: 26 or later
targetSdkVersion: 29 (recommended)
compileSdkVersion: 29 (recommended)
Gradle version: 6.1.1 or later (recommended)
Make sure that you have downloaded the AR Engine APK from AppGallery and installed it on the device.
If you need to use multiple HMS Core kits, use the latest versions required for these kits.
Preparations1. Before getting started, you will need to register as a Huawei developer and complete identity verification on the HUAWEI Developers website. You can click here to find out the detailed registration and identity verification procedure.
2. Before getting started, integrate the AR Engine SDK via the Maven repository into your development environment.
3. The procedure for configuring the Maven repository address in Android Studio varies for Gradle plugin earlier than 7.0, Gradle plugin 7.0, and Gradle plugin 7.1 or later. You need to configure it according to the specific Gradle plugin version.
4. Take Gradle plugin 7.0 as an example:
Open the project-level build.gradle file in your Android Studio project and configure the Maven repository address.
Go to buildscript > repositories and configure the Maven repository address for the SDK.
Code:
buildscript {
repositories {
google()
jcenter()
maven {url "https://developer.huawei.com/repo/" }
}
}
Open the project-level settings.gradle file and configure the Maven repository address for the HMS Core SDK.
Code:
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
repositories {
google()
jcenter()
maven {url "https://developer.huawei.com/repo/" }
}
}
}
5. Add the following build dependency in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:arenginesdk:{version}
}
App Development1. Check whether AR Engine has been installed on the current device. If so, your app will be able to run properly on the device. If not, you need to prompt the user to install AR Engine on the device, for example, by redirecting the user to AppGallery and prompting the user to install it. The sample code is as follows:
Code:
boolean isInstallArEngineApk =AREnginesApk.isAREngineApkReady(this);
if (!isInstallArEngineApk) {
// ConnectAppMarketActivity.class is the activity for redirecting users to AppGallery.
startActivity(new Intent(this, com.huawei.arengine.demos.common.ConnectAppMarketActivity.class));
isRemindInstall = true;
}
2. Initialize an AR scene. AR Engine supports five scenes, including motion tracking (ARWorldTrackingConfig) scene, face tracking (ARFaceTrackingConfig) scene, hand recognition (ARHandTrackingConfig) scene, human body tracking (ARBodyTrackingConfig) scene, and image recognition (ARImageTrackingConfig) scene.
Call ARHandTrackingConfig to initialize the hand recognition scene.
Code:
mArSession = new ARSession(context);
ARHandTrackingConfig config = new ARHandTrackingconfig(mArSession);
3. After obtaining an ARhandTrackingconfig object, you can set the front or rear camera. The sample code is as follows:
Code:
Config.setCameraLensFacing(ARConfigBase.CameraLensFacing.FRONT);
4. After obtaining config, configure it in ArSession, and start hand recognition.
Code:
mArSession.configure(config);
mArSession.resume();
5. Initialize the HandSkeletonLineDisplay class, which draws the hand skeleton based on the coordinates of the hand skeleton points.
Code:
Class HandSkeletonLineDisplay implements HandRelatedDisplay{
// Methods used in this class are as follows:
// Initialization method.
public void init(){
}
// Method for drawing the hand skeleton. When calling this method, you need to pass the ARHand object to obtain data.
public void onDrawFrame(Collection<ARHand> hands,){
// Call the getHandskeletonArray() method to obtain the coordinates of hand skeleton points.
Float[] handSkeletons = hand.getHandskeletonArray();
// Pass handSkeletons to the method for updating data in real time.
updateHandSkeletonsData(handSkeletons);
}
// Method for updating the hand skeleton point connection data. Call this method when any frame is updated.
public void updateHandSkeletonLinesData(){
// Method for creating and initializing the data stored in the buffer object.
GLES20.glBufferData(…,mVboSize,…);
// Update the data in the buffer object.
GLES20.glBufferSubData(…,mPointsNum,…);
}
}
6. Initialize the HandRenderManager class, which is used to render the data obtained from AR Engine.
Code:
Public class HandRenderManager implements GLSurfaceView.Renderer{
// Set the ARSession object to obtain the latest data in the onDrawFrame method.
Public void setArSession(){
}
}
7. Initialize the onDrawFrame() method in the HandRenderManager class.
Code:
Public void onDrawFrame(){
// In this method, call methods such as setCameraTextureName() and update() to update the calculation result of ArEngine.
// Call this API when the latest data is obtained.
mSession.setCameraTextureName();
ARFrame arFrame = mSession.update();
ARCamera arCamera = arFrame.getCamera();
// Obtain the tracking result returned during hand tracking.
Collection<ARHand> hands = mSession.getAllTrackables(ARHand.class);
// Pass the obtained hands object in a loop to the method for updating gesture recognition information cyclically for processing.
For(ARHand hand : hands){
updateMessageData(hand);
}
}
8. On the HandActivity page, set a render for SurfaceView.
Code:
mSurfaceView.setRenderer(mHandRenderManager);
Setting the rendering mode.
mSurfaceView.setRenderMode(GLEurfaceView.RENDERMODE_CONTINUOUSLY);
ConclusionAugmented reality creates immersive, digital experiences that bridge the digital and real worlds, making human-machine interactions more seamless than ever. Fields like gaming, online shopping, tourism, medical training, and interior decoration have seen surging demand for AR apps and devices. In particular, AR is expected to dominate the future of online shopping, as it offers immersive experiences based on real-time interactions with virtual products, which is what younger generations are seeking for. This considerably improves user's shopping experience, and as a result helps merchants a lot in improving the conversion rate and reducing the return rate. If you are developing an online shopping app, virtual try-on is a must-have feature for your app, and AR Engine can give you everything you need. Try the engine to experience what smart, interactive features it can bring to users, and how it can streamline your development.
Related
More information like this, you can visit HUAWEI Developer Forum
This article is based on Huawei’s In-App Purchases. We can create a new sample application for online grocery store to buy fruits and vegetables with online payment using In-App Purchases.
Huawei's In-App Purchases (IAP) service integrates multiple payment methods for global payment and allows you to easily offer in-app purchases. Users can purchase a variety of products or services, including common virtual products and subscriptions, directly within your app.
HUAWEI IAP provides a product management system (PMS) for managing the prices and languages of in-app products (including games) in multiple locations.
The latest version of IAP supports the following functions:
Release: You can release an app or a game with one package and manage the prices and languages of in-app purchases. The locations supported by the PMS on the price configuration page shall prevail.
Currencies and languages: You can set one default currency and one default language for each location. Setting multiple languages for one location is not allowed.
Price: Huawei provides an in-app product price reference for each location based on the converted price (tax included) set the exchange rate. You can change the price.
Exchange rate: fixed exchange rate by which Huawei will update the price. Updating the exchange rate by Huawei will not affect your price if you do not change the price.
Intended audience: global developers. To release an in-app product (or a game) to multiple locations, you need to manage the price and language of the products locally.
These are the following 3 types of in-app products supported by the IAP:
1. Consumable: Consumables are used once, are depleted, and can be purchased again.
2. Non-consumable: Non-consumables are purchased once and do not expire.
3. Auto-renewable subscriptions: Users can purchase access to value-added functions or content in a specified period of time. The subscriptions are automatically renewed on a recurring basis until users decide to cancel.
Prerequisite
1) A computer (desktop or laptop)
2) A Huawei phone used for running the app with HUAWEI IAP integrated
3) A data cable used for connecting the computer to the Huawei phone
4) Android Studio 3.0 or later
5) Java SDK 1.7 or later
6) HMS Core (APK) 3.0.0.300 or later
7) HMS Core SDK 4.0.0.300 or later
8) Must have Huawei Developer Account
9) Must have Huawei Merchant Account
Things Need To Be Done
1) Create an app in AppGallery Connect.
2) Create an Android Studio project.
3) Start development with kit integration inside the application.
4) Launch the application.
Create a project on AppGalleryConnect portal:
1. Click My projects.
{
"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"
}
2. Click Add project and provide your project details.
3. Provide your project name and click OK.
4. Navigate to General Information, and then provide Data Storage location.
5. Navigate to Manage APIs and enable APIs which require by application
6. Navigate to General information and download the agconnect-services.json file
7. Navigate to In-App Purchases and copy Public Key.
8. Navigate to My apps, click Operate, and then enter details in Add Product.
9. Click View and Edit in above screenshot, enter Product price details, and then click Save.
10. Click Activate for product activation.
Create a project in Android Studio:
1. Open your android studio and Create New Project.
2. Enter the maven url inside the repositories of buildscript and allprojects (project build.gradle file)
Add maven url and add following AppGalleryConnect class path.
Code:
buildscript {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.huawei.agconnect:agcp:1.0.0.300'
}
}
allprojects {
repositories {
maven {url 'http://developer.huawei.com/repo/'}
google()
jcenter()
}
}
3. Add the following dependencies in app module based gradle file
Code:
implementation 'com.huawei.hms:iap:4.0.0.300'
4. Generate SHA-256 fingerprint in android studio
5. Add json file inside your application
Start development with kit integration inside the application
We have created the following package inside the project.
We have created 3 activities Home, Store, and ViewPurchases activity inside activity package.
Home Activity: In this activity, we have created a simple User interface for our online store app.
Code:
public class HomeActivity extends BaseActivity {
private ActivityHomeBinding homeBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
init();
}
private void init() {
setToolbar(homeBinding.tbWidget.findViewById(R.id.toolbar),
false, "My Online Store", homeBinding.tbWidget.findViewById(R.id.tv_toolbar_title));
homeBinding.btnBuyFromStore.setOnClickListener(v->StoreActivity.start(this));
homeBinding.btnViewYourPurchases.setOnClickListener(v->ViewPurchasesActivity.start(this));
}
}
Store Activity: In this activity we have simply displayed the all products which is available.
Code:
public class HomeActivity extends BaseActivity {
private ActivityHomeBinding homeBinding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeBinding = DataBindingUtil.setContentView(this, R.layout.activity_home);
init();
}
private void init() {
setToolbar(homeBinding.tbWidget.findViewById(R.id.toolbar),
false, "My Online Store", homeBinding.tbWidget.findViewById(R.id.tv_toolbar_title));
homeBinding.btnBuyFromStore.setOnClickListener(v->StoreActivity.start(this));
homeBinding.btnViewYourPurchases.setOnClickListener(v->ViewPurchasesActivity.start(this));
}
}
This is not the end. For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201333994591170041&fid=0101188387844930001
How can we add money into Huawei points
These posts have shown the first few steps of developing a Unity game:
Unity Editor Installation and APK Packaging
How Can I Use the HUAWEI Game Service Demo Provided by Unity
Initializing a Huawei Game and Implementing HUAWEI ID Sign-in Using Unity
I tried to upload the packaged APK file to AppGallery Connect. Let’s see how it went.
Based on Unity documents, I first completed my game information in UDP, and uploaded its demo package. But the upload failed and UdpSdkNotDetectedError was displayed.
{
"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"
}
I asked Unity technical support for help, and they told me to also integrate the UDP SDK.
The UDP SDK is used for in-app purchases. You can learn more about it from this document:
https://docs.unity3d.com/Packages/[email protected]/manual/index.html
Integration of the UDP SDK
According to the Unity documents, there are three ways to integrate the UDP SDK:
Using Unity IAP (Unity IAP adds another layer to the UDP APIs.)
UDP is included in Unity IAP from version 1.22.0 to 1.23.5. If you use the Unity IAP package (1.22.0–1.23.5), do not install the UDP separately.
Using the UDP package
Using the UDP package and Unity IAP
The package of the Unity IAP 2.0.0 and later does not contain the UDP package. You need to download them both.
Latest version of Unity Asset Store (2020–11–24)
UDP version: 2.0.0
Unity IAP version: 2.2.2
Unity official documentation:
https://docs.unity3d.com/Packages/[email protected]/manual/index.html
https://distribute.dashboard.unity.com/udp/guideDoc/HUAWEI
Importing a UDP Package
If it’s your first time integrating the UDP SDK, just download the latest version of UDP package from Unity Asset Store.
Here’s the address:
https://assetstore.unity.com/packages/add-ons/services/billing/unity-distribution-portal-138507
Import the resource to Unity Editor.
If you see Unity Distribution Portal here, the resource has been imported.
Associating a Unity Project with a UDP Client ID
Document: https://docs.unity3d.com/Packages/[email protected]/manual/games-with-iap.html
Before you integrate Unity IAP, you need to associate your Unity project with a UDP client ID. Follow the instructions below.
Integrating the Unity IAP API.
Reference:
https://docs.unity3d.com/Packages/[email protected]/manual/games-with-iap.html
Before You Start
If you’re still confused by now, don’t worry, check the sample code provided by Unity. You can view it here after you downloaded the UDP package.
Integrating and Testing the StoreService.Initialize API
Integration
According to Unity, this API must be called before your game is released to other app stores using UDP.
I will continue with my earlier integrations, and here’s a few tips for you:
1. Add a button. Right-click HeaderPanel and choose UI > Button. Rename it Initialize.
2. Write code for the button.
Key points:
1) Add a namespace for UDP.
2) Declare the Initialize button, the callback listener of the API, and the boolean value.
C#:
private static InitListener m_InitListener=new InitListener();
// IAP initialized flag
private static bool m_Initialized;
private static Button initialize_button;
3) Capture the Initialize button in initUI().
C#:
initialize_button= GameObject.Find(“Initialize”).GetComponent<Button>();
4) Add the following code to private void initListeners():
C#:
initialize_button.onClick.AddListener(() =>
{
Show("starting initialize");
StoreService.Initialize(m_InitListener);
Show("initialize finished");
});
5) If you want the StoreService.Initialize API to be automatically called at app launch, add the highlighted code here:
C#:
void Start()
{
initUI();
initListeners();
// Call the Appinit method in your game code
appInit();
// Call the Initialize method in your game code
initialize();
}
private void initialize()
{
m_Initialized = false;
Debug.Log("Init button is clicked.");
Show("Initializing");
StoreService.Initialize(m_InitListener);
}
6) Edit the callback processing logic.
C#:
public class InitListener : IInitListener
{
public void OnInitialized(UserInfo userInfo)
{
Debug.Log("[Game]On Initialized suceeded");
Show("Initialize succeeded");
m_Initialized = true;
}
public void OnInitializeFailed(string message)
{
Debug.Log("[Game]OnInitializeFailed: " + message);
Show("Initialize Failed: " + message);
}
}
Packaging and Testing
The following information indicates that the API is called successfully.
Adding a Sandbox Test Account
If the following message is displayed, you need to add a sandbox account to check whether the IAP API is integrated successfully before app release.
Check this document:
https://docs.unity3d.com/Packages/[email protected]/manual/creating-a-game-on-udp.html
Make sure to click SAVE after adding the account.
The following information indicates that the API is called successfully.
Integrating and Testing the StoreService.QueryInventory API
API Functions
This API is used to query HUAWEI IAP for any missing transactions.
For consumables, if a product is purchased but not delivered, this API returns the product ID. Which means, it returns the consumable with a payment exception.
For non-consumables, this API returns all non-consumables that have been purchased by the player.
Integration
Similar to the integration of StoreService.Initialize.
Packaging and Testing
When calling this API, you can pass the product ID you want to query. If you pass one, you’ll see the corresponding information here.
After launching the app, you’ll see the following screen:
Creating a Product
To better test the IAP API, you can create a few products. Check this document:
https://docs.unity3d.com/Packages/c...#managing-in-app-purchases-on-the-udp-console
Here, I created two products.
Note: Currently, Unity IAP does not support subscriptions for games released on HUAWEI AppGallery.
Integrating and Testing the StoreService.Purchase API
Integration
Similar to the integration of StoreService.Initialize.
Packaging and TestingNon-consumables
StoreService.Purchase(“non_consumable_product01”, “payload”, m_PurchaseListener);
Here, non_consumable_product01 is a non-consumable I created in UDP.
After a successfull purchase is successful, call the API again. The following message is displayed.
Call StoreService.QueryInventory(productIds,m_PurchaseListener);.
Define productIds as follows:
List<string> productIds = new List<string> { “consumable_product01”, “non_consumable_product01” };
Now, you can see the information of the two products I created and the non-consumable I just purchased.
Consumables
After a consumable is purchased, it will be delivered and consumed.
If a consumable fails to be delivered after being purchased, you can call the StoreService.QueryInventory API to query its information, which is similar to HUAWEI IAP.
1) The consumable is not consumed after purchase.
Call this API:
StoreService.Purchase("non_consumable_product01", "payload", m_PurchaseListener);
A message is displayed, indicating that the product needs to be consumed before another purchase.
2) StoreService.QueryInventory(productIds,m_PurchaseListener);
Define productIds as follows:
C#:
List<string> productIds = new List<string> { "consumable_product01", "non_consumable_product01" };
The consumable is included in the purchased products that are returned.
3) Call this API to consume the product:
C#:
StoreService.ConsumePurchase(PurchaseInfo,IPurchaseListener)
According to the official document, PurchaseInfo is returned using the onPurchase method. You can obtain this method from the callback of StoreService.QueryInventory or StoreService.Purchase.
Here, I called the StoreService.QueryInventory API, obtained the consumable, and consumed it:
C#:
StoreService.ConsumePurchase(inventory.GetPurchaseInfo("consumable_product01"), this);
The following information indicates that the product is consumed.
Note:
After the consumption, if you call the StoreService.QueryInventory API again, you’ll see that there’s no consumable left. The query and redeliver process is complete.
Server APIs involved in Unity IAP
According to Unity, if the server APIs fail to receive the callback, no matter what the payment result is, from an app store, payment failure will be returned by UDP. Unity also provides some server APIs for you to integrate.
I’m not going to show you the demo test. You can try it on your own.
Payment Callback API
If you have your own game server, you can receive successful payment notifications sent by UDP.
For details, check this document:
https://docs.unity3d.com/Packages/c...ames-with-iap.html#game-client-implementation
Configure the callback URL here.
Order Query API
You can also send an HTTP GET request for order details and verify its information.
For details, check this document:
https://docs.unity3d.com/Packages/c...ames-with-iap.html#server-side-implementation
Very useful if you use unity.
Rebis said:
Very useful if you use unity.
Click to expand...
Click to collapse
Thank you for your liking appreciation.
Introduction
This article is based on Multiple HMS services application. I have created Hotel Booking application using HMS Kits. We need mobile app for reservation hotels when we are traveling from one place to another place.
In this article I have implemented Account kit and Ads Kit. User can login through Huawei Id.
{
"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"
}
Flutter setup
Refer this URL to setup Flutter.
Software Requirements
1. Android Studio 3.X
2. JDK 1.8 and later
3. SDK Platform 19 and later
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location.
4. Enabling Required Services: Account and Ads Kit.
5. Generating a Signing Certificate Fingerprint.
6. Configuring the Signing Certificate Fingerprint.
7. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Add the below permissions in Android Manifest file.
Code:
<manifest xlmns:android...>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
</manifest>
3. Refer below URL for cross-platform plugins.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001051088628-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: hotelbooking
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
shared_preferences: ^0.5.12+4
bottom_navy_bar: ^5.6.0
cupertino_icons: ^1.0.0
provider: ^4.3.3
huawei_ads:
path: ../huawei_ads/
huawei_account:
path: ../huawei_account/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- assets/images/
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Account kit
Account kit allows users to login their applications conveniently, quickly and simple login functionalities to the 3rd party applications.
If you examine Account Kit’s Official Huawei resources on internet, it also appears that they imply the simplicity, fastness and security. We can make use of following observation to understand where this fastness and simplicity is originated.
Service Features
Quick and standard
Huawei Account Kit allows you to connect to the Huawei ecosystem using your HUAWEI ID from a range of devices. This range of devices is not limited with mobile phones, you can also easily access applications on tablets, wearables, and smart displays using Huawei ID.
Massive user base and global services
Huawei Account Kit serves 190+ countries and regions worldwide. Users can also use HUAWEI ID to quickly sign in to apps. For details about supported regions/countries, please refer here from official documentation.
Secure, reliable, and compliant with international standards
Complies with international standards and protocols (such as OAuth2.0 and OpenID Connect), and supports two-factor authentication to ensure high security.
Integration
Signing-In
To allow users securely signing-in with Huawei ID, you should use signIn method of HMSAccount module. When this method called for the first time for a user, a Huawei ID authorization interface will be shown Once signIn successful, it will return AuthHuaweiID object.
Code:
void _signInHuawei() async {
final helper = new HmsAuthParamHelper();
helper
..setAccessToken()
..setIdToken()
..setProfile()
..setEmail()
..setAuthorizationCode();
try {
HmsAuthHuaweiId authHuaweiId =
await HmsAuthService.signIn(authParamHelper: helper);
StorageUtil.putString("Token", authHuaweiId.accessToken);
Navigator.push(context,MaterialPageRoute(builder: (context) => HomePageScreen()),
);
} on Exception catch (e) {}
}
Signing-Out
signOut method is used to allow user signing-out from app, it does not clear user information permanently.
Code:
void signOut() async {
try {
final bool response = await HmsAuthService.signOut();
} on Exception catch (e) {
print(e.toString());
}
}
ADs kit
Nowadays, traditional marketing has left its place on digital marketing. Advertisers prefer to place their ads via mobile media rather than printed publications or large billboards, this way they can reach their target audience more easily and they can measure their efficiency by analyzing many parameters such as ad display and the number of clicks.
HMS Ads Kit is a mobile service that helps us to create high quality and personalized ads in our application. It provides many useful ad formats such as native ads, banner ads and rewarded ads to more than 570 million Huawei device users worldwide.
Advantages
1. Provides high income for developers.
2. Rich ad format options.
3. Provides versatile support.
1. Banner Ads are rectangular ad images located at the top, middle or bottom of an application’s layout. Banner ads are automatically refreshed at intervals. When a user taps a banner ad, in most cases the user is taken to the advertiser’s page.
2. Rewarded Ads are generally preferred in gaming applications. They are the ads that in full-screen video format that users choose to view in exchange for in-app rewards or benefits.
3. Native Ads are ads that take place in the application’s interface in accordance with the application flow. At first glance they look like a part of the application, not like an advertisement.
4. Interstitial Ads are full screen ads that cover the application’s interface. Such that ads are displayed without disturbing the user’s experience when the user launches, pauses or quits the application.
5. Splash Ads are ads that are displayed right after the application is launched, before the main screen of the application comes.
Huawei Ads SDK integration Let’s call HwAds.init() in the initState()
Code:
@override
void initState() {
super.initState();
HwAds.init();
}
Load Banner Ads
void loadAds() {
BannerAd _bannerAd;
_bannerAd = createAd()
..loadAd()
..show();
}
BannerAd createAd() {
return BannerAd(
adSlotId: "testw6vs28auh3",
size: BannerAdSize.s320x50,
adParam: new AdParam());
}
Load Native Ads
Code:
NativeAdConfiguration configuration = NativeAdConfiguration();
configuration.choicesPosition = NativeAdChoicesPosition.bottomRight;
Container(
height: 100,
margin: EdgeInsets.only(bottom: 10.0),
child: NativeAd(
adSlotId: "testu7m3hc4gvm",
controller: NativeAdController(
adConfiguration: configuration,
listener: (AdEvent event, {int errorCode}) {
print("Native Ad event : $event");
}),
type: NativeAdType.small,
),
),
Result
Tips & Tricks
1. Download latest HMS Flutter plugin.
2. The lengths of access_token and refresh_token are related to the information encoded in the tokens. Currently, access_token and refresh_token contains a maximum of 1024 characters.
3. This API can be called by an app up to 10,000 times within one hour. If the app exceeds the limit, it will fail to obtain the access token.
4. Whenever you updated plugins, click on pug get.
Conclusion
We implemented simple hotel booking application using Account kit and Ads kit in this article.
Thank you for reading and if you have enjoyed this article, I would suggest you to implement this and provide your experience.
Reference
Account Kit URL
Ads Kit URL
Read full article
Garrygb said:
Hi! Thank you for share this information. I tried to build apps for my business using HMS kits but unfortunately have some problems with the main code and I can't find where this code error. Perhaps, I will try to ask for help from professional apps developers.
Click to expand...
Click to collapse
Hi can you please explain which kit you integrated in your application ,can you explain detail so that i can able to help you out to fix your problems
I deleted all projects and start new.
BackgroundThe real-time onscreen subtitle is a must-have function in an ordinary video app. However, developing such a function can prove costly for small- and medium-sized developers. And even when implemented, speech recognition is often prone to inaccuracy. Fortunately, there's a better way — HUAWEI ML Kit, which is remarkably easy to integrate, and makes real-time transcription an absolute breeze!
Introduction to ML KitML Kit allows your app to leverage Huawei's longstanding machine learning prowess to apply cutting-edge artificial intelligence (AI) across a wide range of contexts. With Huawei's expertise built in, ML Kit is able to provide a broad array of easy-to-use machine learning capabilities, which serve as the building blocks for tomorrow's cutting-edge AI apps. ML Kit capabilities include those related to:
Text (including text recognition, document recognition, and ID card recognition)
Language/Voice (such as real-time/on-device translation, automatic speech recognition, and real-time transcription)
Image (such as image classification, object detection and tracking, and landmark recognition)
Face/Body (such as face detection, skeleton detection, liveness detection, and face verification)
Natural language processing (text embedding)
Custom model (including the on-device inference framework and model development tool)
Real-time transcription is required to implement the function mentioned above. Let's take a look at how this works in practice:
{
"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"
}
Now let's move on to how to integrate this service.
Integrating Real-Time TranscriptionSteps
Registering as a Huawei developer on HUAWEI Developers
Creating an app
Create an app in AppGallery Connect. For details, see Getting Started with Android.
We have provided some screenshots for your reference:
3. Enabling ML Kit
4. Integrating the HMS Core SDK.
Add the AppGallery Connect configuration file by completing the steps below:
Download and copy the agconnect-service.json file to the app directory of your Android Studio project.
Call setApiKey during app initialization.
To learn more, go to Adding the AppGallery Connect Configuration File.
5.Configuring the maven repository address
Add build dependencies.
Import the real-time transcription SDK.
Code:
implementation 'com.huawei.hms:ml-computer-voice-realtimetranscription:2.2.0.300'
Add the AppGallery Connect plugin configuration.
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration:
id 'com.huawei.agconnect'
}
Please refer to Integrating the Real-Time Transcription SDK to learn more.
Setting the cloud authentication information
When using on-cloud services of ML Kit, you can set the API key or access token (recommended) in either of the following ways:
Access token
You can use the following API to initialize the access token when the app is started. The access token does not need to be set again once initialized.
MLApplication.getInstance().setAccessToken("your access token");
API key
You can use the following API to initialize the API key when the app is started. The API key does not need to be set again once initialized.
MLApplication.getInstance().setApiKey("your ApiKey");
For details, see Notes on Using Cloud Authentication Information.
Code Development
Create and configure a speech recognizer.
Code:
MLSpeechRealTimeTranscriptionConfig config = new MLSpeechRealTimeTranscriptionConfig.Factory()
// Set the language. Currently, this service supports Mandarin Chinese, English, and French.
.setLanguage(MLSpeechRealTimeTranscriptionConstants.LAN_ZH_CN)
// Punctuate the text recognized from the speech.
.enablePunctuation(true)
// Set the sentence offset.
.enableSentenceTimeOffset(true)
// Set the word offset.
.enableWordTimeOffset(true)
// Set the application scenario. MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING indicates shopping, which is supported only for Chinese. Under this scenario, recognition for the name of Huawei products has been optimized.
.setScenes(MLSpeechRealTimeTranscriptionConstants.SCENES_SHOPPING)
.create();
MLSpeechRealTimeTranscription mSpeechRecognizer = MLSpeechRealTimeTranscription.getInstance();
Create a speech recognition result listener callback.
Code:
// Use the callback to implement the MLSpeechRealTimeTranscriptionListener API and methods in the API.
protected class SpeechRecognitionListener implements MLSpeechRealTimeTranscriptionListener{
@Override
public void onStartListening() {
// The recorder starts to receive speech.
}
@Override
public void onStartingOfSpeech() {
// The user starts to speak, that is, the speech recognizer detects that the user starts to speak.
}
@Override
public void onVoiceDataReceived(byte[] data, float energy, Bundle bundle) {
// Return the original PCM stream and audio power to the user. This API is not running in the main thread, and the return result is processed in a sub-thread.
}
@Override
public void onRecognizingResults(Bundle partialResults) {
// Receive the recognized text from MLSpeechRealTimeTranscription.
}
@Override
public void onError(int error, String errorMessage) {
// Called when an error occurs in recognition.
}
@Override
public void onState(int state,Bundle params) {
// Notify the app of the status change.
}
}
The recognition result can be obtained from the listener callbacks, including onRecognizingResults. Design the UI content according to the obtained results. For example, display the text transcribed from the input speech.
Bind the speech recognizer.
Code:
mSpeechRecognizer.setRealTimeTranscriptionListener(new SpeechRecognitionListener());
Call startRecognizing to start speech recognition.
Code:
mSpeechRecognizer.startRecognizing(config);
Release resources after recognition is complete.
Code:
if (mSpeechRecognizer!= null) {
mSpeechRecognizer.destroy();
}
(Optional) Obtain the list of supported languages.
Code:
MLSpeechRealTimeTranscription.getInstance()
.getLanguages(new MLSpeechRealTimeTranscription.LanguageCallback() {
@Override
public void onResult(List<String> result) {
Log.i(TAG, "support languages==" + result.toString());
}
@Override
public void onError(int errorCode, String errorMsg) {
Log.e(TAG, "errorCode:" + errorCode + "errorMsg:" + errorMsg);
}
});
We have finished integration here, so let's test it out on a simple screen.
Tap START RECORDING. The text recognized from the input speech will display in the lower portion of the screen.
We've now built a simple audio transcription function.
Eager to build a fancier UI, with stunning animations, and other effects? By all means, take your shot!
For reference:Real-Time Transcription
Sample Code for ML Kit
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source
{
"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
If you are new to series of this article, follow the below article.
Beginner: Integration of Huawei Account kit in Navigation Glove IoT application Using Kotlin - Part 1
Beginner: Integration of Huawei Map kit in Navigation Glove IoT application Using Kotlin - Part 2
Beginner: Integration of Huawei Site kit in Navigation Glove IoT application Using Kotlin - Part 3
Beginner: Integration of Huawei Direction API in Navigation Glove IoT application Using Kotlin - Part 4
Beginner: Connecting to Smart Gloves Using Bluetooth in Navigation Glove IoT application Using Kotlin - Part 5
Click to expand...
Click to collapse
In this article, we will learn how to integrate Analytics kit and Crash Service in Smart Glove application.
Adding Events with Huawei Analytics Kit
This guide walks you through the process of building application that uses Huawei Analytics Kit to trigger event and can find data on the console.
What You Will Build
You will build an application that triggers events, setting user properties, logging custom event etc.
Prerequisite
About 10 minutes
A favorite text editor or IDE(For me Android Studio)
JDK 1.8 or later
Gradle 4+
SDK platform 19
Analytics Kit
What is Mobile analytics?
Mobile analytics captures data from mobile app, website, and web app visitors to identify unique users, track their journeys, record their behaviour, and report on the app’s performance. Similar to traditional web analytics, mobile analytics are used to improve conversions, and are the key to crafting world-class mobile experiences.
How to complete this guide
When a person says that I know theoretical concept, only when he/she knows the answer for all WH questions. To complete this guide, let’s understand all WH questions.
1. Who has to use analytics?
2. Which one to use?
3. What is Huawei Analytics kit?
4. When to use HMS Analytics kit?
5. Why to use analytics kit?
6. Where to use analytics Kit?
Once you get answer for all the above questions, then you will get theoretical knowledge. But to understand with result you should know answer for below question.
1. How to integrate Huawei analytics kit?
Who has to use the analytics kit?
The answer is very simple, the analytics kit will be used in the mobile/web application. So off course software developer has to use analytics kit.
Which one to use?
Since there are many analytics vendors in the market. But for mobile application I recommend Huawei analytics kit. Now definitely you will have question why? To answer this I’ll give some reasons.
Very easy to integrate.
Documentation is too good.
Community is too good. Response from community is so fast.
Moreover, it is very similar to other vendors, so no need to learn new things.
You can see events in real time.
What is Huawei Analytics kit?
Flutter Analytics plugin enables the communication between HMS Core analytics SDK and Flutter platform. This plugin exposed all the functionality which is provided by HMS core analytics SDK.
Huawei Analytics kit offers you a range of analytics models that helps you to analyse the users’ behaviour with predefined and custom events, you can gain a deeper insight into your users, products and content. It helps you to gain insight into that how users behave on different platforms based on the user behaviour events and user attributes reported through apps.
Huawei Analytics kit, our one-stop analytics platform provides developers with intelligent, convenient and powerful analytics capabilities, using this we can optimize apps performance and identify marketing channels.
Collect and report custom events.
Set a maximum of 25 user attributes.
Automate event collection and session calculation.
Preset event IDs and parameters.
When to use HMS Analytics kit?
Mobile app analytics are a developer’s best friend. It helps you gain understanding about that how users’ behaviour and app can be optimized to reach your goals. Without mobile app analytics, you would be trying out different things blindly without any data to back up your experiments.
That’s why it’s extremely important for developers to understand their mobile app analytics to track their progress while working towards achieving their goals.
Why to use analytics kit?
Mobile app analytics are essential to development process for many reasons. They give you insights into that how users are using your app, which parts of the app they interact with, and what actions they take within the app. You can use these insights to come up with an action plan to improve your product in future, like adding new features that the users seem to need, or improve existing ones in a way that would make the users lives easier, or removing features that the users don’t seem to use.
You’ll also gain insights into whether you’re achieving your goals for your mobile app, whether its revenue, awareness, or other KPIs, and then take the data you have to adjust your strategy and optimize your app to reach your further goals.
When it comes to why? Always everyone thinks about benefits.
Benefits of Analytics
App analytics helps you to drive ROI over every aspect of performance.
App analytics helps you to gather accurate data to better serve for customers.
App analytics allows you to drive personalized and customer-focused marketing.
App analytics allows you to track individual and group achievements of marketing goals from campaigns.
App analytics offers data-driven insights into issues concerning churn and retention.
Where to use analytics Kit?
This is very important question, because you already know that why to use the analytics kit. So, wherever you want understand about user behaviour, which part of the application users are using regularly, which functionality of the application users are using more. In the scenario you can use analytics kit in either mobile/web application you can use the analytics kit.
Crash Service
What is Huawei Crash service?
In this article, we will learn how to integrate Crash services of AppGallery in Pygmy collection finance application.
Huawei Crash is a realtime crash reporting tool that helps in tracking, prioritizing, and fix stability issues that compromise the quality of your app. Crashlytics also helps in troubleshooting and saves the debugging.
The AppGallery Connect Crash service provides a powerful lightweight solution to app crash problems. With the service, you can quickly detect, locate and resolve app crashes (unexpected exits of apps), and have access to highly readable crash reports in real time, without the need to write any code.
To ensure stable running of your app and prevent user experience deterioration caused by crashes, you are advised to monitor the running status of your app on each device, which is the key. The Crash service provides real-time reports, revealing any crash of your app on any device. In addition, the Crash service can intelligently aggregate crashes, providing context data when a crash occurs, such as environment information and stack, for you to prioritize the crash easily for rapid resolution.
Why do we need the crash service?
Although apps have gone through rounds the tests before release considering the large user base diverse device models and complex network environment. It’s inevitable for apps to crash occasionally. Crashes compromise user experience, users may even uninstall app due to crashes and your app is not going to get good reviews.
You can’t get sufficient crash information from reviews to locate crashes, therefore you can’t resolve them shortly. This will severely harm your business. That’s why we need to use the crash services in our apps to be more efficient.
Now start with practical
Till now you understood theoretical concept of the analytics kit. Now let’s start with the practical example, to understand about practical we should get answer for the below question.
How to integrate Huawei analytics kit in Android finance application?
To achieve this you need to follow the steps.
1. Configure application on the AGC.
2. Client application development process.
Configure application on the AGC
Follow the steps.
Step 1: We need to register as a developer account in AppGallery Connect. If you are already developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on current location.
Step 4: Enabling Analytics Kit. Project setting > Manage API > Enable analytics kit toggle button.
Step 5: Generating a Signing Certificate Fingerprint.
Step 6: Configuring the Signing Certificate Fingerprint.
Step 7: Download your agconnect-services.json file, paste it into the app root directory.
Step 8: Choose Quality > Crash > Enable the crash service.
Client application development process
Follow the steps.
Step 1: Create Android application in the Android studio (Any IDE which is your favorite)
Step 2: Add the App level gradle dependencies. Choose inside project Android > app > build.gradle.
How to integrate Analytics Kit and Crash Service
1. Configure the application on the AGC.
2. Client application development process.
3. Testing a Splash Ad.
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Java:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hianalytics:5.1.0.300'
implementation "com.huawei.agconnect:agconnect-crash:1.6.0.300"
}
Root level gradle dependencies.
Java:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: To allow HTTP and HTTPS network requests on devices with targetSdkVersion 28 or later, configure the following information in the AndroidManifest.xml file:
XML:
<application
...
android:usesCleartextTraffic="true">
...
</application>
Analytics kit
HuaweiLog.kt
Java:
package com.huawei.navigationglove.analytics
import com.huawei.navigationglove.analytics.HuaweiLog
import android.os.Bundle
import android.util.Log
import java.lang.Exception
import java.util.ArrayList
import java.util.HashMap
class HuaweiLog {
var eventName: String? = null
private val data: HashMap<String, String>? = HashMap()
fun setEventName(eventName: String?): HuaweiLog {
this.eventName = eventName
return this
}
fun setKeyAndValue(key: String, value: String): HuaweiLog {
data!![key] = value
return this
}
fun toBundle(): Bundle {
val bundle = Bundle()
try {
if (data != null && data.size > 0) {
for ((key, value) in data) {
bundle.putString(key, value)
Log.d("Huawei", "$key $value")
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return bundle
} /*
public HuaweiLog setTestDescription(ArrayList list) {
testdata.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), list);
return this;
}*/
}
HuaweiAnalyticsClient.kt
Java:
package com.huawei.navigationglove.analytics
import android.content.Context
import android.util.Log
import com.huawei.hms.analytics.HiAnalytics
import com.huawei.hms.analytics.type.ReportPolicy
import com.huawei.hms.analytics.HiAnalyticsInstance
import java.lang.Exception
import java.lang.RuntimeException
import java.util.HashSet
class HuaweiAnalyticsClient private constructor() {
fun initAnalytics(context: Context?) {
mHuaweiAnalyticsClient = HiAnalytics.getInstance(context)
if (mHuaweiAnalyticsClient == null) {
Log.e(TAG, "Analytics Client could not be initialized.")
return
}
mHuaweiAnalyticsClient!!.setAnalyticsEnabled(true)
mHuaweiAnalyticsClient!!.setUserId("UserId")
mHuaweiAnalyticsClient!!.setAutoCollectionEnabled(true)
// Used to report an event upon app switching to the background.
val moveBackgroundPolicy = ReportPolicy.ON_MOVE_BACKGROUND_POLICY
// Used to report an event at the specified interval.
val scheduledTimePolicy = ReportPolicy.ON_SCHEDULED_TIME_POLICY
// Set the event reporting interval to 600 seconds.
scheduledTimePolicy.threshold = 600
val reportPolicies: MutableSet<ReportPolicy> = HashSet()
// Add the ON_SCHEDULED_TIME_POLICY and ON_MOVE_BACKGROUND_POLICY policies.
reportPolicies.add(scheduledTimePolicy)
reportPolicies.add(moveBackgroundPolicy)
// Set the ON_MOVE_BACKGROUND_POLICY and ON_SCHEDULED_TIME_POLICY policies.
mHuaweiAnalyticsClient!!.setReportPolicies(reportPolicies)
}
fun logEvent(log: HuaweiLog) {
if (mHuaweiAnalyticsClient == null) {
throw RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().")
}
try {
mHuaweiAnalyticsClient!!.onEvent(log.eventName, log.toBundle())
Log.d("Huawei", log.eventName!!)
} catch (e: Exception) {
Log.d(TAG, "Huawei analytics failed" + e.message)
}
}
/* public void putHuaweiUserProperty(HuaweiUserProperty.KeyName propertyKey, String value) {
if (mHuaweiAnalyticsClient == null) {
throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
}
try {
mHuaweiAnalyticsClient.setUserProfile(propertyKey.textValue(), value);
} catch (Exception e) {
Log.d(TAG, "Huawei analytics failed", e);
}
}*/
fun setHuaweiUserId(userId: String?) {
if (mHuaweiAnalyticsClient == null) {
throw RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().")
}
if (userId == null) {
mHuaweiAnalyticsClient!!.setUserId(null)
return
}
mHuaweiAnalyticsClient!!.setUserId(userId)
}
companion object {
private val TAG = HuaweiAnalyticsClient::class.java.simpleName
private var ourInstance: HuaweiAnalyticsClient? = null
private var mHuaweiAnalyticsClient: HiAnalyticsInstance? = null
val instance: HuaweiAnalyticsClient?
get() {
if (ourInstance == null) {
ourInstance = HuaweiAnalyticsClient()
}
return ourInstance
}
}
}
AnalyticUtils.kt
Java:
package com.huawei.navigationglove.analytics
import android.util.Log
import java.lang.Exception
object AnalyticUtils {
private val TAG = AnalyticUtils::class.java.simpleName
fun logHuaweiAnalyticEvent(huaweiLog: HuaweiLog) {
try {
HuaweiAnalyticsClient.instance!!.logEvent(huaweiLog)
Log.d(TAG, "Huawei analytics $huaweiLog")
} catch (e: Exception) {
Log.d(TAG, "Huawei analytics failed")
}
}
}
Crash Report
Java:
//AGConnectCrash.getInstance().testIt(this)
AGConnectCrash.getInstance().enableCrashCollection(true)
AGConnectCrash.getInstance().setUserId("Add user ID");
AGConnectCrash.getInstance().log(Log.DEBUG, "set debug log.");
AGConnectCrash.getInstance().log(Log.INFO, "set info log.");
AGConnectCrash.getInstance().log(Log.WARN, "set warning log.");
AGConnectCrash.getInstance().log(Log.ERROR, "set error log.");
AGConnectCrash.getInstance().setCustomKey("stringKey", "Hello world");
AGConnectCrash.getInstance().setCustomKey("booleanKey", false);
AGConnectCrash.getInstance().setCustomKey("doubleKey", 1.1);
AGConnectCrash.getInstance().setCustomKey("floatKey", 1.1f);
AGConnectCrash.getInstance().setCustomKey("intKey", 0);
AGConnectCrash.getInstance().setCustomKey("longKey", 11L);
Result
Analytics
Crash Service
Tips and Tricks
Make sure you are already registered as a Huawei developer.
Make sure you have added the agconnect-services.json file to the app folder.
Make sure you have added the SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Make sure you added agconnect-service.json file.
Add internet permission in AndroidManifest.xml
Add the below code to download the HMS core apk
Conclusion
In this article, we have learnt the integration of the Huawei Analytics kit and Crash service in Smart Glove application using Android Studio and Kotlin. And also we have learned how to download crash report and also we have learnt the tracking the analytics data on the console.
Reference
Analytics Kit - Official document
Huawei Crash – Official document
Analytics Kit – Training Video
Huawei Crash – Training Video