Implement Realistic 3D Rendering in Three Steps - Huawei Developers

The conventional method of rendering a 3D model and scene with realistic materials is often tedious, making it difficult to standardize into several, simple steps.
Let's see what this process requires:
First, a rich array of texture maps and material images should be prepared according to how detailed and complex the model and scene are. The more complex they are, the more time-consuming the process of collecting such maps and images will be. Of course you can turn to those available on the market, but they could be expensive.
Second, parameters that have to be created from scratch. Most 3D modeling programs require abundant parameters for rendering, and setting or controlling models via parameter adjustment.
Third, work experience. The demand for 3D modelers is increasing, emphasizing the skills and work experience necessary for 3D modeling. As models and scenes are becoming more diverse and delicate, the modeler has a bigger influence over the quality of the models.
Indeed, such requirements — if met — lead to a desirable result. They, however, are also daunting.
Fortunately, there is now an easier solution to this with the material generation capability from 3D Modeling Kit, which is easy-to-use and can create high-quality materials in just three steps.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
​The image on the left shows a complex scene containing multiple objects. Such a scene is common to see in a 3D game. To render it with materials, we just need to:
1. Use an RGB camera to collect images of real materials.
2. Input the images for material generation, which automatically generates the texture maps.
3. Use the maps for rendering.
​The material generation capability from 3D Modeling Kit utilizes AI to streamline and simplify the strenuous process of material generation and rendering, to improve the efficiency of creating 3D models at a lower cost. Specifically speaking, this capability offers the template materials that are created from the experience and material creation specifications of technical artists, to make such valuable assets reusable.
Introduction to Material Generation​
This capability enables your users to turn one or more RGB images into four physically based rendering (PBR) texture maps (the diffuse map, normal map, specular map, and roughness map), with just a tap, to help create true-to-life materials. This capability utilizes AI to create 3D materials for commercial use.
Specifications
Software and hardware requirements: an Android device with a standard RGB camera, instead of an RGB-D or light detection and ranging (LiDAR) sensor
Supported material types: concrete, marble, rock, gravel, brick, gypsum, clay, metal, wood, bark, leather, fabric, paint, plastic, composite material, and ground (including grass and sand)
Supported input images: have a resolution within the range of 1K to 4K, containing no seam, light spot, shade, or reflection.
Output texture maps: have a resolution of 1K (1024 x 1024 px) or 2K (2048 x 2048 px).
SDK size: 88 KB
Accuracy (SSIM): > 0.9
Application scenarios: The powerful material generation capability can be adopted in a wide range of scenarios, for example:
E-commerce: Use this capability to create 3D product models, delivering a more immersive online shopping experience to users.
Exhibition: Display lifelike 3D models of valuable items such as cultural exhibits.
Game: Create realistic wooden floors, tables, and walls for indoor scenes, to better immerse players.
Development Preparations​Integrating the HMS Core SDK​Add the AppGallery Connect configuration file of your app.
Add the agconnect-services.json file to your app after you have enabled 3D Modeling Kit.
Step 1. Sign in to AppGallery Connect and click My projects.
Step 2. Find your project and click the app that needs to integrate the HMS Core SDK.
Step 3. Go to Project settings > General information. In the App information area, click agconnect-services.json to download the configuration file.
Step 4. Copy the file to the app's root directory.
​Configuring the Maven Repository Address for the HMS Core SDK
Step 1. Open the project-level build.gradle file of your Android Studio project.
Step 2. Add the AppGallery Connect plugin and the Maven repository.
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
Go to buildscript > dependencies and add the AppGallery Connect plugin configuration, if the agconnect-services.json file has been added to the app configuration, if the agconnect-services.json file has been added to the app.
Code:
buildscript {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
...
// Add the AppGallery Connect plugin configuration.
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
// Configure the Maven repository address for the HMS Core SDK.
maven {url 'https://developer.huawei.com/repo/'}
}
}
Note that the Maven repository address cannot be accessed from a browser. It can only be configured in the IDE. If there are multiple Maven repositories, add the Maven repository address of Huawei as the last one.
Adding Build Dependencies
Step 1. Open the app-level build.gradle file.
​Step 2. Add build dependencies in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:modeling3d-material-generate:{version}'
}
Note: Replace {version} with the actual SDK version number. For details about the version number, please refer to Version Change History.
For example: implementation 'com.huawei.hms:modeling3d-material-generate:1.0.0.300'.
Step 3. Add the AppGallery Connect plugin configuration in either of the following methods:
Method 1: Add the following information under the declaration in the file header:
Code:
apply plugin: 'com.huawei.agconnect'
Method 2: Add the plugin configuration in the plugins block.
Code:
plugins {
id 'com.android.application'
// Add the following configuration.
id 'com.huawei.agconnect'
}
Defining Multi-language Settings​
If your app supports all the languages supported by the HMS Core SDK, skip the operation procedure in this section.
If your app supports only some of these languages, follow the operation procedure in this section to complete the required configuration.
a. Open the app-level build.gradle file.
b. Go to android > defaultConfig, add resConfigs, and configure the supported languages as follows:
Code:
android {
defaultConfig {
...
resConfigs "en", "zh-rCN", "Other languages supported by your app"
}
}
For details about the languages supported by the HMS Core SDK, please refer to Languages Supported by the HMS Core SDK.
Synchronizing the Project​After completing the preceding configuration, click the synchronization icon on the toolbar to synchronize the Gradle files.
​If an error occurs, check the network connection and the configuration in the build.gradle files.
Configuring Obfuscation Scripts​Before building the APK, configure the obfuscation configuration file to prevent the HMS Core SDK from being obfuscated.
Step 1. Open the app-level obfuscation configuration file proguard-rules.pro of your project and add configurations to exclude the HMS Core SDK from obfuscation.
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.huawei.hianalytics.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
Adding Permissions​To use the material generation capability, declare the following permissions in the AndroidManifest.xml file:
Code:
<!-- Write texture map files to storage and read data to be processed from storage. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Connect to Internet for uploading images or downloading texture maps. -->
<uses-permission android:name="android.permission.INTERNET" />
Development Procedure​Before developing your app, you need to make necessary preparations. Ensure that the Maven repository address for the HMS Core SDK has been configured in your project, and the SDK of this service has been integrated.
1.Set an access token or use the API key in agconnect-services.json during app initialization for your app authentication.
(Recommended) Use the setAccessToken method to set an access token during initialization when the app is started. The access token does not need to be set again.
Code:
MaterialGenApplication.getInstance().setAccessToken("your AccessToken");
For details about how to obtain the access token, please refer to "Client Credentials" in OAuth 2.0-based Authentication.
Use the setApiKey method to set an API key during initialization when the app is started. The API key does not need to be set again.
Code:
MaterialGenApplication.getInstance().setApiKey("your api_key");
When you create an app in AppGallery Connect, an API key will be assigned to your app.
2.Create a material generation engine and configurator, and initialize the engine.
Code:
// Create a material generation engine and pass the current context.
Modeling3dTextureEngine engine = Modeling3dTextureEngine.getInstance(context);
// Create a material generation configurator.
Modeling3dTextureSetting setting = new Modeling3dTextureSetting.Factory()
// Set the working mode to AI.
.setTextureMode(Modeling3dTextureConstants.AlgorithmMode.AI)
.create();
3.Create a listener callback to process the image upload result.
Code:
Modeling3dTextureUploadListener uploadListener = new Modeling3dTextureUploadListener() {
public void onResult(String taskId, Modeling3dTextureUploadResult result, Object ext) {
// Obtain the image upload result.
if (result.isComplete()) {
// Process the upload result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during upload.
}
@Override
public void onUploadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
4.Upload the collected images to the cloud.
Code:
// Obtain the ID of a material generation task and pass it to the configurator.
Modeling3dTextureInitResult modeling3dTextureInitResult = engine.initTask(setting);
String taskId = modeling3dTextureInitResult.getTaskId();
if (taskId == null || taskId.equals("")) {
Log.e("", "get taskId error " + modeling3dTextureInitResult.getRetMsg());
} else {
// Set the upload listener.
engine.setTextureUploadListener(uploadListener);
// Upload the images in asynchronous mode, passing the task ID and directory of the images.
engine.asyncUploadFile(taskId, filePath);
}
5.Query the progress of an on-cloud material generation task.
Code:
// Create a material generation task processing instance and pass the current context.
Modeling3dTextureTaskUtils taskUtils = Modeling3dTextureTaskUtils.getInstance(context);
// Query the material generation progress.
Modeling3dTextureQueryResult queryResult = taskUtils.queryTask(taskId);
6.Create a listener callback to process the download result of generated texture maps.
Code:
Modeling3dTextureDownloadListener downloadListener = new Modeling3dTextureDownloadListener() {
public void onResult(String taskId, Modeling3dTextureDownloadResult result, Object ext) {
// Obtain the download result of generated texture maps.
if (result.isComplete()) {
// Process the download result.
}
}
@Override
public void onError(String taskId, int errorCode, String message) {
// Callback when an error occurs during download.
}
@Override
public void onDownloadProgress(String taskId, double progress, Object ext) {
// Reserved.
}
};
7.Download the generated texture maps.
Code:
// Set the download listener.
engine.setTextureDownloadListener(downloadListener);
// Download the texture maps, passing the task ID and texture map path.
engine.asyncDownloadTexture(taskId, savePath);
8.Call the synchronous API to obtain the generated texture maps in real time.
Code:
// Call the synchronous API, passing the image file path, texture map path, and configurator.
int result = engine.syncGenerateTexture(filePath, downloadPath, setting);
9.Delete the material generation task.
Code:
int ret = taskUtils.deleteTask(taskId);
Amazing capability, right? To learn more about 3D Modeling Kit, check out:
References
Official website of 3D Modeling Kit
Development guide to the kit
HMS Core section on HUAWEI Developer Forum
GitHub and Gitee to obtain the open-source code for the kit
Stack Overflow where you can find solutions to integration-related problems

Related

Search places by keywords with HMS Site Kit

Hello everyone, in this article series, I will tell you about what is HMS Site Kit and how to use it’s features. With HMS Site Kit, you can basically provide users with easy and reliable access to services to related to locations and places.
With the HMS Site Kit, we can provide them make use of this features while helping users to to discover world quickly;
We can take place suggestions according to the keywords that we have determined,
According to the location of the user’s device, we can search for nearby places,
We can get detailed information about a location,
We can learn the human readable address information of a coordinate point,
We can learn the time period where a coordinate point is found.
In the first article of Site Kit series, I will give you an information about how to setup Site Kit to Android project and how to use Keyword Search.
How to integrate HMS Site Kit to project?
First of all, we need to create a signed Bundle/APK of our project. For this, you can follow the steps which have shown in the picture below.
We can start to creating signature by clicking on the Build->Generate Signed Bundle/APK menu on Android Studio. Then, we can start the process of generating a signed APK by selecting the APK option on screen that comes up.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
By pressing the Create New button on the screen that comes up, we can determine the path, password, key alias and key password values of the .jks file to be created for our application. Informations in the Certificate field is not mandatory.
After clicking OK button, we can continue the APK signing process by entering our password informations.
Then, we can complete the signing process by choosing which version of our application we want to sign such as release and debug, together with the signature versions.
After completing this process, we need to make configurations of this signature file in the build.gradle file at the app level of our application.
Code:
signingConfigs {
release {
storeFile file('SiteKitDemo.jks')
keyAlias 'SiteKitDemo'
keyPassword '****'
storePassword '****'
v1SigningEnabled true
v2SigningEnabled true
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.release
debuggable true
}
}
After performing this process, we can perform the operations related to Gradle synchronization by clicking on the sync now button.
After performing this process, we need to add ‘SHA-256 certificate fingerprint’ value of our application to AppGallery Connect.
We can learn value of ‘SHA-256 certificate fingerprint’ via termianl/CMD. For this, we need to go by terminal to the bin folder under the jre(Java Runtime Environment) installed on our system and run the command below.
Code:
C:\Program Files (x86)\Java\jre1.8.0_251\bin>keytool -list -v -keystore <keystore-path>
We will see a screen output as follows. Here, we need to get the value of SHA256.
We need to add this SHA256 value which we have received to the General Information field in the Project Settings menu on AppGalleryConnect. After performing this process, we can download the agconnect-services.json file.
After performing this process, we need to enable Site Kit service in Manage APIs tab on Project Settings tab.
We need to add agconnect-services.json file which we have downloaded, to under app folder on Android Studio of our project as follows.
After performing this process, we need to add Maven libraries and dependency values on build.gradle files.
First of all, we need to open build.gradle file at the project level and add the lines shown below:
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.61'
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' } // HUAWEI Maven repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
def agcpVersion = "1.3.1.300"
classpath "com.huawei.agconnect:agcp:${agcpVersion}" // HUAWEI agcp plugin
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' } // HUAWEI Maven repository
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
After performing this process, we need to add plugin and dependency values in the build.gradle file at the app level as follows.
Code:
apply plugin: 'com.huawei.agconnect'
...
...
dependencies {
...
def siteKitVersion = "4.0.3.300"
implementation "com.huawei.hms:site:${siteKitVersion}"
}
To prevent HMS SDK from hiding, we need to add following lines of code to proguard-rules.pro file which is located under the app folder.
Code:
-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keepattributes SourceFile,LineNumberTable
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
HMS Site Kit — Keyword Search
Thanks to this feature provided by Site Kit, we can search for many places such as tourist attractions, restaurants, schools and hotels by entering information such as keywords, coordinates.
Thanks to the data from this search result, we can easily access many different information about places such as name, address, coordinates, phone numbers, pictures, address details. Within the AddressDetail model, we can easily access information about the address piece by piece through different variables and change the way the address’ notation as we wish.
First of all, after sharing sharing the method what we can search by keyword, we will examine these pieces of code and parameters one by one.
Code:
fun keywordSearch(coordinate: Coordinate, keyword: String, radius: Int,
pageIndex: Int, pageSize: Int, countryCode: String){
val searchService = SearchServiceFactory.create(context,
URLEncoder.encode(
"Your-API-KEY",
"utf-8"))
var request = TextSearchRequest()
request.query = keyword
request.location = coordinate
request.radius = radius
request.pageIndex = pageIndex
request.pageSize = pageSize
request.language = Locale.getDefault().language // Getting system language
request.countryCode = countryCode
searchService.textSearch(request, object: SearchResultListener<TextSearchResponse>{
override fun onSearchError(searchStatus: SearchStatus?) {
Log.e("SITE_KIT","${searchStatus?.errorCode} - ${searchStatus?.errorMessage}")
}
override fun onSearchResult(textSearchResponse: TextSearchResponse?) {
var siteList = textSearchResponse?.sites
siteList?.let {
for(site in siteList){
Log.i("SITE_KIT", "Name => ${site.name}," +
"Format address => ${site.formatAddress}, " +
"Coordinate => ${site.location.lat} - ${site.location.lng}, " +
"Phone => ${site.poi.phone}, " +
"Photo URLS => ${site.poi.photoUrls}, " +
"Rating => ${site.poi.rating}, " +
"Address Detail => ${site.address.thoroughfare}, ${site.address.subLocality}, " +
"${site.address.locality}, ${site.address.adminArea}, ${site.address.country}")
}
} ?: kotlin.run {
Log.e("SITE_KIT","There is not any site")
}
}
})
}
First, we need to create a SearchService object from the SearchServiceFactory class. For this, we can use the create() method of the SearchServiceFactory class. We need to declare two parameters in create() method.
The first of these parameters is context value. It is recommended that Context value should be in Activity type. Otherwise, when HMS Core(APK) needs to be updated, we can not receive any notification about it.
The second parameter is API Key value that we can access via AppGallery Connect. This value is generated automatically by AppGallery Connect when a new app is created. We need to encode API parameter as encodeURI.
We need to create a TextSearchRequest object to perform searching by keyword. We will perform the related search criteria on this TextSearchRequest object.
While performing the searching operation, we can set many different criteria as we see in the code snippet. Let us examine the duties of these criteria one by one if you want to:
Query: Used to specify the keyword that we will use during the search process.
Location: It is used to specify latitude and longitude values with a Coordinate object to ensure that search results are searched as closely to the location that we want.
Radius: It is used to make the search results within in a radius determined in meters. It can take values between 1 and 50000, and its default value is 50000.
CountryCode: It is using to limit search results according to certain country borders.
Language: It is used to specify the language that search results have to be returned. If this parameter is not specified, the language of the query field we have specified in the query field is accepted by default. In example code snippet in above, the language of device has been added automatically in order to get a healthy result.
PageSize: Results return with the Pagination structure. This parameter is used to determine the number of Sites to be found in each page.
PageIndex: It is used to specify the number of the page to be returned with the Pagination structure.
Once we have determined our criteria, we can start the search using textSearch() method of SearchService object. textSearch() method takes two parameters.
First parameter is TextSearchRequest object which we have defined above. Here, our search criterias are defined.
For the second parameter, we need to implement SearchResultListener interface. Since the SearchResultListener interface is generic, we need the data type that results will return here. Here we can specify TextSearchResponse class that is model provided by Huawei Site Kit. This interface contains two methods, onSearchError() and onSearchResult() methods. We can configure these methods according to logic of our program and take necessary actions.

Integrate Huawei Ads Kit into Ionic Project in 10 Mins

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Ads can provide to developers an extensive data capabilities to deliver high quality ad content to their users. By integrating HMS ads kit we can start earning right away. It is very useful particularly when we are publishing a free app and want to earn some money from it.
Integrating HMS ads kit does not take more than 10 mins. HMS ads kit currently offers five types of ad format:
1) Banner Ad
2) Native Ad
3) Reward Ad
4) Interstitial Ad
5) Splash Ad
In this article we are going to learn how to integrate HMS Ads Kit in Ionic application.
Demo
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Prerequisite
1) Must have a Huawei Developer Account.
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 installed.
4) Must install node in the system
5) Must install Ionic in the system using below command:
Code:
npm install -g [user=1329689]@iONiC[/user]/cli
Things need to be done
1) Generating a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
2) Create an app in the Huawei AppGallery connect.
3) Provide the SHA Key in App Information Section.
4) Provide storage location.
5) Download the agconnect-services.json and store it somewhere on our computer.
6) Create a blank Ionic Project using below command:
Code:
ionic start Your_Application_Name blank --type=angular
7) Run the following command in the root directory of your Ionic project to install it through npm.
Code:
npm install @hmscore/cordova-plugin-hms-ads
8) If you want full Ionic support with code completion etc., install @iONiC-native/core in your project.
Code:
npm install [user=1329689]@iONiC[/user]-native/core --save-dev
9) Run the following command to copy the ionic/dist/hms-ads folder from library to node_modules @iONiC-native folder under your Ionic project.
Code:
cp node_modules/@hmscore/cordova-plugin-hms-ads/ionic/dist/hms-ads node_modules [user=1329689]@iONiC[/user]-native/ -r
10) Run the following command to compile the project:
Code:
ionic build
npx cap init [appName] [appId]
Where appName is the name of your app, and appId is package_name in your agconnect-services.json file (ex: com.example.app).
11) Run the following command to add android platform to your project:
Code:
ionic capacitor add android
12) Make sure your project has a build.gradle file with a maven repository address and agconnect service dependencies as shown below:
13) Add the Signing certificate configuration to the build.gradle file in the app directory as show below:
14) Add plugin to the build.gradle file in the app directory as show below:
15) Add ads service implementation into to dependencies section of build.gradle file in the app directory as show below:
16) Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below:
17) To update dependencies, and copy any web assets to your project, run the following code:
Code:
npx capacitor sync
Let’s Code
Import
Import the following code in your application page:
Code:
import {
HmsAds, InterstitialAdEvents,
BannerAdOptions, BannerAdEvents, SplashAdEvents,
RewardAdEvents, NativeAdEvents, BannerAdSize, Color, Gender,
NonPersonalizedAd} from [user=1329689]@iONiC[/user]-native/hms-ads/ngx';
Initialization
We need to initialize HMS ads kit as show below:
Code:
async ionViewDidEnter(){
const isInit = await this.hmsads.isInit();
if(!isInit){
await this.hmsads.init({ bannerFloat: false });
}
}
Banner Ads
Banner ads are rectangular images that occupy a spot at the top, middle, or bottom within an app's layout. Banner ads refresh automatically at regular intervals. When a user taps a banner ad, the user is redirected to the advertiser's page in most cases.
Code:
async showBannerAd() {
const options: BannerAdOptions = {
adId: 'testw6vs28auh3',
bannerAdSize: BannerAdSize['BANNER_SIZE_SMART'],
bgColor: Color['TRANSPARENT'],
anchor: 'bottom',
bannerRefresh: 50
}
this.banner = new this.hmsads.Banner;
await this.banner.create(options);
this.banner.on(BannerAdEvents.LOADED, () => {
console.log("bannerAdsInstance :: loaded");
});
this.banner.on(BannerAdEvents.FAILED, () => {
console.log("bannerAdInstance :: failed");
});
await this.banner.loadAd({});
}
Below are the size we can choose to create banner ads:
Native Ad
Native ads fit seamlessly into the surrounding content to match our app design. Such ads can be customized as needed.
Code:
async showNativeAd() {
if (this.nativeAdInstance != null)
await this.nativeAdInstance.destroy();
const template = this.nativeAdSize as "video" ;
const nativeElem = document.getElementById("native-ad-element");
let adId = 'testy63txaom86';
nativeElem.style.height = '300px';
// Create a new native ad with selected template
this.nativeAdInstance = new this.hmsads.Native();
await this.nativeAdInstance.create({
div: 'native-ad-element',
template,
bg: Color.WHITE
});
this.nativeAdInstance.on(NativeAdEvents.NATIVE_AD_LOADED, async () => {
console.log("nativeAdInstance :: loaded");
await this.nativeAdInstance.show();
});
// Load the ad.
this.nativeAdInstance.loadAd({
adId
});
}
We can change the template here to banner, video, small or full.
Reward Ad
Rewarded ads are full-screen video ads that reward users for watching.
Code:
async showRewardAd(){
const reward = new this.hmsads.Reward();
await reward.create({
adId: 'testx9dtjwj8hp',
});
reward.on(RewardAdEvents.LOADED, async () => {
await reward.show();
});
reward.loadAd({});
}
Interstitial Ad
Interstitial ads are full-screen ads that cover the interface of an app. Such ads are displayed when a user starts, pauses, or exits an app, without disrupting the user's experience.
Code:
async showInterstitialAd(){
const interstitial = new this.hmsads.Interstitial()
await interstitial.create({ adId: 'testb4znbuh3n2' })
interstitial.on(InterstitialAdEvents.LOADED, async () => {
await interstitial.show()
})
await interstitial.loadAd({})
console.log("finished.")
}
Splash Ad
Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed.
Code:
async showSplashAd() {
const splash = new this.hmsads.Splash();
await splash.create({
logo: {
copyright: 'Copyright Huawei 2020',
owner: 'Huawei',
anchor: 'bottom',
bg: Color['TRANSPARENT']
}
});
splash.on(SplashAdEvents.LOADED, async () => {
await splash.show();
});
splash.on(SplashAdEvents.DISMISSED, async () => {
console.log("SplashAd dismissed");
await splash.cancel();
await splash.destroy();
})
await splash.load({
adId: 'testq6zq98hecj',
orientation: this.hmsads.Orientation.SCREEN_ORIENTATION_PORTRAIT
});
}
Install Referrer Information
For better support app promotion targeted at Huawei devices, we need install referrer capability for advertisers to track promotion channels and attribute conversions.
Code:
showReferrerDetails(){
this.hmsads.getReferrerDetails(true).then(result => alert(JSON.stringify(result)));
}
Obtaining OAID Information
The OAID information can be used to recommend personalized ads to users and attribute ad conversions.
Code:
showOAIDDetails(){
this.hmsads.getOaidResult().then(result => alert(JSON.stringify(result)));
}
Conclusion
We learn how to integrate HMS Ads Kit in Ionic Project. Feel free to comment, share and like the article. Also you can follow me to get awesome article like this every week.
For more reference
https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/introduction-0000001050437673

Integrate AppGallery Connect's Cloud DB Service in Three Easy Steps

Cloud DB is a device-cloud synergy database product that provides data synergy management capabilities between the device and cloud, unified data models, and various data management APIs. In addition to ensuring data availability, reliability, consistency, and security, Cloud DB enables seamless data synchronization between the device and cloud, and supports offline app operations, helping you quickly develop device-cloud and multi-device synergy apps. For more information about Cloud DB, please click here.
Cloud DB can be easily integrated into apps through its SDK and APIs, ensuring security and reliability. During integration, the SDK and APIs ease your workload by performing server setup, deployment, and O&M for you.
Now, let’s first take a look at how to quickly integrate Cloud DB in Android apps. You only need to perform the following three steps:
1. Create an object type and a Cloud DB zone.
2. Export the object type and perform account authentication.
3. Integrate the Cloud DB SDK into your Android project and call APIs to add, delete, modify, or query data.
1. Creating an Object Type and a Cloud DB Zone​Cloud DB is still in beta, so you’ll need to send an email to apply for the service. For more details on how to do so, please read the following documentation.
1.1. What Is an Object Type?​Simply put, each object type corresponds to a table used to store data in your database. Think of it as creating an Excel file to store data, whereby each sheet in the Excel file is equivalent to an object type in Cloud DB.
1.2. What Is a Cloud DB Zone?​A Cloud DB zone is an independent data storage zone. Multiple Cloud DB zones are independent of each other. Going back to the Excel file analogy, imagine that you’re a teacher responsible for multiple classes, and you record the scores of students in each class in an Excel file. Each Excel file contains a student information sheet and a score sheet that are independent of each other. A Cloud DB zone is akin to an Excel file in this analogy.
1.3. Creating an Object Type​Before you start, apply for and enable Cloud DB by performing the following:
1. Sign in to AppGallery Connect and click My projects. Select your project and app. Go to Build > Cloud DB, click the ObjectTypes tab, and create an object type.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
2. Create an object type named StudentInfo. Please remember to set the primary key and select the upsert and delete permissions for the Authenticated user.
1.4. Creating a Cloud DB Zone​On the Cloud DB Zones tab page, click Add, enter the name of the Cloud DB zone, and click OK.
Before You Start​When using Cloud DB, you need to export the object type first.
You need to export the object type created in the previous step to your local Android project. This synchronizes data between your Android project and Cloud DB.
Remember to place the exported object type in your Android project. In the example below, I placed the object type in the model directory.
Integrating Cloud DB in Your Android Project​1. Integrating the Cloud DB SDK​1. In AppGallery Connect, click My projects, and click a project card. Go to Project settings > General information, and download the agconnect-services.json file in the App information area. Then, place the JSON file under the app directory in your Android project.
2.Configure the project-level build.gradle file.
XML:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.4.2.301'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3. Configure the app-level build.gradle file.
XML:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
...
android {
......
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
...
implementation 'com.huawei.agconnect:agconnect-auth:1.4.2.300' // Auth Service of AppGallery Connect, for account authentication.
implementation 'com.huawei.agconnect:agconnect-database:1.2.3.301' // Cloud DB SDK.
}
1.1 Preparations
Cloud DB places operation restrictions on users. Only authenticated users can add, delete, and modify data. Therefore, you’ll need to integrate Auth Service first.
Enable Auth Service in AppGallery Connect. Using anonymous account authentication as an example, click My projects, click a project card, and go to Build > Auth Service to enable it.
Sample code for enabling anonymous account authentication:
Java:
AGConnectAuth.getInstance().signInAnonymously().addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
}
});
2. Completing Initialization​The initialization consists of three parts: initializing Cloud DB, creating an object type, and creating and opening a Cloud DB zone.
1. Define required parameters in onCreate:
Java:
private AGConnectCloudDB mCloudDB;
private CloudDBZoneConfig mConfig;
private CloudDBZone mCloudDBZone;
2.Initialize AGConnectCloudDB.
Java:
AGConnectCloudDB.initialize(this);
3.Obtain an AGConnectCloudDB instance and create an object type.
Java:
mCloudDB = AGConnectCloudDB.getInstance();
try {
mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "createObjectType Failed " + e.getMessage());
}
4. Create and open a Cloud DB zone.
Java:
Config = new CloudDBZoneConfig("classs1",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
mConfig.setPersistenceEnabled(true);
try {
CloudDBZone = mCloudDB.openCloudDBZone(mConfig, true);
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "openCloudDBZone failed: " + e.getMessage());
}
Note that you can also use the asynchronous openCloudDBZone2 method. The detailed operations are not described here. For details, please refer to:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-clouddb-get-started#h1-1594008398022
3. Using Cloud DB Functions​Once you have completed authentication, you can perform related operations on Cloud DB. The following uses the query operation as an example:
1. In AppGallery Connect, insert two records — test1 and test2 — for testing.
2. Go back to your Android project and call executeQuery to query all data.
Java:
Task<CloudDBZoneSnapshot<StudentInfo>> queryTask = mCloudDBZone.executeQuery(
CloudDBZoneQuery.where(StudentInfo.class),
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<StudentInfo>>() {
@Override
public void onSuccess(CloudDBZoneSnapshot<StudentInfo> snapshot) {
//
CloudDBZoneObjectList<StudentInfo> InfoCursor = snapshot.getSnapshotObjects();
ArrayList<StudentInfo> infoList = new ArrayList<>();
StudentInfo studentInfo = new StudentInfo();
try {
while (InfoCursor.hasNext()) {
studentInfo = InfoCursor.next();
infoList.add(studentInfo);
}
Log.i("CloudDB", "query success: " + JSONArray.toJSONString(studentInfo));
} catch (AGConnectCloudDBException e) {
Log.e("CloudDB", "query failed: " + e.getMessage());
}
snapshot.release();
}
});
3. Then, you can view the corresponding query data in Logcat.
4. You can refer to the configuration guide and API reference to learn more about the add, delete, and modify operations:
Configuration guide:
https://developer.huawei.com/consum...allery-connect-Guides/agc-clouddb-insert-data
API reference:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb
Summary​You can use Cloud DB after performing just three easy steps:
1. Create an object type and a Cloud DB zone.
2. Export the object type to an Android project.
3. Integrate the SDK into the Android project and call related APIs.
Once you have completed these steps, you will have integrated a database system into your app, without having to perform any setup or deployment operations. Currently, Cloud DB is still free to use.
Cloud DB links:
Development guide:
https://developer.huawei.com/consum...llery-connect-Guides/agc-clouddb-introduction
API reference:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-References/clouddb
Demo:
https://github.com/AppGalleryConnect/agc-demos/tree/main/Android/clouddb-java

Beginner: Ads Alert! Integration of Huawei Ads Kit in Application using React Native

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, I will explain how to integrate Huawei Ads Kit in an Application using React Native. I will be using 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.
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 Interstitial 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
React Native CLI : 2.0.1
React Native Ads Kit SDK : 4.0.4
React-native-hms-ads gradle dependency.
Preparation
In order to develop the HMS react native apps, following steps are mandatory:
1. Create an app or project in the Huawei AppGallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project. Use the following command
Code:
react-native init project name
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
5. 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
Code:
maven {url 'http://developer.huawei.com/repo/'}
Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“: react-native-hms-ads”)
Linking the HMS Ads Kit Sdk
Run below command in the project directory
Code:
react-native link react-native-hms-ads
Adding permissions
Add below permissions to Android.manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Sync Gradle.
Development
To successfully run interstitial ads in application, we would need to:
Creating an Interstitial Ad.
Setting Ad Slot ID.
Loading the Ad.
Displaying the Ad.
Listening for Ad Events
Creating an Interstitial Ad
JavaScript:
HMSInterstitial module is used to create the interstitial Ad
import HMSAds, {
HMSInterstitial,
InterstitialMediaTypes,
} from 'react-native-hms-ads';
Setting Ad Slot ID
JavaScript:
setAdId() method is responsible for setting the Ad Slot. Below is the code for same. Refer this article to know the process for creating the slot Id’s.
// creating object for the Ad Slot ID
const Interstitial = () => {
let interstitialAdIds = {};
interstitialAdIds[InterstitialMediaTypes.IMAGE] = 'teste9ih9j0rc3';
interstitialAdIds[InterstitialMediaTypes.VIDEO] = 'testb4znbuh3n2';
}
// creating object for setting up the media type for the ad
const [displayForm, setDisplayForm] = useState({
mediaType: InterstitialMediaTypes.VIDEO,
adId: interstitialAdIds.video,
})
// setting up the ID
HMSInterstitial.setAdId(displayForm.adId);
Setting Ad Request Parameters
JavaScript:
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';
HMSInterstitial.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: '',
});
Loading the Ad
Calling the loadAd() method to load the ad on button click.
JavaScript:
HMSInterstitial.loadAd()
Displaying the Ad
isLoaded() method is called to confirm if the ad has finished loading. Once ad loading is completed, show() method is called to display the ad on a button click.
JavaScript:
setLoaded(false);
HMSInterstitial.show();
Listening for Ad Events
As we handle multiple Ad events for different actions, Listener can be added for listening to these events as below.
JavaScript:
useEffect(() => {
HMSInterstitial.setAdId(displayForm.adId);
HMSInterstitial.adClosedListenerAdd(() => {
toast('HMSInterstitial adClosed');
});
// HMSInterstitial.adClosedListenerRemove();
HMSInterstitial.adFailedListenerAdd((error) => {
toast('HMSInterstitial adFailed');
console.warn('HMSInterstitial adFailed, error: ', error);
});
// HMSInterstitial.adFailedListenerRemove();
HMSInterstitial.adLeaveListenerAdd(() => {
toast('HMSInterstitial adLeave');
});
// HMSInterstitial.adLeaveListenerRemove();
HMSInterstitial.adOpenedListenerAdd(() => {
toast('HMSInterstitial adOpened');
});
// HMSInterstitial.adOpenedListenerRemove();
HMSInterstitial.adLoadedListenerAdd((result) => {
toast('HMSInterstitial adLoaded');
console.log('HMSInterstitial adLoaded, result: ', result);
});
// HMSInterstitial.adLoadedListenerRemove();
HMSInterstitial.adClickedListenerAdd(() => {
toast('HMSInterstitial adClicked');
});
// HMSInterstitial.adClickedListenerRemove();
HMSInterstitial.adImpressionListenerAdd(() => {
toast('HMSInterstitial adImpression');
});
// HMSInterstitial.adImpressionListenerRemove();
return HMSInterstitial.allListenersRemove;
})
Add all these functionalities to a button according to your UI.
For example, in a News Application if there is a button names “Sports” then:
JavaScript:
<Button
title="Sports"
onPress={() => {
HMSInterstitial.setAdParam({ …})
HMSInterstitial.loadAd();
setLoaded(false);
HMSInterstitial.show();
}}
/>
Testing
Run the below command to build the project
Code:
React-native run-android
Run the application (Generating the Signed Apk):
Open project directory path in command prompt. Navigate to android directory and run the below command for signing the apk.
Code:
gradlew assembleRelease
Result
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.
Code:
gradlew clean
Conclusion
In this article, we can learn about how to integrate Ads Kit and how to add Interstitial 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

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

{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
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
React Native CLI : 2.0.1
React Native Ads Kit SDK : 4.0.4
React-native-hms-ads gradle dependency.
Preparation
In order to develop the HMS react native apps, following steps are mandatory:
1. Create an app or project in the Huawei AppGallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
3. Create a react native project. Use the following command
Code:
react-native init project name
4. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
5. Run below command under project directory using CLI if you cannot find node modules.
Code:
npm install & npm link
Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Ads Kit Sdk
Run below command in the project directory
Code:
react-native link react-native-hms-ads
5. Adding permissions
Add below permissions to Android.manifest file.
Code:
<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:
Creating an Splash Ad.
Setting Ad Slot ID.
Customizing Screen
Loading the Ad.
Displaying the Ad.
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:
Code:
import {HMSSplash} from '@hmscore/react-native-hms-ads';
Setting Ad Slot ID
Code:
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);
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.
Code:
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.
Code:
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: '',
});
Displaying the Ad
Call the show() method to display the ad. The sample code is as follows:
Code:
HMSSplash.show()
.then(res=>console.log(res));
Listen to Ad Events
Listener functions can be triggered with the different ad actions and associated events.
Code:
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>
);
}
Testing
Run the below command to build the project
Code:
React-native run-android
Result
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.
Code:
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

Categories

Resources