Integration of Huawei Ads Kit and Analytics Kit in Money Management Android app (Kotlin) – Part 2
Tags: ads, analytics, kotlin, android
Published: 2022-04-18 07:00:27


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0dge2am0gizjx5ybuiy.jpg)
**Introduction**
In this article, we can learn how to integrate the **Huawei Analytics Kit** and **Ads Kit** in Money Management app along with that will display the **Income** and **Expense list** of the users. The main intention of this app is to track the daily spending's of the user. Based on this tracking, users can plan their spending's on daily, monthly or yearly basis.

So, I will provide the series of articles on this Money Management App, in upcoming articles I will integrate other Huawei Kits.

**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/9fv6jscwpg9coc2kuywl.PNG)

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

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

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

**Ads Kit**
Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.
**HMS Ads Kit** has 7 types of Ads kits. Now we can implement **Rewarded Ads** in this application.
Rewarded ads are full-screen video ads that allow users to view in exchange for in-app rewards.

**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/9v626cg8s5uu8u9yurf4.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/w7c99f84bk7tbcfb3eib.png)
- Enter **SHA-256 certificate fingerprint** and click **Save** button, as follows.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alnlx2qq06ezeoioa5d8.png)
Note: Above steps from Step 1 to 7 is common for all Huawei Kits.
- Click **Manage APIs** tab and enable **HUAWEI Analytics**.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gpd9rd495l6nx0peozyk.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 Analytics Kit
implementation 'com.huawei.hms:hianalytics:6.4.0.300'
// Huawei Ads Kit
implementation 'com.huawei.hms:ads-lite:13.4.51.300'301'
// Recycler View
implementation 'androidx.recyclerview:recyclerview:1.2.1'
```
- Now Sync the gradle.
- Add the required permission to the **AndroidManifest.xml** file.

```
// Analytics Kit
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA" />
```
**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 Analytics.

```
class MainActivity : AppCompatActivity() {


    // Initialize the Analytics
    var  mInstance: HiAnalyticsInstance? = null

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

        btn_login.setOnClickListener(mOnClickListener)
        // Initialize the Analytics function
        initAna()

    }

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


    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("email", data!!.extras!!.getString("email" ))
                bundle.putString("name", data.extras!!.getString("name"))
                bundle.putString("phone", data!!.extras!!.getInt("phone").toString())
                bundle.putString("marks", data!!.extras!!.getFloat("86.5").toString())
                mInstance!!.onEvent(HAEventType.SIGNIN, bundle)

                Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
            }
        }
    }

}
```

In the **Home.kt** we can find the business logic for Rewarded Ads.

```
class Home : AppCompatActivity() {

    private var rewardedAd: RewardAd? = null

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)

        btn_income.setOnClickListener {
            rewardAdShow()
        }
        btn_expense.setOnClickListener {
            val intent = Intent(this, ExpenseActivity::class.java)
            startActivity(intent)
        }
        loadRewardAd()

    }

    private fun navigateToScreen(){
        val intent = Intent(this, IncomeActivity::class.java)
        startActivity(intent)
    }

    // Load a rewarded ad
    private fun loadRewardAd() {
        if (rewardedAd == null) {
            rewardedAd = RewardAd(this, "testx9dtjwj8hp")
        }
        val rewardAdLoadListener: RewardAdLoadListener = object : RewardAdLoadListener() {
            override fun onRewardedLoaded() {
                showToast("onRewardedLoaded")
            }
            override fun onRewardAdFailedToLoad(errorCode: Int) {
                navigateToScreen()
                showToast("onRewardAdFailedToLoad errorCode is :$errorCode")
            }
        }
        rewardedAd!!.loadAd(AdParam.Builder().build(), rewardAdLoadListener)
    }

   // Display a rewarded ad
    private fun rewardAdShow() {
        if (rewardedAd!!.isLoaded) {
            rewardedAd!!.show(this, object : RewardAdStatusListener() {
                override fun onRewardAdOpened() {
                    showToast("onReward Ad Opened")
                }
                override fun onRewardAdFailedToShow(errorCode: Int) {
                    showToast("onReward AdFailed ToShow errorCode is :$errorCode")
                    navigateToScreen()
                }
                override fun onRewardAdClosed() {
                    showToast("onReward Ad Closed")
                    navigateToScreen()
                    loadRewardAd()
                }
                override fun onRewarded(reward: Reward) {
                    loadRewardAd()
                }
            })
        }
    }

    private fun showToast(text: String) {
        runOnUiThread {
            Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
        }
    }

}
```

In the **IncomeActivity.kt** we can find the business logic for Recycler View of Income List.

```
class IncomeActivity : AppCompatActivity() {

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

        val recyclerView = income_recycler_view
        val adapter = IncomeAdapter(this)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)

    }

}
```

Create the **IncomeAdapter.kt** adapter class to hold the Income list.

```
class IncomeAdapter internal constructor (context: Context): RecyclerView.Adapter<IncomeAdapter.ViewHolder>(){

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var prices = arrayOf(" +5000", " +1000", " +500", " +900", " +10000", " +700", " +4000", " +850")
    private var images = intArrayOf(R.drawable.bank_deposit, R.drawable.crypto, R.drawable.mutual, R.drawable.post,
                         R.drawable.rainday, R.drawable.real, R.drawable.retirement_plan, R.drawable.stock)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): IncomeAdapter.ViewHolder {
        val itemView = inflater.inflate(R.layout.income_list, parent, false)
        return IncomeAdapter.ViewHolder(itemView)
    }
    override fun onBindViewHolder(holder: IncomeAdapter.ViewHolder, position: Int) {
        holder.itemPrice.text = prices[position]
        holder.itemImage.setImageResource(images[position])
    }
    override fun getItemCount(): Int {
        return prices.size
    }

    class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        var itemPrice: TextView = itemView.findViewById(R.id.amount)
        var itemImage: ImageView = itemView.findViewById(R.id.images)
    }

}
```

In the **ExpenseActivity.kt** we can find the business logic for Recycler View of Expense List.

```
class ExpenseActivity : AppCompatActivity() {
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_expense)

        val recyclerView = expense_recycler_view
        val adapter = ExpenseAdapter(this)
        recyclerView.adapter = adapter
        recyclerView.layoutManager = LinearLayoutManager(this)

    }
    
}

```

Create the **ExpenseAdapter.kt** adapter class to hold the Expense list.

```
class ExpenseAdapter internal constructor (context: Context): RecyclerView.Adapter<ExpenseAdapter.ExpenseViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var expenseprices = arrayOf(" -1000", " -2000", " -1500", " -500", " -2000", " -7000", " -2500", " -6500")
    private var expenseimages = intArrayOf(R.drawable.clothes, R.drawable.food, R.drawable.grocery, R.drawable.icecream,
                                R.drawable.movie, R.drawable.resorts, R.drawable.shooping, R.drawable.trip)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExpenseAdapter.ExpenseViewHolder {
        val itemView = inflater.inflate(R.layout.expense_list, parent, false)
        return ExpenseAdapter.ExpenseViewHolder(itemView)
    }
    override fun onBindViewHolder(holder: ExpenseAdapter.ExpenseViewHolder, position: Int) {
        holder.expensePrice.text = expenseprices[position]
        holder.expenseImage.setImageResource(expenseimages[position])
    }
    override fun getItemCount(): Int {
        return expenseprices.size
    }

    class ExpenseViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
        var expensePrice: TextView = itemView.findViewById(R.id.expense_amount)
        var expenseImage: ImageView = itemView.findViewById(R.id.expense_images)
    }

}
```

In the **activity_home.xml** we can create the UI screen for buttons.

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    tools:context=".Home">

    <Button
        android:id="@+id/btn_income"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="70dp"
        android:textAlignment="center"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="@color/dot_dark_screen3"
        android:padding="10dp"
        android:textAllCaps="false"
        android:text="Income" />
    <Button
        android:id="@+id/btn_expense"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:textAlignment="center"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="@color/dot_dark_screen4"
        android:padding="8dp"
        android:textAllCaps="false"
        android:text="Expenses" />
    <Button
        android:id="@+id/btn_trans"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:textAlignment="center"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:textColor="@color/dot_dark_screen5"
        android:padding="8dp"
        android:textAllCaps="false"
        android:text="Transactions" />
</LinearLayout>
```

In the **activity_income.xml** we can create the UI screen Recycler Items.

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    tools:context=".IncomeActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:layout_gravity="center_horizontal"
        android:text="Income"
        android:textStyle="bold"
        android:textColor="#025022"
        android:layout_marginBottom="20dp"
        android:textSize="30sp"/>
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/income_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
```
In the **activity_expense**.xml we can create the UI screen Recycler Items.

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    tools:context=".ExpenseActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:layout_gravity="center_horizontal"
        android:text="Expenses"
        android:textStyle="bold"
        android:textColor="#F1066F"
        android:layout_marginBottom="20dp"
        android:textSize="30sp"/>
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/expense_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
```
In the **income_list.xml** we can create the custom view of Recycler UI Items.

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="-3dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="0dp"
    android:layout_marginBottom="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/images"
            android:layout_width="130dp"
            android:layout_height="80dp"
            android:layout_gravity="left"
            android:layout_marginStart="0dp"
            android:layout_marginLeft="0dp" />
        <TextView
            android:id="@+id/amount"
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:layout_marginLeft="45dp"
            android:text="Item"
            android:textSize="36sp"
            android:layout_gravity="end"
            android:textAlignment="viewEnd"
            android:textColor="@android:color/holo_green_light"
            android:textStyle="bold" />
    </LinearLayout>

</androidx.cardview.widget.CardView>
```

In the **expense_list.xml** we can create the custom view of Recycler UI Items.

```
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="-3dp"
    android:layout_marginTop="5dp"
    android:layout_marginRight="0dp"
    android:layout_marginBottom="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/expense_images"
            android:layout_width="130dp"
            android:layout_height="80dp"
            android:layout_gravity="left"
            android:layout_marginStart="0dp"
            android:layout_marginLeft="0dp" />
        <TextView
            android:id="@+id/expense_amount"
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            android:layout_marginLeft="45dp"
            android:text="Item"
            android:textSize="36sp"
            android:layout_gravity="end"
            android:textAlignment="viewEnd"
            android:textColor="@color/purple_200"
            android:textStyle="bold" />
    </LinearLayout>

</androidx.cardview.widget.CardView>
```

**Demo**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebs3k5vwre7fjybrdqgk.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 how to integrate the **Huawei Analytics Kit** and **Ads Kit** in Money Management app along with that will display the **Income** and **Expense** list of the users. The main intention of this app is to track the daily spending's of the user. Based on this tracking, users can plan their spending's on daily, monthly or yearly basis. So, I will provide the series of articles on this Money Management App, in upcoming articles will integrate other Huawei Kits.

I hope you have read this article. If you found it is helpful, please provide likes and comments.

Reference
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)
Ads Kit - [Documentation](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-reward-0000001050066917)
Ads Kit – [Training Video](https://developer.huawei.com/consumer/en/training/course/video/101614748910616026)