Integration of Huawei Account Kit and Analytics Kit in Quiz Android app (Kotlin) – Part 1
Tags: accountkit, analytics, hmscore, kotlin
Published: 2022-05-12 10:15:17



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27uaqrvqzk8y1bjck6gz.png)
**Introduction**
In this article, we can learn how to integrate the **Huawei Account Kit** and **Analytics Kit** in Quiz Application. The quiz application is mainly intended to develop the knowledge for users and also to learn about particular topics. So, I will provide the series of articles on this Quiz App, in upcoming articles I will integrate other Huawei Kits.

**Account Kit**
**Huawei Account Kit** provides for developers with **simple**, **secure**, and **quick sign-in** and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on **Sign In with HUAWEI ID** button to quickly and securely sign in to the app.

**Analytics Kit**
**HUAWEI Analytics Kit** provides analysis models to understand user behaviour and gain in-depth insights into **users**, **products** and **content**. It helps you to gain insight about user behaviour on different platforms based on the **user behaviour events** and **user attributes** reported by through apps.

**AppGallery Connect**
Find the Analytics using AppGallery connect dashboard.
Choose **My Projects > Huawei Analytics > Overview > Project overview**.
Project overview displays the core indicators of current project, such as the number of new users, **User activity, User acquisition, User revisit, New user retention, Active user retention, User characteristics** and **Popular pages** etc. providing a quick overview of the users and how they are using your app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24udz9ccx6l023083f5l.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8gwu22n1s4i374b54oyo.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8f32lp2d51439t4h95i.PNG)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ywri7yppqt883rk4gpf.PNG)

**Requirements**
1. Any operating system (MacOS, Linux and Windows).
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 and above installed.
4. Minimum API Level 24 is required.
5. Required EMUI 9.0.0 and later version devices.

**How to integrate HMS Dependencies**

- First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a [Huawei ID](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148).

- Create a project in android studio, refer [Creating an Android Studio Project](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#1).

- Generate a **SHA-256 certificate fingerprint**.

- To generate **SHA-256 certificate fingerprint**. On right-upper corner of android project click **Gradle**, choose **Project Name > Tasks > android**, and then click **signingReport**, as follows.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50u81aads3s4lb18kjih.png)

Note: Project Name depends on the user created name.

- [Create an App in AppGallery Connect](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0).

- Download the **agconnect-services.json** file from **App information**, copy and paste in android **Project** under **app** directory, as follows.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t4lnyo1c3lx9k5eh0hna.png)

- Enter **SHA-256 certificate fingerprint** and click **Save** button, as follows.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54faqckxw9q2iz0shrd3.png)

- Click **Manage APIs** tab and enable **Account Kit** and **HUAWEI Analytics**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ecm50bvoo3tnu6ee4s2r.jpg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6123dhfw33x3k2h1ynl2.jpg)

- Add the below maven URL in **build.gradle(Project)** file under the repositories of **buildscript**, **dependencies** and **allprojects**, refer [Add Configuration](https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0).

```
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
```
- Add the below plugin and dependencies in **build.gradle(Module)** file.

```
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Account Kit
implementation 'com.huawei.hms:hwid:6.3.0.301'
// Huawei Analytics Kit
implementation 'com.huawei.hms:hianalytics:6.4.0.300'
```
- Now Sync the gradle.
- Add the required permission to the **AndroidManifest.xml** file.
```
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
```

**Let us move to development**
I have created a project on Android studio with empty activity let us start coding.
In the **MainActivity.kt** we can find the business logic for Huawei login button.
```
class MainActivity : AppCompatActivity() {

    // Account Kit variables
    private var mAuthManager: AccountAuthService? = null
    private var mAuthParam: AccountAuthParams? = null
    // Analytics Kit - Initialize the Analytics
    var  mInstance: HiAnalyticsInstance? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Account kit button click Listener
        btn_login.setOnClickListener(mOnClickListener)

        // Initialize the Analytics function
        initAna()

    }

    // Account kit, method to send an authorization request.
    private fun signIn() {
        mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
            .setIdToken()
            .setAccessToken()
            .setProfile()
            .createParams()
        mAuthManager = AccountAuthManager.getService(this@MainActivity, mAuthParam)
        startActivityForResult(mAuthManager?.signInIntent, 1002)
    }

    private val mOnClickListener: View.OnClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            when (v?.id) {
                R.id.btn_login -> signIn()
            }
        }
    }

    // Process the authorization result
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1002 ) {
            val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
            if (authAccountTask.isSuccessful) {
                // Analytics data to send custom events
                val bundle = Bundle()
                bundle.putString("name", data!!.extras!!.getString("name" ))
                bundle.putString("email", data!!.extras!!.getString("email" ))
                mInstance!!.onEvent(HAEventType.SIGNIN, bundle)
                Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
                val intent = Intent(this@MainActivity, Home::class.java)
                startActivity(intent)
            } else {
                Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
            }
        }
    }

    private fun initAna() {
        // Enable Analytics Kit Log
        HiAnalyticsTools.enableLog()
        // Generate the Analytics Instance
        mInstance = HiAnalytics.getInstance(this)
        // Enable collection capability
        mInstance?.setAnalyticsEnabled(true)
    }

}
```

In the **activity_main.xml** we can create the UI screen.
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:ignore="ExtraText,MissingConstraints">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="273dp"
            android:background="@drawable/blue_bg">
            <ImageView
                android:layout_width="77dp"
                android:layout_height="77dp"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="93dp"
                android:src="@drawable/quiz_icon" />
        </FrameLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="62dp"
            android:layout_marginTop="37dp"
            android:layout_marginRight="62dp"
            android:background="@drawable/blue_border_rounded_cornwe">

            <EditText
                android:id="@+id/edt_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/username_icon"
                android:background="@android:color/transparent"
                android:hint="Email"
                android:inputType="textEmailAddress"
                android:maxLines="1"
                android:paddingLeft="17dp"
                android:paddingTop="15dp"
                android:paddingBottom="15dp"
                android:textSize="13sp">
            </EditText>

            <ImageView
                android:id="@+id/username_icon"
                android:layout_width="18dp"
                android:layout_height="13dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="17dp"
                android:src="@drawable/email" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="62dp"
            android:layout_marginTop="13dp"
            android:layout_marginRight="62dp"
            android:background="@drawable/blue_border_rounded_cornwe">

            <EditText
                android:id="@+id/edt_pass"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@id/pass_icon"
                android:background="@android:color/transparent"
                android:hint="Password"
                android:inputType="textPassword"
                android:maxLength="10"
                android:maxLines="1"
                android:paddingLeft="17dp"
                android:paddingTop="15dp"
                android:paddingBottom="15dp"
                android:textSize="13sp">
            </EditText>

            <ImageView
                android:id="@+id/pass_icon"
                android:layout_width="18dp"
                android:layout_height="13dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="17dp"
                android:src="@drawable/password" />
        </RelativeLayout>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="62dp"
            android:layout_marginTop="19dp"
            android:layout_marginRight="62dp"
            android:background="@drawable/blue_fill__rounded_color"
            android:gravity="center"
            android:paddingTop="14dp"
            android:paddingBottom="14dp"
            android:text="Login"
            android:textColor="@color/white"
            android:textSize="13sp">
        </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="12dp"
            android:paddingTop="14dp"
            android:paddingBottom="14dp"
            android:text="FORGOT PASSWORD ?"
            android:textColor="#1566e0"
            android:textSize="12sp">
        </TextView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="25dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="14dp"
            android:gravity="center"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="or"
                android:textColor="#0E0E0E"
                android:textSize="15sp">
            </TextView>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="25dp"
            android:gravity="center"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/btn_login"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:src="@drawable/huawei_icon" />
            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:src="@drawable/facebook_icon" />
            <ImageView
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_marginRight="20dp"
                android:src="@drawable/instagram_icon" />
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
```

**Demo**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mf9a8413jgnxj44dpfbo.gif)

**Tips and Tricks**
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to **24** or later, otherwise you will get **AndriodManifest** merge issue.
3. Make sure you have added the **agconnect-services.json** file to app folder.
4. Make sure you have added **SHA-256 fingerprint** without fail.
5. Make sure all the dependencies are added properly.

**Conclusion**
In this article, we have learned to integrate the **Huawei Account Kit** and **Analytics Kit** in **Quiz Application**. The quiz application is mainly intended to develop the knowledge for users and also to learn about particular topics. So, I will provide the series of articles on this Quiz App, in upcoming articles I will integrate other Huawei Kits.
I hope you have read this article. If you found it is helpful, please provide likes and comments.

**Reference**
Account Kit – [Documentation](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/get-channel-0000001074587201)
Account Kit – [Training Video](https://developer.huawei.com/consumer/en/training/course/video/101583015541549183)
Analytics Kit – [Documentation](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050705116)
Analytics Kit – [Training Video](https://developer.huawei.com/consumer/en/training/course/video/101626701193106319)