DEV Community

Cover image for Integration of Huawei Account kit and Analytics kit in Know My Board in your language - Part 1
HMS Community
HMS Community

Posted on

Integration of Huawei Account kit and Analytics kit in Know My Board in your language - Part 1

Introduction

In this article, we will learn about Know board in your language and also we will learn about integration of the Huawei Account kit and Analytics kit in Know board application.

It’s really quite interesting application. Have patience to read the full article. Because great things will take time.

Let us understand how this application works.

The purpose of this application is to showcase how easy it is to understand the foreign language using HMS Kits. One of the most common problems encountered by foreigners while traveling is language barriers. Our application use case can support travellers to not only understand the travel directions but also it can support them throughout the journey to enhance the local connect by translating food menu, shop details etc. This app helps you to translate the foreign language and provide results in English language.

Huawei Kits Used in this application

Huawei Account kit
Huawei Analytics kit
Huawei ML Kit
Huawei Location Kit
Huawei Site kit
Huawei Map Kit
Huawei Account kit: Account Kit provides you with simple, secure, and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
Huawei Analytics Kit: 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.
Huawei ML Kit: We are using ML Kit Text Recognition service to fetch the text from Image. Once the text is fetched we are using Text Translation service to get the result in English language.
Huawei Location kit: Using location kit we will get users current location so that they can get the current locale which can be shared with ML Kit. Using the same location co-ordinate we will try to call the translation API and showcase translated results to customer.
Huawei Map kit: It is used to show users shared location and nearby landmarks on the map.
Huawei Site Kit: To show the landmark on the map which can be shared with different users at the given at the time of request for this we have used the nearby service from the site kit.

Prerequisite

AppGallery Account
Android Studio 3.X
SDK Platform 19 or later
Gradle 4.6 or later
HMS Core (APK) 4.0.0.300 or later
Huawei Phone EMUI 3.0 or later
Non-Huawei Phone Android 4.4 or later
Account 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. It save lot of time to user instead of entering all the details just sign in with Huawei Account. And also it is very secure.

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.

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.

Service integration on AppGallery.

  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 the current location.

  4. Enabling Account Kit and Analytics Kit Service on AppGallery.

  5. Generating a Signing Certificate Fingerprint.

  6. Configuring the Signing Certificate Fingerprint.

  7. Get your agconnect-services.json file to the app root directory.

Client development

  1. Create android project in android studio IDE.

  2. Add the maven URL inside the repositories of buildscript and allprojects respectively (project level build.gradle file).

maven { url 'https://developer.huawei.com/repo/' }
Enter fullscreen mode Exit fullscreen mode
  1. Add the classpath inside the dependency section of the project level build.gradle file.
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
Enter fullscreen mode Exit fullscreen mode
  1. Add the plugin in the app-level build.gradle file.
apply plugin: 'com.huawei.agconnect'
Enter fullscreen mode Exit fullscreen mode
  1. Add the below library in the app-level build.gradle file dependencies section.
implementation 'com.huawei.hms:hwid:6.4.0.301'
implementation 'com.huawei.hms:hianalytics:6.4.1.302'
Enter fullscreen mode Exit fullscreen mode
  1. Add all the below permission in the AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Enter fullscreen mode Exit fullscreen mode
  1. Sync the project.

LoginViewModel.kt

package com.huawei.hms.knowmyboard.dtse.activity.viewmodel

import android.app.Application
import com.huawei.hms.knowmyboard.dtse.activity.app.MyApplication.Companion.activity
import androidx.lifecycle.AndroidViewModel
import com.huawei.hms.support.account.service.AccountAuthService
import androidx.lifecycle.MutableLiveData
import android.graphics.Bitmap
import android.util.Log
import android.view.View
import com.huawei.hms.location.LocationResult
import androidx.lifecycle.LiveData
import android.widget.Toast
import com.huawei.hms.support.account.request.AccountAuthParams
import com.huawei.hms.support.account.request.AccountAuthParamsHelper
import com.huawei.hms.support.account.AccountAuthManager
import com.huawei.hms.common.ApiException
import java.util.ArrayList

class LoginViewModel(application: Application) : AndroidViewModel(application) {
    var service: AccountAuthService? = null
    private val message = MutableLiveData<String>()
    val textRecongnized = MutableLiveData<ArrayList<String>>()
    val imagePath = MutableLiveData<Bitmap>()
    val locationResult = MutableLiveData<LocationResult>()
    fun sendData(msg: String) {
        message.value = msg
    }

    fun getMessage(): LiveData<String> {
        return message
    }

    fun setImage(imagePath: Bitmap) {
        this.imagePath.value = imagePath
    }

    fun setLocationResult(locationResult: LocationResult) {
        this.locationResult.value = locationResult
    }

    fun setTextRecognized(textRecognized: ArrayList<String>) {
        this.textRecongnized.value = textRecognized
    }

    fun logoutHuaweiID() {
        if (service != null) {
            service!!.signOut()
            sendData("KnowMyBoard")
            Toast.makeText(getApplication(), "You are logged out from Huawei ID", Toast.LENGTH_LONG)
                .show()
        }
    }

    fun loginClicked(view: View?) {
        val authParams =
            AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode()
                .createParams()
        service = AccountAuthManager.getService(activity, authParams)

        activity!!.startActivityForResult(service?.signInIntent, 8888)
    }

    fun cancelAuthorization() {
        if (service != null) {
            // service indicates the AccountAuthService instance generated using the getService method during the sign-in authorization.
            service!!.cancelAuthorization().addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    // Processing after a successful authorization cancellation.
                    Log.i("TAG", "onSuccess: ")
                    sendData("KnowMyBoard")
                    Toast.makeText(getApplication(), "Cancelled authorization", Toast.LENGTH_LONG)
                        .show()
                } else {
                    // Handle the exception.
                    val exception = task.exception
                    if (exception is ApiException) {
                        val statusCode = exception.statusCode
                        Log.i("TAG", "onFailure: $statusCode")
                        Toast.makeText(
                            getApplication(),
                            "Failed to cancel authorization",
                            Toast.LENGTH_LONG
                        ).show()
                    }
                }
            }
        } else {
            Toast.makeText(getApplication(), "Login required", Toast.LENGTH_LONG).show()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

UserData.kt

package com.huawei.hms.knowmyboard.dtse.activity.model

import com.huawei.hms.support.api.entity.auth.Scope
import java.util.HashSet

class UserData {
    var uid: String? = null
    var openId: String? = null
    var displayName: String? = null
    var photoUriString: String? = null
    var accessToken: String? = null
    var status = 0
    var gender = 0
    var serviceCountryCode: String? = null
    var countryCode: String? = null
    var grantedScopes: Set<Scope>? = null
    var serverAuthCode: String? = null
    var unionId: String? = null
    var email: String? = null
    var extensionScopes: HashSet<Scope> = HashSet<Scope>()
    var idToken: String? = null
    var expirationTimeSecs: Long = 0
    var givenName: String? = null
    var familyName: String? = null
    var ageRange: String? = null
    var homeZone = 0
    var carrierId = 0
}
Enter fullscreen mode Exit fullscreen mode

MainActivity.kt

import com.huawei.hms.knowmyboard.dtse.activity.app.MyApplication.Companion.activity
import androidx.appcompat.app.AppCompatActivity
import com.huawei.hms.knowmyboard.dtse.activity.viewmodel.LoginViewModel
import com.huawei.hms.mlsdk.text.MLTextAnalyzer
import android.graphics.Bitmap
import com.huawei.hms.mlsdk.langdetect.local.MLLocalLangDetector
import com.huawei.hms.mlsdk.translate.local.MLLocalTranslator
import android.app.ProgressDialog
import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import android.content.Intent
import com.huawei.hms.support.account.AccountAuthManager
import com.google.gson.Gson
import com.huawei.hms.common.ApiException
import android.provider.MediaStore
import com.huawei.hms.mlsdk.common.MLFrame
import com.huawei.hms.mlsdk.text.MLText
import com.huawei.hmf.tasks.OnSuccessListener
import com.huawei.hms.mlsdk.langdetect.MLLangDetectorFactory
import com.huawei.hms.mlsdk.langdetect.local.MLLocalLangDetectorSetting
import com.huawei.hmf.tasks.OnFailureListener
import android.content.DialogInterface
import android.net.Uri
import android.util.Log
import androidx.appcompat.app.AlertDialog
import com.huawei.hms.knowmyboard.dtse.R
import com.huawei.hms.knowmyboard.dtse.activity.model.UserData
import com.huawei.hms.mlsdk.common.MLApplication
import com.huawei.hms.mlsdk.translate.local.MLLocalTranslateSetting
import com.huawei.hms.mlsdk.translate.MLTranslatorFactory
import com.huawei.hms.mlsdk.model.download.MLModelDownloadStrategy
import com.huawei.hms.mlsdk.model.download.MLModelDownloadListener
import com.huawei.hms.mlsdk.text.MLLocalTextSetting
import com.huawei.hms.mlsdk.MLAnalyzerFactory
import java.io.IOException
import java.lang.Exception
import java.util.ArrayList

class MainActivity() : AppCompatActivity() {
    var loginViewModel: LoginViewModel? = null
    private var mTextAnalyzer: MLTextAnalyzer? = null
    var imagePath: Uri? = null
    var bitmap: Bitmap? = null
    var result = ArrayList<String>()
    var myLocalLangDetector: MLLocalLangDetector? = null
    var myLocalTranslator: MLLocalTranslator? = null
    var textRecognized: String? = null
    var progressDialog: ProgressDialog? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
        activity = this
        progressDialog = ProgressDialog(this)
        progressDialog!!.setCancelable(false)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        // Process the authorization result to obtain the authorization code from AuthAccount.
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 8888) {
            val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
            if (authAccountTask.isSuccessful) {
                // The sign-in is successful, and the user's ID information and authorization code are obtained.
                val authAccount = authAccountTask.result
                val userData = UserData()
                userData.accessToken = authAccount.accessToken
                userData.countryCode = authAccount.countryCode
                userData.displayName = authAccount.displayName
                userData.email = authAccount.email
                userData.familyName = authAccount.familyName
                userData.givenName = authAccount.givenName
                userData.idToken = authAccount.idToken
                userData.openId = authAccount.openId
                userData.uid = authAccount.uid
                userData.photoUriString = authAccount.avatarUri.toString()
                userData.unionId = authAccount.unionId
                val gson = Gson()
                Log.e("TAG", "sign in success : " + gson.toJson(authAccount))
                loginViewModel = ViewModelProvider(this@MainActivity).get(
                    LoginViewModel::class.java
                )
                loginViewModel!!.sendData(authAccount.displayName)
                progressDialog!!.dismiss()
            } else {
                // The sign-in failed.
                Log.e(
                    "TAG",
                    "sign in failed:" + (authAccountTask.exception as ApiException).statusCode
                )
                progressDialog!!.dismiss()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Analytics kit

package com.huawei.hms.knowmyboard.dtse.activity.app

import com.huawei.hms.knowmyboard.dtse.activity.app.MyApplication
import com.huawei.hms.analytics.HiAnalytics
import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.huawei.hms.analytics.HiAnalyticsInstance

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        // Or initialize Analytics Kit with the given context.
        instance = HiAnalytics.getInstance(this)
        instance?.setUserProfile("userKey", "value")

        // Enable tracking of the custom event in proper positions of the code.
        val bundle = Bundle()
        bundle.putString("language", "English")
        bundle.putString("Country", "India")
        instance?.onEvent("board_details", bundle)
    }

    companion object {
        var activity: Activity? = null
        var instance: HiAnalyticsInstance? = null
    }
}
Enter fullscreen mode Exit fullscreen mode

Enable Analytics kit in debug mode using below command

adb shell setprop debug.huawei.hms.analytics.app <package_name>
Enter fullscreen mode Exit fullscreen mode

Disable the debug mode using below command

adb shell setprop debug.huawei.hms.analytics.app .none.
Enter fullscreen mode Exit fullscreen mode

Result

Image description

Tips and Tricks

  1. Make sure you are already registered as a Huawei developer.

  2. Set min SDK version to 21 or later, otherwise you will get AndriodManifest to merge issue.

  3. Make sure you have added the agconnect-services.json file to the app folder.

  4. Make sure you have added the SHA-256 fingerprint without fail.

  5. Make sure all the dependencies are added properly.

  6. If you get the 6003 error code, there may be SHA-256 certificate issue.

Conclusion

In this article, we have learnt how integrate the Huawei Account kit and Analytics Kit in application using Android Studio and Kotlin. We also learnt the Application details and how does this application works and other than that Account Kit, HMS core provides a wider range of services to enhance the user experience with the Huawei platform. We have learnt the steps to create projects and steps to integrate the account kit and analytics kit.

Reference

Account Kit - Official document

Account Kit - Training Video

Analytics Kit - Official document

Top comments (0)