Pygmy Collection Application Part 2 (Ads Kit)
Tags: android, java, hms, huawei
Published: 2022-02-09 05:43:58

## **Introduction**

In my last article, I have explained how to integrate account kit finance application. Have a look into Pygmy collection application Part 1 (Account kit).

In this article, we will learn how to integrate Splash Ads kit in Pygmy collection finance application.

First we will understand why we need Ads kit.

Every company makes or builds some kind of product. Building or developing is not a big deal but marketing is the big deal to earn money.

**Traditional marketing**
1. Putting Banners in City.
2. Advertisement in Radio or TV or newspaper.
3. Painting on the wall.
4. Meeting distributors with sample of product.

So, now let’s understand the drawback of each traditional marketing.

**1. Putting Banners in City**
You know in one city there will be many localities, sub localities streets, area, main roads, service roads etc. How many places you will put banners? If you consider one city only you need to put so many banners and when it comes to multiple cities and globe level. Imagine you need so many marking people across all the cities. And also think about cost. As an organization they need profit with less investment. But when they go with banner advertisement they have to spent lot of money for marketing only.

**2. Advertisement in Radio or TV or newspaper**
Now let’s take radio or TV advertisement and newspaper. Let’s take example in one home there are 5 people. How many TV’s will be there?

Max 1 or 2.

What about phones?
Its mobile world everyone will have phone. 5 member’s means 5 phones some times more than 5 because few people will have 2-3 phones.

There are thousands of channels. If you want to give advertisement how many channels you will give, 1 or 2 or max 10 channels you will give advertisement. Do you think all people will watch only those channels which you have provided advertisement?

Radio and newspaper also right. Nowadays who will listen radio? Now everyone is moving towards the social media. And also everybody is reading news in mobile application nobody takes newspaper because people started think about paper is waste and people are thinking about environment.

**3. Painting on the wall.**
How many houses you will paint? Just think about money and time. As I said earlier, think about multiple cities and multiple streets.

**4. Meeting distributors with sample of product.**
Meeting distributors with sample product. Do you think this will work out? No it won’t work out because all marketing person will not have same marketing knowledge. On top of that you should have to give training about product for them. Even after training about product they will miss some main key points of product while explaining distributors. If distributors are not convinced about product which is explained by marketing person straight away they will say “no to your product”.

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. In this way, they can reach their target audience more easily and they can measure their efficiency by analysing many parameters such as ad display and the number of clicks. In addition to in-app purchases, the most common method used by mobile developers to generate revenue from their application is to create advertising spaces for advertisers.

In this sense, Huawei Ads meets the needs of both advertisers and mobile developers. So what is this HMS Ads Kit, let’s take a closer look.

**Now let us understand Huawei Ads.**
Ads Kit leverages the vast user base of Huawei devices and Huawei's extensive data capabilities to provide you with the Publisher Service, helping you to monetize traffic. Meanwhile, it provides the advertising service for advertisers to deliver personalized campaigns or commercial ads to Huawei device users.

The video on this page introduces traffic monetization through Ads Kit, advantages of HUAWEI Ads Publisher Service, and the process for advertisers to display ads.

You can click [here](https://developer.huawei.com/consumer/en/training/detail/101582707399567035) to watch the MOOC video about Ads Kit.

**Types of Huawei Ads**
- Banner Ads.
- Native Ads.
- Rewarded Ads.
- Interstitial Ads.
- Splash Ads.
- Roll Ads.

**Banner Ads.**
Banner ads are rectangular images that occupy a spot within an app's layout, either at the top, middle, or bottom of the device screen. Banner ads refresh automatically at regular intervals. When a user clicks a banner ad, the user is redirected to the advertiser's page.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs17einghshna2q162hn.png)
**Native Ads.**
Native ads can be images, text, or videos, which are less disruptive and fit seamlessly into the surrounding content to match your app design. You can customize native ads as needed.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8gfi3fh4qzjzutjk6ka.png)
**Rewarded Ads.**
Rewarded ads are full-screen video ads that allow users to view in exchange for in-app rewards.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16q28doe01n2417zhwur.png)
**Interstitial Ads.**
Interstitial ads are full-screen ads that cover the interface of an app. Such an ad is displayed when a user starts, pauses, or exits an app, without disrupting the user's experience.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0lc1fmk9zh0ct8150aeu.png)
**Splash Ads.**
Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed. You need to design a default slogan image for the app in advance, and ensure that the default slogan image is displayed before a splash ad is loaded, enhancing user experience.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/emoygp4y37n27xaxxizb.png)
**Rolls Ads.**
Roll ads are displayed as short videos or images, before, during, or after the video content is played.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f7dptkgwl28u7hj81r2x.png)
**How to integrate Ads Kit**
1. Configure the application on the AGC.
2. Client application development process.
3. Testing a Splash Ad.

**Configure application on the AGC**
Follow the steps
Step 1: We need to [register as a developer](https://developer.huawei.com/consumer/en/doc/start/registration-and-verification-0000001053628148) account in AppGallery Connect. If you are already a 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-android-0000001058210705)
Step 3: Set the data storage location based on the current location.
Step 4: Generating a Signing Certificate Fingerprint.
Step 5: Configuring the Signing Certificate Fingerprint.
Step 6: Download your agconnect-services.json file, paste it into the app root directory.

**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:ads:3.4.47.302'
}

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

**SplashScreen.java**

```
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.FrameLayout;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.huawei.hms.ads.AdListener;
import com.huawei.hms.ads.AdParam;
import com.huawei.hms.ads.AudioFocusType;
import com.huawei.hms.ads.BannerAdSize;
import com.huawei.hms.ads.HwAds;
import com.huawei.hms.ads.banner.BannerView;
import com.huawei.hms.ads.splash.SplashAdDisplayListener;
import com.huawei.hms.ads.splash.SplashView;
import com.shea.pygmycollection.R;
import com.shea.pygmycollection.huaweianalytics.AnalyticUtils;
import com.shea.pygmycollection.huaweianalytics.HuaweiAnalyticsClient;
import com.shea.pygmycollection.huaweianalytics.HuaweiEventParams;
import com.shea.pygmycollection.huaweianalytics.HuaweiLog;
import com.shea.pygmycollection.utils.PygmyNavigator;
import com.shea.pygmycollection.utils.UserDataUtils;

public class SplashScreen extends AppCompatActivity {

    private static final int TIME_OUT = 3000;
    // "testq6zq98hecj" is a dedicated test ad unit ID. Before releasing your app, replace the test ad unit ID with the formal one.
    private static final String AD_ID = "testd7c5cewoj6";
    private static final int AD_TIMEOUT = 10000;
    private static final int MSG_AD_TIMEOUT = 1001;
    private static final String TAG = SplashScreen.class.getSimpleName();
    SplashView splashView;
    /**
     * Pause flag.
     * On the splash ad screen:
     * Set this parameter to true when exiting the app to ensure that the app home screen is not displayed.
     * Set this parameter to false when returning to the splash ad screen from another screen to ensure that the app home screen can be displayed properly.
     */
    private boolean hasPaused = false;
    // Callback processing when an ad display timeout message is received.
    private Handler timeoutHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (SplashScreen.this.hasWindowFocus()) {
                jump();
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        // Initialize the HUAWEI Ads SDK.
        HwAds.init(this);
        splashView = findViewById(R.id.splash_ad_view);
       // AGConnectCrash.getInstance().testIt(this);
        AGConnectCrash.getInstance().enableCrashCollection(true);
        AnalyticUtils.logHuaweiAnalyticEvent(new HuaweiLog()
                .setScreenName(HuaweiEventParams.ScreenName.MAIN_SPLASH)
                .setDescription(HuaweiEventParams.Description.OPEN_SHARE_SCREEN)
                .setEventName(HuaweiEventParams.EventName.OPEN)
                .setUiElementName(HuaweiEventParams.UiElementName.GALLARY_BUTTON)
        );
        loadAd();
    }

    SplashAdDisplayListener adDisplayListener = new SplashAdDisplayListener() {
        @Override
        public void onAdShowed() {
            // Called when an ad is displayed.
            Log.d(TAG, "onAdShowed");
            AGConnectCrash.getInstance().log("onAdShowed");
        }

        @Override
        public void onAdClick() {
            // Called when an ad is clicked.
            Log.d(TAG, "onAdClick");
            AGConnectCrash.getInstance().log(Log.INFO, "OnAClick");
        }
    };

    /**
     * When the ad display is complete, the app home screen is displayed.
     */
    private void jump() {
        if (!hasPaused) {
            hasPaused = true;
            if (UserDataUtils.isUserLoggedIn(SplashScreen.this)) {
                PygmyNavigator.navigateToHomeScreen(SplashScreen.this);
            } else {
                PygmyNavigator.navigateToLoginScreen(SplashScreen.this);
            }
            finish();
        }
    }

    /**
     * Set this parameter to true when exiting the app to ensure that the app home screen is not displayed.
     */
    @Override
    protected void onStop() {
        // Remove the timeout message from the message queue.
        timeoutHandler.removeMessages(MSG_AD_TIMEOUT);
        hasPaused = true;
        super.onStop();
    }

    /**
     * Set this parameter to false when returning to the splash ad screen from another screen to ensure that the app home screen can be displayed properly.
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        hasPaused = false;
        jump();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void loadAd() {
        int orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        AdParam adParam = new AdParam.Builder().build();
        SplashView.SplashAdLoadListener splashAdLoadListener = new SplashView.SplashAdLoadListener() {
            @Override
            public void onAdLoaded() {
                // Called when an ad is loaded successfully.
            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Called when an ad fails to be loaded. The app home screen is then displayed.
                jump();
            }

            @Override
            public void onAdDismissed() {
                // Called when the display of an ad is complete. The app home screen is then displayed.
                jump();
            }
        };
        // Obtain SplashView.
        splashView.setAdDisplayListener(adDisplayListener);
        // Set the default slogan.
        splashView.setSloganResId(R.drawable.ic_baseline_account_balance_wallet_24);
        // Set the audio focus type for a video splash ad.
        splashView.setAudioFocusType(AudioFocusType.GAIN_AUDIO_FOCUS_ALL);
        // Load the ad. AD_ID indicates the ad unit ID.
        splashView.load(AD_ID, orientation, adParam, splashAdLoadListener);
        // Send a delay message to ensure that the app home screen can be properly displayed after the ad display times out.
        timeoutHandler.removeMessages(MSG_AD_TIMEOUT);
        timeoutHandler.sendEmptyMessageDelayed(MSG_AD_TIMEOUT, AD_TIMEOUT);
    }
}
```

**activity_splash_screen.xml**

```

<?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:hwads="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=".ui.activities.SplashScreen"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    android:background="@color/colorAccent">

    <RelativeLayout
        android:id="@+id/logo_area"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:visibility="visible">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="40dp"
            android:orientation="horizontal">


            <ImageView
                android:id="@+id/iv"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_centerInParent="true"
                android:layout_gravity="center"
                android:src="@drawable/splash_image"
                android:visibility="visible" />

            <TextView
                android:id="@+id/appName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginLeft="20dp"
                android:gravity="center"
                android:text="eCollection"
                android:textColor="@android:color/white"
                android:textSize="40sp"
                android:textStyle="bold"
                android:visibility="visible" />


        </LinearLayout>
    </RelativeLayout>

    <!-- Splash ad view. -->

    <com.huawei.hms.ads.splash.SplashView
        android:id="@+id/splash_ad_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/logo_area" />

    <com.huawei.hms.ads.banner.BannerView
        android:id="@+id/hw_banner_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        hwads:adId="testw6vs28auh3"
        android:visibility="gone"
        hwads:bannerSize="BANNER_SIZE_360_57"/>

</RelativeLayout>
```

**3. Testing a Splash Ads**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/041jsstwdo3tn97r4b24.PNG)
## Result
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kx97m7bnzo86xhh85ym.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fa0k9u0qxhwy0qtjrc6d.png)
  
## Tips and Tricks
Make sure you added **agconnect-service.json** file.
If your app can run both on Huawei mobile phones and non-Huawei Android phones (**outside the Chinese mainland**), integrate the HUAWEI Ads SDK (com.huawei.hms:ads) into your app.
If your app can run only on Huawei mobile phones, integrate the HUAWEI Ads Lite SDK (**com.huawei.hms:ads-lite**).
Add internet permission in **AndroidManifest.xml**

## Conclusion
In this article, we have learnt what the traditional marketing. Drawbacks of traditional marketing and Types of Huawei Ads, How to integrate **Huawei Splash Ads**.

## Reference
[Huawei Splash Ads](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-splash-0000001050066919)
[Official Huawei Ads kit](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-introduction-0000001070671805)