Beginner: Huawei App Messaging Unity Game Development - Huawei Developers

Introduction
You can use App Messaging of AppGallery Connect to subscribe and send relevant messages to target active users of your app to encourage them to use key app functions. For example, you can send in-app messages to encourage users to subscribe certain products, provide tips on passing a game level or recommend activities of a restaurant.
App Messaging allows you to customize our messages look and the way they will be sent, and define events for triggering message sending to your users at the right moment.
AG Connect supports three types of messages as follows:
1. Pop-up message
2. Image message
3. Banner message
Development Overview
You need to install Unity software and I assume that you have prior knowledge about the unity and C#.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK installation package.
Unity software installed.
Visual Studio/Code installed.
HMS Core (APK) 4.X or later.
Follows the steps.
1. Create Unity Project.
Open unity Hub.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows:
{
"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. Click Asset Store, search Huawei HMS Core App Services and click Import, as follows.
3. Once import is successful, verify directory in Assets> Huawei HMS Core App Services path, as follows.
4. Choose Edit > Project Settings > Player and edit the required options in Publishing Settings, as follows.
5. Generate a SHA-256 certificate fingerprint.
To generating SHA-256 certificate fingerprint use below command.
Code:
keytool -list -v -keystore D:\Unity\projects_unity\file_name.keystore -alias alias_name
6. Download agconnect-services.json and copy and paste to Assets > Plugins > Android, as follows.
7. Choose Project Settings > Player and update package name.
8. Open LauncherTemplate.gradle and add below line.
Code:
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.hms:hianalytics:5.1.0.301'
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.301'
9. Open AndroidManifest file and add below permissions.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
10. Open "baseProjectTemplate.gradle" and add lines, as follows.
Code:
classpath'com.huawei.agconnect:agcp:1.4.1.300'
maven {url 'https://developer.huawei.com/repo/'}
11. Open "mainTemplate.gradle" and add lines, as follows.
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.301'
implementation 'com.huawei.hms:hianalytics:5.1.0.301'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.1.300'
12. Enable debug mode use in cmd prompt [optional].
Code:
adb shell setprop debug.huawei.hms.analytics.app package_name
13. Configuring project in AGC
14. Create Scripts folder and create a class.
APPMessaging.cs
C#:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HuaweiService;
using HuaweiService.appmessage;
using HuaweiService.analytic;
using HuaweiService.push;
using Exception = HuaweiService.Exception;
public class APPMessaging : MonoBehaviour
{
private HiAnalyticsInstance instance;
private AGConnectAppMessaging appMessaging;
private void Start()
{
instance = HiAnalytics.getInstance(new Context());
appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
instance.setAnalyticsEnabled(true);
getAAID();
}
private void getAAID(){
// Task result = instance.getAAID();
Task id = HmsInstanceId.getInstance(new Context()).getAAID();
id.addOnSuccessListener(new HmsSuccessListener<AAIDResult>((aaidResult) =>
{
string aaId = aaidResult.getId();
Debug.Log("AAID==>> "+aaId);
})).addOnFailureListener(new HmsFailureListener((e) =>
{
Debug.Log("AAID==>> Failed");
}));
}
public delegate void SuccessCallBack<T>(T o);
public class HmsSuccessListener<T>:OnSuccessListener{
public SuccessCallBack<T> CallBack;
public HmsSuccessListener(SuccessCallBack<T> c){
CallBack = c;
}
public void onSuccess(T arg0)
{
if(CallBack != null)
{
CallBack.Invoke(arg0);
}
}
public override void onSuccess(AndroidJavaObject arg0){
if(CallBack !=null)
{
Type type = typeof(T);
IHmsBase ret = (IHmsBase)Activator.CreateInstance(type);
ret.obj = arg0;
CallBack.Invoke((T)ret);
}
}
}
public delegate void SuccessCallBack(AndroidJavaObject object);
public delegate void FailureCallBack(Exception e);
public class HmsFailureListener:OnFailureListener{
public FailureCallBack CallBack;
public HmsFailureListener(FailureCallBack c){
CallBack = c;
}
public override void onFailure(Exception arg0){
if(CallBack !=null){
CallBack.Invoke(arg0);
}
}
}
}
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<!-- GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application>
<activity android:name="com.unity3d.player.UnityPlayerActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application>
</manifest>
15. Follow the steps, as shown in image:
a. Create empty GameObject.
b. Assign script APPMessaging(as per you script name) to empty GameObject.
16. To build apk and run in device, choose File > Build Settings > Build for apk or Build and Run for run on connected device.
Result
Sign in to AppGallery Connect and click My projects.
Find and click your project.
Navigate to Grow > App Messaging and click New.
Select Name and Description.
Click Test in Operation drop-down.
Enter text in Test user AAID and click Save.
Tips and Tricks
Always use the latest version of the library.
Add agconnect-services.json file without fail.
Add SHA-256 fingerprint without fail.
Make sure dependencies added in build files.
Make sure you have enable debug mode.
Make sure the image url is correct and aspect ratio for Portrait is 3:2 (300x200) and Landscape aspect ratio is 1:1 or 3:2 (100 x100 or 300x200).
Conclusion
In this article, we have learnt to integrate Huawei AppMessaging service into unity game development. AppMessaging provides services sending promotional messages and new updates and also we can target users to promote some products.
Thanks for reading the article, please do likes, comments and your queries or suggestions.
References
App Messaging - click here
Unity App Messaging Integration Manual - click here
Original source

Related

How Can I Quickly Integrate App Linking of AppGallery Connect into My Android App?

Recently, my app needs to use cross-platform sharing links. App Linking of AppGallery Connect just meets my requirements.
Perform the following steps for service integration:
i. Step 1: Create an app and enable App Linking for the app.
ii. Step 2: Create a URL prefix.
iii. Step 3: Integrate the App Linking SDK into the Android project.
iv. Step 4: Create a link of App Linking.
v. Step 5: Receive and test the link.
1. Creating an App and Enabling App Linking for the App
Create an app or use an existing app in AppGallery Connect. Click My projects and go to Grow > App Linking, and click Enable now in the displayed page.
{
"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"
}
Go to My projects > Project settings > General information, download the agconnect-services.json file, and save the file to the app directory of your Android project.
2. Creating a URL Prefix
On the displayed App Linking service page, click the URL prefix tab and then click Add URL prefix to create a unique URL prefix.
The system will automatically check your domain name to ensure its uniqueness.
3. Integrating the App Linking SDK into Your Android Project
To configure the SDK address, open your Android project, and configure the following content in red in the project-level build.gradle file.
XML:
buildscript {
repositories {
// ...
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
// ...
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
}
}
allprojects {
repositories {
// ...
maven {url 'https://developer.huawei.com/repo/'}
}
}
Open the app-level build.gradle file and configure the App Linking SDK and Analytics SDK by adding the following information in red:
XML:
...
apply plugin: 'com.huawei.agconnect'
...
dependencies {
...
implementation "com.huawei.agconnect:agconnect-applinking:1.4
implementation 'com.huawei.hms:hianalytics:5.0.4.301'.1.300"
}
4. Creating a Link of App Linking
You can create a link of App Linking in AppGallery Connect or call an API in your Android project.
4.1 Creating a Link in AppGallery Connect
1. On the displayed App Linking service page, click the App Linking tab and create a link as prompted.
2. Configure the deep link of Android.
3. Set Link behavior for Android to Open in app.
After the link is successfully created, copy and use it.
4.2 Creating a Link Through Coding
1. In the activity_main.xml file, configure two buttons, one for link creation and the other for sharing. Create a TextView to display the link.
HTML:
<Button
android:id="@+id/create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create App Linking"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4" />
<TextView
android:id="@+id/showLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="your App Linking"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5" />
<Button
android:id="@+id/shareLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Share App Linking"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.8" />
Refer to the figure as follows.
2. Copy and add the URL prefix, and set the deep link to be opened.
Java:
private static final String DOMAIN_URI_PREFIX = "https://testapplinking1016.drcn.agconnect.link";
private static final String DEEP_LINK = " https://consumer.huawei.com/cn/";
private static final String Android_DEEP_LINK = "myapp://testapplinking/?data=1016";
private String shortLink;
3. In onCreate of MainActivity, you can add a CREATE APP LINKING button to create a link.
Java:
findViewById(R.id.create).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppLinking.Builder builder = new AppLinking.Builder()
.setUriPrefix(DOMAIN_URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK))
.setAndroidLinkInfo(new AppLinking.AndroidLinkInfo.Builder()
.setAndroidDeepLink(Android_DEEP_LINK).build());.build());
builder.buildShortAppLinking().addOnSuccessListener(shortAppLinking -> {
shortLink = shortAppLinking.getShortUrl().toString();
TextView showAppLinking = findViewById(R.id.showLink);
showAppLinking.setText(shortLink);
}).addOnFailureListener(e -> {
Log.e("AppLinking", "Failure + "+ e.getMessage());
});
}
});
4. Then, you can tap SHARE APP LINKING in your app to share the created link.
Java:
findViewById(R.id.shareLink).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, shortLink);
startActivity(intent);
}
});
5. Receiving a Link
To receive a link, you need to configure the manifest file and set the getAppLinking method to the link entry.
1. Configure the manifest file. Here, the scheme of the deep link domain name is set in the file.
Example: DEEP_LINK = “myapp://testapplinking/?data=1016”;
private static final String DEEP_LINK = "myapp://testapplinking/?data=1016";
Sample code:
XML:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="testapplinking" android:scheme="myapp" />
</intent-filter>
2. In the main entry of onCreate, set getAppLinking to obtain and display the link.
Java:
AGConnectAppLinking.getInstance().getAppLinking(this).addOnSuccessListener(resolvedLinkData -> {
if (resolvedLinkData != null) {
String Result = resolvedLinkData.getDeepLink().toString();
TextView showAppLinking = findViewById(R.id.showLink);
showAppLinking.setText(Result);
}
});
6. Packaging Your App and Testing App Linking
1. After your app runs properly, tap CREATE APP LINKING to create a link. The link is displayed on the app screen.
2. Tap SHARE APP LINKING to share the link to the note. Then tap the link in the note and open the link in a browser. If the browser can directly open your app, the test is successful.
(The test process is the same for the link created in AppGallery Connect.)
For more details, please check:
https://developer.huawei.com/consum...ry-connect-Guides/agc-applinking-introduction
7. Summary
The integration is simple. The SDK is small, and links can be shared across Android and iOS. No adaptation is required on different platforms, reducing the workload.
Operations personnel can create links in AppGallery Connect for app promotion, and developers can write code in apps to create links, which is very convenient.
Reference:
HUAWEI AppGallery Connect App Linking documentation: https://developer.huawei.com/consum...ry-connect-Guides/agc-applinking-introduction

Intermediate: Integration of landmark recognition feature in tourism apps (ML Kit-React Native)

Overview
Did you ever gone through your vacation photos and asked yourself: What is the name of this place I visited in India? Who created this monument I saw in France? Landmark recognition can help! This technology can predict landmark labels directly from image pixels, to help people better understand and organize their photo collections.
Landmark recognition can be used in tourism scenarios. The landmark recognition service enables you to obtain the landmark name, landmark longitude and latitude, and confidence of the input image. A higher confidence indicates that the landmark in the input image is more likely to be recognized. Based on the recognized information, you can create more personalized app experience for users.
{
"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"
}
In this article, I will show how user can get the landmark information using ML Kit Plugin.
Integrate this service into a travel app so that images taken by users are detected by ML Plugin to return the landmark name and address, and the app can provide the brief introduction and tour suggestions based on the returned information.
Create Project in Huawei Developer Console
Before you start developing an app, configure app information in App Gallery Connect.
Register as a Developer
Before you get started, you must register as a Huawei developer and complete identity verification on HUAWEI Developers. For details, refer to Registration and Verification.
Create an App
Follow the instructions to create an app Creating an App Gallery Connect Project and Adding an App to the Project. Set the data storage location to Germany
Adding an App to the Project. Set the data storage location to Germany
React Native setup
Requirements
Huawei phone with HMS 4.0.0.300 or later.
React Native environment with Android Studio, NodeJs and Visual Studio code.
Dependencies
Gradle Version: 6.3
Gradle Plugin Version: 3.5.2
React-native-hms-ml gradle dependency
React Native CLI: 2.0.1
1. Environment setup, refer below link.
Setting up the development environment · React Native
This page will help you install and build your first React Native app.
reactnative.dev
2. Create project by using this command.
Code:
react-native init project name
3. You can install react native command line interface on npm, using the install -g react-native-cli command as shown below.
Code:
npm install –g react-native-cli
Generating a Signing Certificate Fingerprint
Signing certificate fingerprint is required to authenticate your app to Huawei Mobile Services. Make sure JDK is installed. To create one, navigate to JDK directory’s bin folder and open a terminal in this directory. Execute the following command:
Code:
keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks -storepass <store_password> -alias <alias> -keypass <key_password> -keysize 2048 -keyalg RSA -validity 36500
This command creates the keystore file in application_project_dir/android/app
The next step is obtain the SHA256 key which is needed for authenticating your app to Huawei services, for the key store file. To obtain it, enter following command in terminal:
Code:
keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
After an authentication, the SHA256 key will be revealed as shown below.
Adding SHA256 Key to the Huawei project in App Gallery
Copy the SHA256 key and visit AppGalleryConnect/ <your_ML_project>/General Information. Paste it to the field SHA-256 certificate fingerprint.
Enable the ML kit from ManageAPIs.
Download the agconnect-services.jsonfrom App Gallery and place the file in android/app directory from your React Native Project.
Follow the steps to integrate the ML plugin to your React Native Application.
Integrate the HMS-ML plugin
Code:
npm i @hmscore/react-native-hms-ml
Download the Plugin from the Download Link
Download ReactNative ML Plugin under node_modules/@hmscore of your React Native project, as shown in the directory tree below:
Code:
project-dir
|_ node_modules
|_ ...
|_ @hmscore
|_ ...
|_ react-native-hms-ml
|_ ...
|_ ...
Navigate to android/app/build.gradle directory in your React Native project. Follow the steps:
Add the AGC Plugin dependency.
Code:
apply plugin: 'com.huawei.agconnect'
Add to dependencies in android/app/build.gradle:
Code:
implementation project(':react-native-hms-ml')
Navigate to App level android/build.gradle directory in your React Native project. Follow the steps:
Add to buildscript/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
Add to buildscript/dependencies
Code:
classpath 'com.huawei.agconnect:agcp:1.3.1.300’'3)
Navigate to android/settings.gradle and add the following:
Code:
include ':react-native-hms-ml'
project(':react-native-hms-ml').projectDir = new File(rootProject.projectDir, '../node_modules/@hmscore/react-native-hms-ml/android')
Use case
Huawei ML kit’s HMSLandmarkRecognition API can be integrate for different applications and to return the landmark name and address, and the app can provide the brief introduction and tour suggestions based on the returned information.
Add below under AndroidManifest.xml file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value="dsc"/>
</ application>
Set API Key:
Before using HUAWEI ML in your app, set Api key first.
Copy the api_key value in your agconnect-services.json file.
Call setApiKey with the copied value.
JavaScript:
HMSApplication.setApiKey("api_key").then((res) => {console.log(res);})
catch((err) => {console.log(err);})
Analyze Frame
Using HMSLandmarkRecognition.asyncAnalyzeFrame() recognizes landmarks in images asynchronously.
JavaScript:
async asyncAnalyzeFrame() {
try {
var result = await HMSLandmarkRecognition.asyncAnalyzeFrame(true, this.getFrameConfiguration(), this.getLandmarkAnalyzerSetting());
console.log(result);
if (result.status == HMSApplication.SUCCESS) {
result.result.forEach(element => {
this.state.landmark.push(element.landMark);
this.state.possibility.push(element.possibility);
this.state.url.push('https://en.wikipedia.org/wiki/'+element.landMark)
long = [];
lat = [];
element.coordinates.forEach(ll => {
long.push(ll.longitude);
lat.push(ll.latitude);
})
this.state.coordinates.push(lat, long);
});
this.setState({
landMark: this.state.landmark,
possibility: this.state.possibility,
coordinates: this.state.coordinates,
url:this.state.url,
});
}
else {
ToastAndroid.showWithGravity(result.message, ToastAndroid.SHORT, ToastAndroid.CENTER);
}
} catch (e) {
console.error(e);
}
}
Final Code:
JavaScript:
import React from 'react';
import {
Text,
View,
TextInput,
ScrollView,
TouchableOpacity,
Image,
ToastAndroid,
SafeAreaView
} from 'react-native';
import { styles } from '@hmscore/react-native-hms-ml/example/src/Styles';
import { HMSLandmarkRecognition, HMSApplication } from '@hmscore/react-native-hms-ml';
import { showImagePicker } from '@hmscore/react-native-hms-ml/example/src/HmsOtherServices/Helper';
import { WebView } from 'react-native-webview';
export default class App extends React.Component {
componentDidMount() { }
componentWillUnmount() { }
constructor(props) {
super(props);
this.state = {
imageUri: '',
landmark: [],
coordinates: [],
possibility: [],
url:[]
};
}
getLandmarkAnalyzerSetting = () => {
return { largestNumOfReturns: 10, patternType: HMSLandmarkRecognition.STEADY_PATTERN };
}
getFrameConfiguration = () => {
return { filePath: this.state.imageUri };
}
async asyncAnalyzeFrame() {
try {
var result = await HMSLandmarkRecognition.asyncAnalyzeFrame(true, this.getFrameConfiguration(), this.getLandmarkAnalyzerSetting());
console.log(result);
if (result.status == HMSApplication.SUCCESS) {
result.result.forEach(element => {
this.state.landmark.push(element.landMark);
this.state.possibility.push(element.possibility);
this.state.url.push('https://en.wikipedia.org/wiki/'+element.landMark)
long = [];
lat = [];
element.coordinates.forEach(ll => {
long.push(ll.longitude);
lat.push(ll.latitude);
})
this.state.coordinates.push(lat, long);
});
this.setState({
landMark: this.state.landmark,
possibility: this.state.possibility,
coordinates: this.state.coordinates,
url:this.state.url,
});
}
else {
ToastAndroid.showWithGravity(result.message, ToastAndroid.SHORT, ToastAndroid.CENTER);
}
} catch (e) {
console.error(e);
}
}
startAnalyze() {
this.setState({
landmark: [],
possibility: [],
coordinates: [],
url:[],
})
this.asyncAnalyzeFrame();
}
render() {
console.log(this.state.url.toString());
return (
<ScrollView style={styles.bg}>
<View style={styles.containerCenter}>
<TouchableOpacity onPress={() => { showImagePicker().then((result) => this.setState({ imageUri: result })) }}>
<Image style={styles.imageSelectView} source={this.state.imageUri == '' ? require('@hmscore/react-native-hms-ml/example/assets/image.png') : { uri: this.state.imageUri }} />
</TouchableOpacity>
</View>
<Text style={styles.h1}>pick the image and explore the information about place</Text>
<View style={styles.basicButton}>
<TouchableOpacity
style={styles.startButton}
onPress={this.startAnalyze.bind(this)}
disabled={this.state.imageUri == '' ? true : false} >
<Text style={styles.startButtonLabel}> Check Place </Text>
</TouchableOpacity>
</View>
<Text style={{fontSize: 20}}> {this.state.landmark.toString()} </Text>
<View style={{flex: 1}}>
<WebView
source={{uri: this.state.url.toString()}}
style={{marginTop: 20,height:1500}}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
scalesPageToFit={true}
/>
</View>
</ScrollView>
);
}
}
Run the application (Generating the Signed Apk):
1. Open project directory path in Command prompt.
2. Navigate to android directory and run the below command for signing the Apk.
Code:
gradlew assembleRelease
Output:
Tips and Tricks:
Download latest HMS ReactNativeML plugin.
Copy the api_key value in your agconnect-services.json file and set API key.
Images in PNG, JPG, JPEG, and BMP formats are supported. GIF images are not supported.
For project cleaning, navigate to android directory and run the below command.
Code:
gradlew clean
Conclusion:
In this article, we have learnt to integrate ML kit in React native project.
This service into a travel apps, so that images taken by users and detected by ML Plugin to return the landmark information, and the app can provide the brief introduction and tour suggestions to user.
Reference
https://developer.huawei.com/consum...-Guides/landmark-recognition-0000001050726194

Expert: Integration of Google Tag Manager and Huawei Dynamic Tag Manager for Firebase Android App

Overview
In this article, I will create an Android Demo app that highlights use case of Google Tag Manager and Dynamic Tag Manager in a Single Android App. I have integrated Huawei Analytics and Google Analytics.
I will create an AppGallery project and deploy AppGallery into the application. I will fire a basic event, so we can debug the hits sent from AppGallery to Huawei Analytics.
I will create a Google Tag Manager container for Firebase, and I will install that in application. I will use that container to take the event when we configured Firebase and will send the data to a (non-Firebase) Google Analytics property as well.
Huawei Analytics Introduction
Analytics kit is powered by Huawei which allows rich analytics models to understand user behaviour and gain in-depth insights into users, products, and content. As such, you can carry out data-driven operations and make strategic decisions about app marketing and product optimization.
Analytics Kit implements the following functions using data collected from apps:
1. Provides data collection and reporting APIs for collection and reporting custom events.
2. Sets up to 25 user attributes.
3. Supports automatic event collection and session calculation as well as predefined event IDs and parameters.
Google Analytics Introduction
Google Analytics collects usage and behaviour data for your app. The SDK logs two primary types of information:
Events: What is happening in your apps, such as user actions, system events, or errors?
User properties: Attributes you define to describe segments of your user base, such as language preference or geographic location.
Analytics automatically logs some events and user properties, you don't need to add any code to enable them.
Dynamic Tag Manager Introduction
Dynamic Tag Manager is a concept of improving collaboration between developers and marketers. It eliminates the need for restructuring application code as a result of new marketing intelligence requirements.
Dynamic Tag Manager console allows you to define different tags and manage the rules that trigger them. One specific tag type is the Universal Analytics tag, which enables you to integrate your Huawei Analytics project with Dynamic Tag Manager. This tag is easily set up by associating it with your Analytics key. This will expose the tags you are firing to your Analytics project in their raw form. From that point, you can define what data is sent to your Analytics project, when and how, without the need of changing your application’s code-of course, assuming you have smartly integrated the Huawei Dynamic Tag Manager’s SDK into your app in the first place.
Google Tag Manager
Google Tag Manager enables developers to change configuration values in their mobile application using the Google Tag Manager interface without having to rebuild and resubmit application binaries to app marketplaces.
This is useful for managing any configuration values or flags in your application that you may need to change in the future, including:
Various UI settings and display strings.
Sizes, locations, or types of ads served in your application.
Various Game settings.
Configuration values may also be evaluated at runtime using rules, enabling dynamic configurations such as:
Using screen size to determine ad banner size.
Using language and location to configure UI elements.
Google TagManager also enables the dynamic implementation of tracking tags and pixels in applications. Developers can push important events into a data layer and decide later which is tracking tags or pixels should be fired.
Prerequisite
1. Android Studio
2. Huawei phone
3. Firebase Account
4. AppGallery Account
App Gallery Integration process
1. Sign In and Create or Choose a project on AppGallery Connect portal.
{
"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. Navigate to Project settings and download the configuration file.
3. Navigate to General Information > Data Storage location.
4. Navigate to Manage APIs > Enable APIs.
5. Enable Huawei Analytics.
6. Enable Dynamic Tag Manager.
7. Create Tag.
8. Configure Tag.
9. Pause or Delete Tag.
Firebase Integration Process
1. Create a Firebase project.
2. Choose Android as a Platform.
3. Add App to your Firebase Project.
4. Download Configuration file.
5. Navigate to Google Tag Manager Console.
Create New Tag, then click Submit.
6. Choose tag type.
7. Choose a Variable
8. Tag Configure.
9. Publish Tag
10. Download the Tag and Add in your Android App.
(Your Project)Android App > Assets > Container > tag_file.
App Development
1. Create A New Project.
2. Configure Project Gradle.
Java:
buildscript {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath 'com.google.gms:google-services:4.3.5'
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3. Configure App Gradle.
Java:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.huawei.agconnect'
android {
compileSdkVersion 30
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.gtm.dtm"
minSdkVersion 27
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//Google Tag Manager with Analytics
implementation platform('com.google.firebase:firebase-bom:26.8.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.android.gms:play-services-tagmanager:17.0.0'
//Dynamic Tag Manager with Huawei Analytics
implementation "com.huawei.hms:hianalytics:5.2.0.300"
implementation "com.huawei.hms:dtm-api:5.2.0.300"
implementation 'in.shadowfax:proswipebutton:1.2.2'
}
4. Configure AndroidManifest.
XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gtm.dtm">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.google.android.gms.tagmanager"
android:noHistory="true">
<intent-filter>
<data android:scheme="tagmanager.c.com.example.app" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
<meta-data
android:name="com.huawei.hms.client.channel.androidMarket"
android:value="false" />
</application>
</manifest>
5. Create an Activity class with XML UI.
MainActivity:
This activity performs all the operation of Huawei Analytics and Google Analytics based on button click events.
Java:
package com.gtm.dtm;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.huawei.hms.analytics.HiAnalytics;
import com.huawei.hms.analytics.HiAnalyticsInstance;
import in.shadowfax.proswipebutton.ProSwipeButton;
public class MainActivity extends AppCompatActivity {
private HiAnalyticsInstance instance;
private FirebaseAnalytics mFirebaseAnalytics;
private ProSwipeButton btnGTM;
private ProSwipeButton btnDTM;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAnalytics=FirebaseAnalytics.getInstance(this);
instance = HiAnalytics.getInstance(this);
btnGTM = (ProSwipeButton) findViewById(R.id.btn_gtm);
btnGTM.setOnSwipeListener(new ProSwipeButton.OnSwipeListener() {
@Override
public void onSwipeConfirm() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
btnGTM.showResultIcon(true);
sendGTMEvent();
}
}, 2000);
}
});
btnDTM = (ProSwipeButton) findViewById(R.id.btn_dtm);
btnDTM.setOnSwipeListener(new ProSwipeButton.OnSwipeListener() {
@Override
public void onSwipeConfirm() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
btnDTM.showResultIcon(true);
sendDTMEvent();
}
}, 2000);
}
});
}
private void sendDTMEvent() {
String eventName = "DTM";
Bundle bundle = new Bundle();
bundle.putString("Click", "Pressed button");
if (instance != null) {
instance.onEvent(eventName, bundle);
Log.d("DTM-Test","log event.");
}
}
private void sendGTMEvent(){
Bundle bundle = new Bundle();
bundle.putString("Click", "Pressed button");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.ADD_TO_CART, bundle);
}
}
main_activity.xml:
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@drawable/bg">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:gravity="center_horizontal"
android:text="Google Tag Manager \n vs \n Dynamic Tag Manager"
android:textColor="#fff"
android:textSize="30dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp">
<in.shadowfax.proswipebutton.ProSwipeButton
android:id="@+id/btn_dtm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:arrow_color="#33FFFFFF"
app:bg_color="@android:color/holo_red_dark"
app:btn_radius="2"
app:btn_text="Send DTM Event"
app:text_color="@android:color/white"
app:text_size="14sp" />
<in.shadowfax.proswipebutton.ProSwipeButton
android:id="@+id/btn_gtm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginTop="10dp"
app:arrow_color="#33FFFFFF"
app:bg_color="@android:color/holo_green_dark"
app:btn_radius="2"
app:btn_text="Send GTM Event"
app:text_color="@android:color/white"
app:text_size="14sp" />
</LinearLayout>
</RelativeLayout>
App Build Result
1. Google Analytics Debug View.
2. Huawei Analytics Overview.
3. App Result.
Tips and Tricks
1. 5.2.0 or later. If HMS Core (APK) is not installed or its version is earlier than 5.2.0, DTM functions can be normally used but the DTM SDK version cannot be updated automatically.
2. ICustomVariable and ICustomTag contain custom extensible variables and templates. You can also customize variables and templates in DTM to meet specific requirements.
Conclusion
In this article, we have learned how to integrate DTM and GTM in application. In this application, I have explained use case of Google tag manager with Dynamic Tag manager in a single application.
Thanks for reading this article. Be sure to like and comments on this article, if you found it helpful. It means a lot to me.
References
1. Huawei Tag Manager
2. Google Tag Manager Console
3. Google Firebase Console

Beginner: Integration of Huawei Mobile Services Account Kit in Banking app (kotlin)

{
"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 be integrating Huawei Account Kit in an Application.
Account Kit
Account Kit provides you with simple, secure and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
Use Case
The Account Kit will be used to log in into a Banking Application which can perform basic functions such as Enter Pin, Withdraw Money, Deposit Money and Check Balance.
Requirements
1. Any operating system (MacOS, Linux and Windows).
2. Must have a Huawei phone with HMS 4.0.2.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. Minimum API Level 21 is required.
5. Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
2. Create a project in android studio, refer Creating an Android Studio Project.
3. Generate a SHA-256 certificate fingerprint.
4. To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.
7. Enter SHA-256 certificate fingerprint and click Save, as follows.
8. Click Manage APIs tab and enable Account Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Account Kit
Code:
implementation 'com.huawei.hms:hwid:6.3.0.301'
11. Now Sync the gradle.
12. Add the required permission to the Manifestfile.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--check wifi state-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Development
Activity_main.xml
XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/sign_in"
android:layout_width="83dp"
android:layout_height="95dp"
android:text="Login with Huawei"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.471" />
</androidx.constraintlayout.widget.ConstraintLayout>
Main Activity
Java:
class MainActivity : AppCompatActivity() {
var sign_in: Button? = null
var authParams: AccountAuthParams? = null
var service: AccountAuthService? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sign_in = findViewById<View>(R.id.sign_in) as Button
sign_in.setOnClickListener(object : OnClickListener() {
fun onClick(view: View?) {
authParams =
AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode()
.createParams()
service = AccountAuthManager.getService([email protected], authParams)
startActivityForResult(service.getSignInIntent(), 8888)
}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
// Process the authorization result to obtain the authorization code from AuthAccount.
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 8888) {
val authAccountTask: jdk.internal.org.jline.utils.ShutdownHooks.Task<AuthAccount> =
AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful()) {
// The sign-in is successful, and the user's ID information and authorization code are obtained.
val authAccount: AuthAccount = authAccountTask.getResult()
Log.i("MainActivity", "serverAuthCode:" + authAccount.getAuthorizationCode())
Log.i("MainActivity", "getDisplayName:" + authAccount.getDisplayName())
Log.i("MainActivity", "getResult:" + authAccountTask.getResult())
} else {
// The sign-in failed.
Log.e(
"MainActivity",
"sign in failed:" + (authAccountTask.getException() as ApiException).getStatusCode()
)
}
}
}
}
Cloud Debugging
Use Cloud Debugging in HMS Toolkit to debug the app on a real device.
To use Cloud Debugging, you need to sign in using a HUAWEI ID, complete identity verification, and then authorize the sign-in.
Go to HMS > CloudDebugging.
You can use Available Devices. Select a device and click RUN.
Result
Conclusion
In this article, we have learnt that how HMS Toolkit helps us to Connects users from a wide range of devices, including phones, tablets, and smart displays. It serves over 900 million users from 190+ countries and regions worldwide and supports 70+ Languages. It guarantees two-factor authentication, real-time risk prediction, and GDPR compliance.
Reference
Account Kit: Documentation

Kickstarting Ads Kit by integrating Interstitial Ads in Application (Kotlin)

{
"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, we can learn how to integrate Huawei Ads Kit in an Application. 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
Any operating system (MacOS, Linux and Windows).
Must have a Huawei phone with HMS 4.0.2.300 or later.
Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Minimum API Level 21 is required.
Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
Create a project in android studio, refer Creating an Android Studio Project.
Generate a SHA-256 certificate fingerprint.
To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save.
8. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
9. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Ads Kit
Code:
Implementation 'com.huawei.hms:ads-lite:13.4.40.301'
10. Now Sync the gradle.
11. Add the required permission to the Manifestfile.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--check wifi state-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
12. If the project is using progaurd, copy and paste the below code in the progaurd-rules.pro file.
Code:
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
Development
In this example, we will place the interstitial ad between two activities. When the “CLICK TO START TRANSACTION” button is clicked on while in the MainActivity (the first activity in this example), an interstitial ad will be shown first, then the pin (the second activity in this example) will come to the place.
1. Create an interstitial ad object.
Code:
Create an InterstitialAd object and use the setAdId() method of the InterstitialAd class to set a test ad unit ID
private var interstitialAd: InterstitialAd? = null
var nextPageBtn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nextPageBtn = findViewById(R.id.btTrans)
interstitialAd = InterstitialAd(this)
interstitialAd.setAdId(adId)
interstitialAd.setAdListener(adListener)
}
2. Load an ad.
Code:
Call the loadAd() method of the InterstitialAd object to load an ad.
private fun loadInterstitialAd() {
...
// Load an interstitial ad.
val adParam = AdParam.Builder().build()
interstitialAd!!.loadAd(adParam)
...
}
3. Display an ad.
Code:
Call the isLoaded() method to check whether an ad has been loaded. If the ad has been loaded, call the show(Activity activity) method of the InterstitialAd object to display the ad.
private fun showInterstitial() {
// Display an interstitial ad.
if (interstitialAd != null && interstitialAd.isLoaded()) {
interstitialAd.show()
} else {
startActivity(Intent([email protected], pin::class.java))
}
}
4. Listen for ad events.
Code:
Call the setAdListener(AdListener adListener) method of the InterstitialAd class to add the ad event listener AdListener for the InterstitialAd object, and implement the methods in AdListener to listen to ad events.
fun adEvent() {
adListener = object : AdListener() {
fun onAdLoaded() {
// Called when an ad is loaded successfully.
super.onAdLoaded()
Toast.makeText([email protected], "Ad loaded", Toast.LENGTH_SHORT).show()
// Display an interstitial ad.
showInterstitial()
}
fun onAdFailed(errorCode: Int) {
// Called when an ad fails to be loaded.
Toast.makeText(
[email protected], "Ad load failed with error code: $errorCode",
Toast.LENGTH_SHORT
).show()
Log.d(
TAG,
"Ad load failed with error code: $errorCode"
)
startActivity(Intent([email protected], pin::class.java))
}
fun onAdClosed() {
// Called when an ad is closed
super.onAdClosed()
Log.d(TAG, "onAdClosed")
startActivity(Intent([email protected], pin::class.java))
}
fun onAdClicked() {
// Called when an ad is clicked.
Log.d(TAG, "onAdClicked")
super.onAdClicked()
adListener.onAdClosed()
}
fun onAdOpened() {
// Called when an ad is opened.
Log.d(TAG, "onAdOpened")
super.onAdOpened()
}
fun onAdLeave() {
// Called when an ad leaves an app.
...
}
fun onAdLeave() {
// Called when an ad leaves an app.
...
}
}
}
Activity_mail.xml
Code:
<?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:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:id="@+id/activity_main"
android:background="@color/purple_200">
<Button
android:id="@+id/btTrans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/click_to_start_transaction"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="327dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_to_world_s_best_bank"
android:textSize="20dp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/hello" />
</RelativeLayout>
Adjust UI according to your application.
Result
Tips and Tricks
Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
Make sure you have added the agconnect-services.json file to app folder.
Make sure you have added SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Conclusion
In this article, we have learnt integration of Ads Kit in application. It provides developers different capabilities to deliver good quality ads content to users.
Reference
Ads Kit: Documentation

Categories

Resources