Pygmy Collection Application Part 4 (Analytics Kit Custom Events)
Tags: android, java, hms, huawei
Published: 2022-02-28 14:49:10

## Introduction
In my last article, I have explained how to integrate an account kit finance application. Have a look into [Pygmy collection application Part 1 (Account kit)](https://forums.developer.huawei.com/forumPortal/en/topic/0201684625183310089?fid=0101187876626530001).
In this article, we will learn how to **integrate Analytics kit** kit in Pygmy collection finance 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.
**What You Need**
About 10 minutes
A favorite text editor or IDE(For me Android Studio)
JDK 1.8 or later
Gradle 4+
SDK platform 19
**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 behavior**, 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, lets 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 allowss 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 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.

**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 couple of steps as follows.
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](https://developer.huawei.com/consumer/en/doc/10104) account in AppGallery Connect. If you are already developer ignore this step.

**Step 2:** Create an app by referring to [Creating a Project](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createproject) and [Creating an App in the Project](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-get-started#createapp)

**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.

**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 Ads Kit**
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**.

```
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
   implementation 'com.huawei.hms:hianalytics:5.1.0.300'
}

```
Root level gradle dependencies.

```
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:

```
<application
...
android:usesCleartextTraffic="true"
>
...
</application>
```

**Step 4:** Initialize Ads kit activity or application class.
**Step 5:** Build Application.

**HuaweiUserProperty.java**

```
public class HuaweiUserProperty {
    public enum KeyName {
        USER_CUSTOMER_ID("user_session_id"),
        USER_PHONE_NUMBER("user_phone_number");
        String textValue;

        KeyName(String textValue) {
            this.textValue = textValue;
        }

        public String textValue() {
            return textValue;
        }
    }
}
```

**HuaweiEvenParams.java**

```
public enum HuaweiEventParams {
    temp;
    public enum EventName {
        TAP("tap"),
        OPEN("open");
        String textValue;

        EventName(String textValue) {
            this.textValue = textValue;
        }

        public String textValue() {
            return textValue;
        }
    }

    public enum Key {
        PREVIOUS_SCREEN_NAME("previous_screen_name"),
        SCREEN_NAME("screen_name"),
        UI_ELEMENT("ui_element_name"),
        DESCRIPTION("description_key"),
        PARENT_SCREEN_NAME("parent_screen_name"),
        CUSTOMER_ID("customer_id"),
        MODEL_NUMBER("model_number");

        String textValue;

        Key() {
        }

        Key(String textValue) {
            this.textValue = textValue;
        }

        String textValue() {
            return this.textValue;
        }
    }

    public enum ScreenName {

        PLATFORM_APP_LAUNCHER("platform_app_launcher"),
        GRANT_PERMISSION_DIALOG_SCREEN("grant_permission_dialog_screen"),
        CONFIGURATION_SCREEN("configuration_screen"),
        MAIN_SPLASH("main_splash"),
        LOGIN_SCREEN("login_screen"),
        COLLECTION_SCREEN("collection_screen"),
        PHONE_NUMBER_SCREEN("phone_number_screen"),
        PHONE_CONF_POPUP("phone_number_confirmation_popup"),
        OTP_SCREEN("otp_screen"),
        PROFILE_POPUP("profile_popup"),
        SOCIAL_MEDIA_LOGIN("social_media_login_screen"),
        MAIN_HOME_DASHBOARD("main_home_dashboard"),
        MAIN_HOME_NAVIGATION("main_home_navigation"),
        PROFILE_SCREEN("profile_screen"),
        IMAGE_SELECTION_POPUP("image_selection_popup"),
        PHONE_NUMBER_POPUP("phone_number_popup"),
        FEEDBACK_SCREEN("feedback_screen"),
        NAVIGATION_SCREEN("navigation_screen");


        String textValue;

        ScreenName(String textValue) {
            this.textValue = textValue;
        }

        String textValue() {
            return this.textValue;
        }
    }

    public enum Description {
        BACKGROUND_POPUP("background_popup"),
        OPEN_PHONE_NUMBER_SCREEN("open_phone_number_screen"),
        OPEN_TERMS_AND_CONDITION_SCREEN("open_terms_and_condition"),
        OPEN_PHONE_NUMBER_CONFIRMATION_POPUP("open_phone_number_confirmation_popup"),
        OPEN_OTP_SCREEN("open_otp_screen"),
        PHONE_NUMBER_SCREEN("phone_number_screen"),
        OPEN_PROFILE_POPUP("open_profile_popup"),
        SOCIAL_MEDIA_LOGIN_SCREEN("social_media_login_screen"),
        MAIN_HOME_DASHBOARD("main_home_dashboard"),
        OPEN_PROFILE_SCREEN("open_profile_screen"),
        OPEN_RECONNECTION_POPUP("open_reconnection_popup"),
        OPEN_MAIN_HOME_NAVIGATION("open_main_home_navigation"),
        OPEN_IMAGE_SELECTION_POPUP("open_image_selection_popup"),
        EDIT_PHONE_NUMBER_POPUP("edit_phone_number_popup"),
        OPEN_GALLERY("open_gallery"),
        OPEN_CAMERA("open_camera"),
        OPEN_CONTACT_SCREEN("open_contact_screen"),
        OPEN_SHARE_SCREEN("show_share_screen"),
        OPEN_LOGIN_SCREEN("open_login_screen"),
        OPEN_HOME_SCREEN("open_home_screen")
        ;


        String textValue;

        Description(String textValue) {
            this.textValue = textValue;
        }

        String textValue() {
            return this.textValue;
        }
    }


    public enum UiElementName {
        SWIPE_LEFT("swipe_left"),
        SWIPE_RIGHT("swipe_right"),
        SKIP_BUTTON("skip_button"),
        NEXT_BUTTON("next_button"),
        OK_BUTTON("ok_button"),
        CANCEL_BUTTON("cancel_button"),
        RESEND_OTP_BUTTON("resend_button"),
        GALLERY_BUTTON("gallery_button"),
        CATURE_FROM_CAMERA_BUTTON("cature_from_camera_button"),
        DONE_BUTTON("done_button"),
        COLLECTION_BUTTON("collection_button"),
        GALLARY_BUTTON("gallary_button");
        String textValue;

        UiElementName(String textValue) {
            this.textValue = textValue;
        }

        String textValue() {
            return this.textValue;
        }
    }


}
```

**HuaweiLog.java**

```
import android.os.Bundle;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HuaweiLog {

    private HuaweiEventParams.EventName eventName;
    private HashMap<String, String> data = new HashMap<>();
    private HashMap<String, ArrayList> testdata = new HashMap<>();

    public HuaweiLog() {
    }

    public HuaweiEventParams.EventName getEventName() {
        return eventName;
    }

    public HuaweiLog setEventName(HuaweiEventParams.EventName eventName) {
        this.eventName = eventName;

        return this;
    }

    public HuaweiLog setPreviousScreenName(HuaweiEventParams.ScreenName previousScreenName) {
        data.put(HuaweiEventParams.Key.PREVIOUS_SCREEN_NAME.textValue(), previousScreenName.textValue());
        return this;
    }

    public HuaweiLog setDescription(HuaweiEventParams.Description description) {
        data.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), description.textValue());
        return this;
    }

    public HuaweiLog setDescription(String description) {
        data.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), description);
        return this;
    }

    public HuaweiLog setCustomerId(String cId) {
        data.put(HuaweiEventParams.Key.CUSTOMER_ID.textValue(), cId);
        return this;
    }

    public HuaweiLog setCustomerMobileNumber(String mobileNumber) {
        data.put(HuaweiEventParams.Key.CUSTOMER_ID.textValue(), mobileNumber);
        return this;
    }

    public HuaweiLog setParentScreenName(HuaweiEventParams.ScreenName parentScreenName) {
        data.put(HuaweiEventParams.Key.PARENT_SCREEN_NAME.textValue(), parentScreenName.textValue());
        return this;
    }

    public HuaweiLog setScreenName(HuaweiEventParams.ScreenName screenName) {
        data.put(HuaweiEventParams.Key.SCREEN_NAME.textValue(), screenName.textValue());
        return this;
    }

    public HuaweiLog setScreenName(String screenName) {
        data.put(HuaweiEventParams.Key.SCREEN_NAME.textValue(), screenName);
        return this;
    }


    public HuaweiLog setUiElementName(String uiElementName) {
        data.put(HuaweiEventParams.Key.UI_ELEMENT.textValue(), uiElementName);
        return this;
    }

    public HuaweiLog setUiElementName(HuaweiEventParams.UiElementName uiElementName) {
        data.put(HuaweiEventParams.Key.UI_ELEMENT.textValue(), uiElementName.textValue());
        return this;
    }

    public HuaweiLog setKeyAndValue(String key, String value) {
        data.put(key, value);
        return this;
    }

    public Bundle toBundle() {
        Bundle bundle = new Bundle();
        try {
            if (data != null && data.size() > 0) {
                for (Map.Entry<String, String> entry : data.entrySet()) {
                    bundle.putString(entry.getKey(), entry.getValue());
                    Log.d("Huawei",entry.getKey()+" "+ entry.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bundle;
    }

    public HuaweiLog setTestDescription(ArrayList list) {
        testdata.put(HuaweiEventParams.Key.DESCRIPTION.textValue(), list);
        return this;
    }
}
```

**HuaweiAnalyticsClient.java**

```
import android.content.Context;
import android.util.Log;

import com.huawei.hms.analytics.HiAnalytics;
import com.huawei.hms.analytics.HiAnalyticsInstance;
import com.huawei.hms.analytics.type.ReportPolicy;
import com.shea.pygmycollection.utils.UserDataUtils;

import java.util.HashSet;
import java.util.Set;

public class HuaweiAnalyticsClient {

    private static final String TAG = HuaweiAnalyticsClient.class.getSimpleName();

    private static HuaweiAnalyticsClient ourInstance;
    private static HiAnalyticsInstance mHuaweiAnalyticsClient;

    private HuaweiAnalyticsClient() {
    }

    public static HuaweiAnalyticsClient getInstance() {
        if (ourInstance == null) {
            ourInstance = new HuaweiAnalyticsClient();
        }
        return ourInstance;
    }


    public void 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);
        if (UserDataUtils.getUserData(context) != null) {
            if (UserDataUtils.getUserId(context) != 0) {
                Integer userId = UserDataUtils.getUserId(context);
                Log.d(TAG, "initAnalytics is called");
                if (userId != null && userId != 0) {
                    setHuaweiUserId(String.valueOf(userId));
                    putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
                } else {
                    setHuaweiUserId("UNKNOWN");
                    putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
                }
            } else {
                setHuaweiUserId("UNKNOWN_USER");
                putHuaweiUserProperty(HuaweiUserProperty.KeyName.USER_PHONE_NUMBER, UserDataUtils.getUserPhoneNumber(context));
            }
        }

        // Used to report an event upon app switching to the background.
        ReportPolicy moveBackgroundPolicy = ReportPolicy.ON_MOVE_BACKGROUND_POLICY;
        // Used to report an event at the specified interval.
        ReportPolicy scheduledTimePolicy = ReportPolicy.ON_SCHEDULED_TIME_POLICY;
        // Set the event reporting interval to 600 seconds.
        scheduledTimePolicy.setThreshold(600);
        Set<ReportPolicy> reportPolicies = new 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);
    }

    public void logEvent(HuaweiLog log) {
        if (mHuaweiAnalyticsClient == null) {
            throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
        }
        try {
            mHuaweiAnalyticsClient.onEvent(log.getEventName().textValue(), log.toBundle());
            Log.d("Huawei", log.getEventName().textValue());
        } catch (Exception e) {
            Log.d(TAG, "Huawei analytics failed" + e.getMessage());
        }
    }

    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);
        }
    }

    public void setHuaweiUserId(String userId) {
        if (mHuaweiAnalyticsClient == null) {
            throw new RuntimeException("HuaweiAnalyticsClient is not initialized. Please call initAnalytics().");
        }

        if (userId == null) {
            mHuaweiAnalyticsClient.setUserId(null);
            return;
        }
        mHuaweiAnalyticsClient.setUserId(userId);
    }

}
```

**AnalyticsUtils.java**

```

import android.util.Log;

public class AnalyticUtils {
    private static final String TAG = AnalyticUtils.class.getSimpleName();

    public static void logHuaweiAnalyticEvent(HuaweiLog huaweiLog) {
        try {
            HuaweiAnalyticsClient.getInstance().logEvent(huaweiLog);
            Log.d(TAG, "Huawei analytics  " + huaweiLog.toString());
        } catch (Exception e) {
            Log.d(TAG, "Huawei analytics failed");
        }
    }
}
```

Now log the events in activity/fragments/dialog

```
AnalyticUtils.logHuaweiAnalyticEvent(new HuaweiLog()
            .setScreenName(HuaweiEventParams.ScreenName.MAIN_SPLASH)
          .setDescription(HuaweiEventParams.Description.OPEN_SHARE_SCREEN)
                .setEventName(HuaweiEventParams.EventName.OPEN)
                .setUiElementName(HuaweiEventParams.UiElementName.GALLARY_BUTTON)
        );


 AnalyticUtils.logHuaweiAnalyticEvent(new HuaweiLog()
                        .setScreenName(HuaweiEventParams.ScreenName.COLLECTION_SCREEN)
                        .setDescription(HuaweiEventParams.Description.OPEN_HOME_SCREEN)
                        .setEventName(HuaweiEventParams.EventName.TAP)
                        .setUiElementName(HuaweiEventParams.UiElementName.COLLECTION_BUTTON));
```

## Result

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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqr45hcwfyj0d581x1vs.PNG)
## Tips and Tricks
Make sure you added **agconnect-service.json** file.
Add internet permission in **AndroidManifest.xml**
Add the below code to download the HMS core apk

```
<application ...>
    <meta-data     
        android:name="com.huawei.hms.client.channel.androidMarket"  
        android:value="false" />
    ...
</application>
```

## Conclusion
In this article, we have learnt what is analytics, why to use analytics kit, where to use, how to use, how to integrate HMS analytics kit and how to add custom events.

## Reference
[Huawei Analytics](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050745149)