[Huawei Developers] shikkerimath:
Overview

In this article, I will create a demo app along with the integration of HMS Ads and Analytics Kit which is based on Cross-platform Technology Xamarin. I have implemented Ads Kit and Analytics Kit. So the developer can easily monetise their efforts using Banner, Splash, Reward and Interstitial Ads also to track the user’s behaviour through the Analytics kit.

Ads Kit Service Introduction

HMS Ads kit is powered by Huawei which allows the developer to monetization services such as Banner, Splash, Reward and Interstitial Ads. HUAWEI Ads Publisher Service is a monetization service that leverages Huawei's extensive data capabilities to display targeted, high-quality ad content in your application to the vast user base of Huawei devices.

Analytics Kit Service Introduction

Analytics kit is powered by Huawei which allows rich analytics models to help you clearly 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.

Prerequisite

1. Xamarin Framework

2. Huawei phone

3. Visual Studio 2019

App Gallery Integration process

1. Sign In and Create or Choose a project on AppGallery Connect portal.

View attachment 5243625

2. Add SHA-256 key.

View attachment 5243627

3. Navigate to Project settings and download the configuration file.

View attachment 5243629

4. Navigate to General Information, and then provide Data Storage location.

View attachment 5243631

5. Navigate to Manage APIs and enable APIs to require by application.

View attachment 5243633

6. Navigate to Huawei Analytics > Overview > Custom dashboard > Enable Analytics

View attachment 5243635

Xamarin Analytics Kit Setup Process

1. Download Xamarin Plugin of all the aar and zip files from below URL:

https://developer.huawei.com/consum...ibrary-V1/xamarin-android-0000001061360985-V1

View attachment 5243637

2. Open the XHiAnalytics-5.0.5.300.sln solution in Visual Studio.

View attachment 5243639

3. Navigate to Solution Explorer and right-click on jar Add > Existing Item and choose aar file which download in Step 1.

View attachment 5243641

4. Choose aar file from download location.

View attachment 5243643

5. Right-click on added aar file, then choose Properties > Build Action > LibraryProjectZip.

View attachment 5243645

Note: Repeat Step 3 and 4 for all aar file.

6. Build the Library and make DLL files.

View attachment 5243647

Xamarin Ads Kit Setup Process

1. Download Xamarin Plugin of all the aar and zip files from below URL:

https://developer.huawei.com/consum..._TOPIC_0000001050175494__section1134316505481

View attachment 5243649

2. Open the XAdsIdentifier-3.4.35.300.sln solution in Visual Studio.

View attachment 5243651

3. Navigate to Solution Explorer and right-click on jar Add > Existing Item and choose aar file which download in Step 1.

View attachment 5243653

4. Choose aar file from download location.

View attachment 5243655

5. Right-click on added aar file, then choose Properties > Build Action > LibraryProjectZip.

View attachment 5243657

Note: Repeat Step 3 and 4 for all aar file.

6. Build the Library and make DLL files.

View attachment 5243659

Xamarin App Development

1. Open Visual Studio 2019 and Create A New Project.

View attachment 5243661

2. Navigate to Solution Explore > Project > Add > Add New Folder.

View attachment 5243663

3. Navigate to Folder(created) > Add > Add Existing and add all DLL files.

Read full article in forum

Ads Kit Integration

Banner Ads Integration Procedure

Kindly refer to the below link:

https://developer.huawei.com/consum...in-Guides/xamarin-banner-ads-0000001050418457

Reward Ads Integration Procedure

Kindly refer to the below link:

https://developer.huawei.com/consum...-Guides/xamarin-rewarded-ads-0000001050178541

Interstitial Ads Integration Procedure

Kindly refer to the below link:

https://developer.huawei.com/consum...ugin-Guides/interstitial-ads-0000001050176486

Splash Ads Integration Procedure

Kindly refer to the below link:

https://developer.huawei.com/consum...in-Guides/xamarin-splash-ads-0000001050418461

Analytics Kit Integration

Initializing Analytics Kit Procedure

Kindly refer to the below link:

https://developer.huawei.com/consum...-Plugin-Guides/initanalytics-0000001050141599

LoginActivity.cs

This activity performs all the operation regarding login with Huawei Id along with display banner ads at bottom of the screen along with track analytics events.

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Huawei.Agconnect.Config;
using Com.Huawei.Hmf.Tasks;
using Com.Huawei.Hms.Ads;
using Com.Huawei.Hms.Ads.Banner;
using Com.Huawei.Hms.Ads.Nativead;
using Com.Huawei.Hms.Analytics;
using Com.Huawei.Hms.Common;
using Com.Huawei.Hms.Support.Hwid;
using Com.Huawei.Hms.Support.Hwid.Request;
using Com.Huawei.Hms.Support.Hwid.Result;
using Com.Huawei.Hms.Support.Hwid.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeatherAppDemo
{
[Activity(Label = "LoginActivity", Theme = "@style/AppTheme", MainLauncher = true)]
public class LoginActivity : AppCompatActivity
{
private static String TAG = "LoginActivity";
private HuaweiIdAuthParams mAuthParam;
public static IHuaweiIdAuthService mAuthManager;
// private NativeAd nativeAd;
private Button btnLoginWithHuaweiId;

HiAnalyticsInstance instance;

InterstitialAd interstitialAd;

protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.login_activity);

loadBannerAds();

HiAnalyticsTools.EnableLog();
// Generate the Analytics Instance
instance = HiAnalytics.GetInstance(this);
// You can also use Context initialization
// Context context = ApplicationContext;
// instance = HiAnalytics.GetInstance(context);
// Enable collection capability
instance.SetAnalyticsEnabled(true);

btnLoginWithHuaweiId = FindViewById<Button>(Resource.Id.btn_huawei_id);

btnLoginWithHuaweiId.Click += delegate
{
// Write code for Huawei id button click
mAuthParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DefaultAuthRequestParam)
.SetIdToken().SetEmail()
.SetAccessToken()
.CreateParams();
mAuthManager = HuaweiIdAuthManager.GetService(this, mAuthParam);
StartActivityForResult(mAuthManager.SignInIntent, 1011);

string text = "Login Clicked";
Toast.MakeText(Android.App.Application.Context, text, ToastLength.Short).Show();
// Initiate Parameters
Bundle bundle = new Bundle();
bundle.PutString("text", text);
instance.OnEvent("ButtonClickEvent", bundle);

navigateToHomeScreen();
};

checkPermission(new string[] { Android.Manifest.Permission.Internet,
Android.Manifest.Permission.AccessNetworkState,
Android.Manifest.Permission.ReadSms,
Android.Manifest.Permission.ReceiveSms,
Android.Manifest.Permission.SendSms,
Android.Manifest.Permission.BroadcastSms}, 100);
}

private void loadBannerAds()
{
// Obtain BannerView based on the configuration in layout
BannerView bottomBannerView = FindViewById<BannerView>(Resource.Id.hw_banner_view);
bottomBannerView.AdListener = new AdsListener();
AdParam adParam = new AdParam.Builder().Build();
bottomBannerView.LoadAd(adParam);

// Obtain BannerView using coding
BannerView topBannerview = new BannerView(this);
topBannerview.AdId = "testw6vs28auh3";
topBannerview.BannerAdSize = BannerAdSize.BannerSize32050;
topBannerview.LoadAd(adParam);
}

private void LoadInterstitialAd()
{
InterstitialAd interstitialAd = new InterstitialAd(this);
interstitialAd.AdId = "testb4znbuh3n2"; //testb4znbuh3n2 is a dedicated test ad slot ID.
AdParam adParam = new AdParam.Builder().Build();
interstitialAd.LoadAd(adParam);
}

private void ShowInterstitial()
{
interstitialAd.AdListener = new AdsListenerInterstitial(this);
// Display an interstitial ad.
if (interstitialAd != null && interstitialAd.IsLoaded)
{
interstitialAd.Show();
}
else
{
// The ad was not loaded.
}
}

private class AdsListenerInterstitial : AdListener
{
LoginActivity interstitialActivity;
public AdsListenerInterstitial(LoginActivity interstitialActivity)
{
this.interstitialActivity = interstitialActivity;
}
public override void OnAdClicked()
{
// Called when an ad is clicked.
}
public override void OnAdClosed()
{
// Called when an ad is closed.
}
public override void OnAdFailed(int errorCode)
{
// Called when an ad fails to be loaded.
}
public override void OnAdLeave()
{
// Called when a user leaves an ad.
}
public override void OnAdLoaded()
{
// Called when an ad is loaded successfully.
// Display an interstitial ad.
interstitialActivity.ShowInterstitial();
}
public override void OnAdOpened()
{
// Called when an ad is opened.
}
}

public void checkPermission(string[] permissions, int requestCode)
{
foreach (string permission in permissions)
{
if (ContextCompat.CheckSelfPermission(this, permission) == Permission.Denied)
{
ActivityCompat.RequestPermissions(this, permissions, requestCode);
}
}
}

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

protected override void AttachBaseContext(Context context)
{
base.AttachBaseContext(context);
AGConnectServicesConfig config = AGConnectServicesConfig.FromContext(context);
config.OverlayWith(new HmsLazyInputStream(context));
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 1011 || requestCode == 1022)
{
//login success
Task authHuaweiIdTask = HuaweiIdAuthManager.ParseAuthResultFromIntent(data);
if (authHuaweiIdTask.IsSuccessful)
{
AuthHuaweiId huaweiAccount = (AuthHuaweiId)authHuaweiIdTask.TaskResult();
Log.Info(TAG, "signIn get code success.");
Log.Info(TAG, "ServerAuthCode: " + huaweiAccount.AuthorizationCode);
Toast.MakeText(Android.App.Application.Context, "SignIn Success", ToastLength.Short).Show();
// navigateToHomeScreen(huaweiAccount);
}

else
{
Log.Info(TAG, "signIn failed: " + ((ApiException)authHuaweiIdTask.Exception).StatusCode);
Toast.MakeText(Android.App.Application.Context, ((ApiException)authHuaweiIdTask.Exception).StatusCode.ToString(), ToastLength.Short).Show();
Toast.MakeText(Android.App.Application.Context, "SignIn Failed", ToastLength.Short).Show();

}
}
}

private void showLogoutButton()
{
/*logout.Visibility = Android.Views.ViewStates.Visible;*/
}

private void hideLogoutButton()
{
/*logout.Visibility = Android.Views.ViewStates.Gone;*/
}

private void navigateToHomeScreen(/*AuthHuaweiId data*/)
{
Intent intent = new Intent(this, typeof(MainActivity));
/*intent.PutExtra("name", data.DisplayName.ToString());
intent.PutExtra("email", data.Email.ToString());
intent.PutExtra("image", data.PhotoUriString.ToString());*/
StartActivity(intent);
Finish();
}

private class AdsListener : AdListener
{

public override void OnAdClicked()
{
// Called when a user taps an ad.
Log.Info(TAG, "Ad Clicked");
Toast.MakeText(Application.Context, "Ad Clicked", ToastLength.Short).Show();
}
public override void OnAdClosed()
{
// Called when an ad is closed.
Log.Info(TAG, "Ad Closed");
Toast.MakeText(Application.Context, "Ad Closed", ToastLength.Short).Show();
}
public override void OnAdFailed(int errorCode)
{
// Called when an ad fails to be loaded.
Log.Info(TAG, "Ad Failed");
Toast.MakeText(Application.Context, "Ad Failed", ToastLength.Short).Show();
}

public override void OnAdLeave()
{
// Called when a user has left the app.
Log.Info(TAG, "Ad Leave");
/*Toast.MakeText(Android.App.Application.Context, "Ad Leave", ToastLength.Short).Show();*/
}
public override void OnAdOpened()
{
// Called when an ad is opened.
Log.Info(TAG, "Ad Opened");
/*Toast.MakeText(Android.App.Application.Context, "Ad Opened", ToastLength.Short).Show();*/
}
public override void OnAdLoaded()
{
// Called when an ad is loaded successfully.
Log.Info(TAG, "Ad Loaded");
Toast.MakeText(Application.Context, "Ad Loaded", ToastLength.Short).Show();
}
}

}
}

Tips and Tricks

1. On mobile phones whose value of targetSdkVersion is 28 or later, ad video assets may fail to be downloaded. In this case, you need to configure the app to allow HTTP network requests. For details, please refer to Configuring Network Permissions.

2. Xamarin requires the ADB daemon to be started over port 5037. If the ADB daemon runs on a different port, Visual Studio will not be able to detect your device.

Conclusion

In this article, we have learned how to integrate HMS Ads and Analytics Kit in Xamarin based Android application. We can display ads and track the user’s event in the 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

https://developer.huawei.com/consum...-Guides/service-introduction-0000001050178531

https://developer.huawei.com/consum..._TOPIC_0000001050175494__section1134316505481

https://developer.huawei.com/consum...S-Plugin-Guides/introduction-0000001050139636

https://forums.developer.huawei.com/forumPortal/en/topic/0204485009808440045

Read full article in forum