DEV Community

HMS Community
HMS Community

Posted on

Splash season is on! Integration of Huawei Ads Kit (Splash Ads) in Application using React Native

Image description

Introduction

In this article, I will explain how to integrate Huawei Ads Kit in an Application using React Native. I will be using Splash Ads. Huawei Ads kit offers Splash Ad to use in the business to achieve certain business and advertisement goals by following the digital marketing practices.

Ads Kit

Huawei 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.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Splash Ads in this application.

Requirements

  1. JDK version: 1.7 or later
  2. Android Studio version: 3.X or later
  3. minSdkVersion: 21 or later
  4. targetSdkVersion: 31 (recommended)
  5. compileSdkVersion: 29 (recommended)
  6. Gradle: 4.1 or later (recommended)
  7. Must have a Huawei Developer Account
  8. Must have a Huawei phone with HMS 4.0.0.300 or later and running EMUI 4.0 or later.
  9. React Native environment with Android Studio, Node Js and Visual Studio code.

Major Dependencies

  1. React Native CLI : 2.0.1
  2. React Native Ads Kit SDK : 4.0.4
  3. React-native-hms-ads gradle dependency.

Preparation

In order to develop the HMS react native apps, following steps are mandatory:

  • Create an app or project in the Huawei AppGallery Connect.

  • Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.

  • Create a react native project. Use the following command
    react-native init project name

  • Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.

  • Run below command under project directory using CLI if you cannot find node modules.
    npm install & npm link

Integration

  • Configure android level build.gradle

Add to buildscript/repositories and allprojects/repositories
maven {url 'http://developer.huawei.com/repo/'}

  • Configure app level build.gradle

Add to dependencies
Implementation project (“: react-native-hms-ads”)

  • Linking the HMS Ads Kit Sdk

Run below command in the project directory
react-native link react-native-hms-ads

  • Adding permissions

Add below permissions to Android.manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Sync Gradle.

*Development *

To successfully run Splash ads in application, we would need to:

  1. Creating an Splash Ad.
  2. Setting Ad Slot ID.
  3. Customizing Screen
  4. Loading the Ad.
  5. Displaying the Ad.
  6. Listening for Ad Events

Creating an Splash Ad
Splash ad components can be added to an app by importing the HMSSplash module. The following sample code shows how to use the class to add a splash ad component:

import {HMSSplash} from '@hmscore/react-native-hms-ads';
Enter fullscreen mode Exit fullscreen mode

Setting Ad Slot ID
setAdId() method is responsible for setting the Ad Slot. Call the setAdId() method to set an ad slot ID. Below is the code for same.

// creating object for the Ad Slot ID
 const Splash = () => {
                    let SplashAdIds = {};
                    SplashAdIds[SplashMediaTypes.IMAGE] = 'teste9ih9j0rc3';
                    SplashAdIds[SplashMediaTypes.VIDEO] = 'testb4znbuh3n2';
                }  
// creating object for setting up the media type for the ad
const [displayForm, setDisplayForm] = useState({
                    mediaType: SplashMediaTypes.VIDEO,
                    adId: SplashAdIds.video,
                })  
// setting up the ID
 HMSSplash.setAdId(displayForm.adId);
Enter fullscreen mode Exit fullscreen mode

Customizing a Screen
Some parts of the splash ad screen can be customized. Slogan images, logos, and text can be defined before the ad is displayed.

HMSSplash.setLogoText('HMS App')
  .then(res=>console.log(res));
HMSSplash.setCopyrightText('Copyright HMS')
  .then(res=>console.log(res));
//add logo,slogan,wide_slogan in res/drawable folder according to your need and preference.
HMSSplash.setLogoResource("logo") 
  .then(res=>console.log(res));
HMSSplash.setSloganResource("slogan")   .then(res=>console.log(res));
HMSSplash.setWideSloganResource("wide_slogan") 
  .then(res=>console.log(res));

Setting Ad Request Parameters
setAsParam() method is used to set the parameters for the specific ad audience. Below code is called on the button click for the same.
 import {ContentClassification,UnderAge } from 'react-native-hms-ads';
  HMSSplash.setAdParam({
                adContentClassification:
                  ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
                // appCountry: '',
                // appLang: '',
                // belongCountryCode: '',
                gender: Gender.UNKNOWN,
                nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
                // requestOrigin: '',
                tagForChildProtection:
                  TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
                tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
                // targetingContentUrl: '',
              });

Enter fullscreen mode Exit fullscreen mode

Displaying the Ad
Call the show() method to display the ad. The sample code is as follows:

HMSSplash.show()
  .then(res=>console.log(res));

Enter fullscreen mode Exit fullscreen mode

Listen to Ad Events
Listener functions can be triggered with the different ad actions and associated events.

HMSSplash.adLoadedListenerAdd(() => {
      toast('HMSSplash adLoaded');
    });
    // HMSSplash.adLoadedListenerRemove();
    HMSSplash.adFailedToLoadListenerAdd(() => {
      toast('HMSSplash adFailedToLoad');
    });
    // HMSSplash.adFailedToLoadListenerRemove();
    HMSSplash.adDismissedListenerAdd(() => {
      toast('HMSSplash adDismissed');
    });
    // HMSSplash.adDismissedListenerRemove();
    HMSSplash.adShowedListenerAdd(() => {
      toast('HMSSplash adShowed');
    });
    // HMSSplash.adShowedListenerRemove();
    HMSSplash.adClickListenerAdd(() => {
      toast('HMSSplash adClick');
    });
Just in case you want to add a video to your splash screen in an application you can use:
    var navigator = this.props.navigator;
        setTimeout (() => {

          navigator.replace({
                component: LoginScreen,
                 // <-- This is the View you go to
            });
        }, 5000);     //<-- Time until it jumps to "MainView"
    }
    render () {
        return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center',width:null,height:null}}>
               <Video source={require('./images/splashVideo.mp4')}
                     style={{position: 'absolute',
                             top: 0,
                             left: 0,
                             right: 0,
                             bottom: 0,
                             opacity: 0.3}}
                             muted={true}
                             repeat={true}
                             resizeMode="cover"
     />
               <View>{StatusBar.setBackgroundColor('black', true)}</View> 
               {/*<Image style={{ width: windowSize.width, height: windowSize.height}} source={require('./images/splash.png')}></Image>*/} 
            </View>
        );
    }

Enter fullscreen mode Exit fullscreen mode

Testing

Run the below command to build the project
React-native run-android

Result

Image description

Tips and Tricks

  1. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
  2. agconnect-services.json is not required for integrating the hms-ads-sdk.
  3. Make sure you have added SHA-256 fingerprint without fail.
  4. Make sure all the dependencies are added properly.
  5. For project cleaning navigate to android directory and run the below command. gradlew clean

Conclusion

In this article, we can learn about how to integrate Ads Kit and how to add Splash ad in React native project. It provides developers different capabilities to deliver good quality ads content to users.

Reference

Ads Kit: Documentation
Ads Kit: Training Video

Top comments (0)