[Huawei Developers] John Wo:
More information like this, you can visit HUAWEI Developer Forum​

In this article we are going to take a look at Huawei Mobile Services (HMS) Push Kit Plugin for Xamarin.Android then we will send our first notification and data message by Huawei Console. After that we will also send them by Push Kit APIs.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120347.74784208826448298337478634129972:50511012065644:2800:6EC16A203E46009EF2444A844A452DCB0CB062E7A768F1B4724D21BCF91F5874.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120347.74784208826448298337478634129972:50511012065644:2800:6EC16A203E46009EF2444A844A452DCB0CB062E7A768F1B4724D21BCF91F5874.png[/IMG]​

HUAWEI Push Kit

Push Kit, is a messaging service provided by Huawei for developers. It offers sending real time notifications and information messages. This helps developers maintain closer ties with users and increases user awareness and engagement. Furthermore, you are free to use on any different meaningful purposes.

HUAWEI Push Kit Xamarin.Android Integration

First of all, you need to be a Huawei Developer to use Huawei Push Kit. If you do not have a HUAWEI ID, register as a Huawei Developer and complete real-name authentication. For details, see Registering as a Developer.

Next, Sign in to AppGallery Connect using the approved Huawei ID and click on the “My projects” button.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120336.68687844118093035897258468638533:50511012065644:2800:87599221AC95A31283C98EC662F9D53BBBA5F6117AC13607382A2103E763AF33.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120336.68687844118093035897258468638533:50511012065644:2800:87599221AC95A31283C98EC662F9D53BBBA5F6117AC13607382A2103E763AF33.png[/IMG]​

Then click the “Add project” button and enter a name for your project.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120329.36062544533620719273423787565831:50511012065644:2800:4F3D434EB27B7D958065034A8C4E56FAFF8727FA015D403309F7AEB959D30092.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120329.36062544533620719273423787565831:50511012065644:2800:4F3D434EB27B7D958065034A8C4E56FAFF8727FA015D403309F7AEB959D30092.png[/IMG]​

After that, set project data storage location. For this Project Setting > General information > Project > Data storage location. As a location choose Germany then submit it. Afterwards, click “Add app” button in the same page then fill all the fields (if you do not know what “Package name” is just copy from Xamarin.Android Solution > Project > Properties >AndroidManifest.xml > package) after that submit.

Adding Push Kit to Your Xamarin.Android App

Firstly, we must generate the “.keystore” file. You can copy following text into batch file and change toolpath and aliasName then run it in “C:\Program Files\Java\jdk1.8.0\bin” folder. For details, see Pre-development Procedure.

SET toolPath="C:\tmp\tool.jks"
SET aliasName=aliasname
keytool -genkey -keystore %toolPath% -alias %aliasName% -keyalg RSA -dname "o=Huawei"
pause
keytool -list -v -keystore %toolPath%
pause

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120308.19651752382098484947020653560527:50511012065644:2800:62FD0F9F255DBFD2A5F6EBE1DCE961ECBA259ABB6D194000F0AFAC15B3A0F62F.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120308.19651752382098484947020653560527:50511012065644:2800:62FD0F9F255DBFD2A5F6EBE1DCE961ECBA259ABB6D194000F0AFAC15B3A0F62F.png[/IMG]​

Keep these Alias name and SHA256 code. Open the project in Visual Studio then Properties of project afterwards fill the fields. It would be better to do this for both Debug and Release because later when you release the project you have to fill these areas.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120301.21325166292054976343647983512472:50511012065644:2800:F32238B1BEB91B590C009618AE3CC6C49311AA637E926E5F17BCE059D48C3AAF.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120301.21325166292054976343647983512472:50511012065644:2800:F32238B1BEB91B590C009618AE3CC6C49311AA637E926E5F17BCE059D48C3AAF.png[/IMG]​

Now, it is turn to use SHA256 fingerprint. Copy it and paste SHA-256 certificate fingerprint section then click to tick icon to save it.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120245.92216085890365426484891064031058:50511012065644:2800:B2A0DD24BF8ED44D4AA2DC647D5CD2D91400FDD96DD01B7C965813EF1858F66C.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120245.92216085890365426484891064031058:50511012065644:2800:B2A0DD24BF8ED44D4AA2DC647D5CD2D91400FDD96DD01B7C965813EF1858F66C.png[/IMG]​

Next, download “agconnect-services.json” file, afterwards right click on “Assets” folder in your project then Add > Existing Item and choose this file. At last enable the Push Kit.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120218.75946718210882455574286008442441:50511012065644:2800:E96D1FC90B2E2DE37CABE73F6664A42C2A07862BDC875F53DB8FBC36C03A8D40.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120218.75946718210882455574286008442441:50511012065644:2800:E96D1FC90B2E2DE37CABE73F6664A42C2A07862BDC875F53DB8FBC36C03A8D40.png[/IMG]

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120205.47395610344774454613236483669947:50511012065644:2800:0E251347045A8B6C5ADE0C8A3D4EC90F351688B7AFDC19DC7A41F6294C559063.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120205.47395610344774454613236483669947:50511012065644:2800:0E251347045A8B6C5ADE0C8A3D4EC90F351688B7AFDC19DC7A41F6294C559063.png[/IMG]​

Adding HUAWEI Push Kit Plugins in Our Project

Firstly, you need to create Android Binding Libraries for Xamarin. For this, see Creating Android Binding Libraries for Xamarin.

Secondly, you need to add these libraries to your project. For this, see Integrating the Xamarin HMS Push Kit Libraries.

Finally, HUAWEI Push Kit requires some permissions to work correctly. For this right click your project >Properties > Android Manifest then scroll to the bottom of the page. Enable following permissions.

· ACCESS_NETWORK_STATE

· INTERNET

· WAKE_LOCK

· DEFAULT (android.intent.category)

· BROWSABLE (android.intent.category)

· DEFAULT (android.permission)

Integrating HMS Core SDK

Add new class as “HmsLazyInputStream.cs” then paste following code.

using System;
using System.IO;
using Android.Util;
using Android.Content;
using Com.Huawei.Agconnect.Config;
namespace XamarinHmsPushDemo.Hmssample
{
class HmsLazyInputStream : LazyInputStream
{
public HmsLazyInputStream(Context context) : base(context)
{
}
public override Stream Get(Context context)
{
try
{
return context.Assets.Open("agconnect-services.json");
}
catch (Exception e)
{
Log.Error(e.ToString(), "Can't open agconnect file");
return null;
}
}
}
}

Next, add “using Com.Huawei.Agconnect.Config;” library in your MainActivity class afterwards add following code.

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

Push Notification

When we send push notification, phone shows this notification on Notification Center. Before we send notification by HUAWEI Push Kit, first the device needs to get a push token.

Add following method into your MainActivity class afterwards call from OnCreate() method then copy the token from Output.

private void GetToken()
{
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
try
{
string appid = AGConnectServicesConfig.FromContext(this).GetString("client/app_id");
string token = HmsInstanceId.GetInstance(this).GetToken(appid, "HCM");
Log.Info("token", token);
}
catch (Exception e)
{
Log.Info("token", e.ToString());
}
}
);
thread.Start();
}

Open your project in AppGallery Connect then Growing > Push Kit > Add notification. Fill the areas as you wish then click “Test effect” button and paste your token there.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120133.38076141037060336556091458884668:50511012065644:2800:50DCE3B833CEF45806B2132B1F77AFDD4EA752EC2476563368F1D77B0D7AE968.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729120133.38076141037060336556091458884668:50511012065644:2800:50DCE3B833CEF45806B2132B1F77AFDD4EA752EC2476563368F1D77B0D7AE968.png[/IMG]​

Data Message

When we send data message to a device, OnMessageReceived method will be triggered then we can use this message. In this example we will send data message and show on application.

To receive a push data message and call other related Push Kit APIs, first you need to create a class that implements “HmsMessageService”. You can use all the code in this link but I will just use omitted OnMessageReceived method for clarity. Furthermore, I want to show you this message on Toast therefore we will also add MyBroadcastReceiver class. Moreover you should get instance of MyBroadcastReceiver in OnCreate method.

using Android.App;
using Android.Content;
using Android.Widget;
using Com.Huawei.Hms.Push;
namespace PushDemo
{
[Service]
[IntentFilter(new[] { "com.huawei.push.action.MESSAGING_EVENT" })]
public class MyMessagingService:HmsMessageService
{
private readonly static string PUSHDEMO_ACTION = "com.companyname.pushdemo.action";
public override void OnMessageReceived(RemoteMessage message)
{
Intent intent = new Intent(PUSHDEMO_ACTION);
intent.PutExtra("msg", message.Data);
SendBroadcast(intent);
}
}
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "com.companyname.pushdemo.action" })]
public class MyBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Toast.MakeText(context, intent.GetStringExtra("msg"), ToastLength.Long).Show();
}
}
}

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729115700.88595579382881440346723276077510:50511012065644:2800:41B4D2CD2636B7CD3B2AD4714CA7EAB2887F382AFA46777A62B5A591BDA8FB58.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729115700.88595579382881440346723276077510:50511012065644:2800:41B4D2CD2636B7CD3B2AD4714CA7EAB2887F382AFA46777A62B5A591BDA8FB58.png[/IMG]​

You will get the Toast, when you click Test effect then OK.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729115505.10903695993229984749144747673409:50511012065644:2800:32C5E60BB9866ABB56F0C6545BDFFFB1288F32064ADCAF96AA1F5EDDE7793B13.jpg"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/026/361/098/5190090000026361098.20200729115505.10903695993229984749144747673409:50511012065644:2800:32C5E60BB9866ABB56F0C6545BDFFFB1288F32064ADCAF96AA1F5EDDE7793B13.jpg[/IMG]​

Using Push Kit APIs

We have sent notification and data message by HUAWEI console, now it is time to send it by HUAWEI Push Kit APIs. At this part main point is showing sample code. You can use this sample code on your other application (WFA, Web APIs, and Web Site etc.). Here is a sample code and little bit modify on GetToken and OnCreate :

using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using Com.Huawei.Agconnect.Config;
using Android.Content;
using XamarinHmsPushDemo.Hmssample;
using Com.Huawei.Hms.Aaid;
using Android.Util;
using System;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Text;
using System.Threading.Tasks;
namespace PushDemoForArticle
{
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
string tokenFromGetToken;//GetToken()
string appID = "appID";//AppGallery Connect > Project Setting > App information > App ID
string appKey = "APIkey";//AppGallery Connect > Project Setting > App information > App key
private static readonly HttpClient client = new HttpClient();
Button btnGetToken;
Button btnNotification;
Button btnDataMessage;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
btnGetToken = FindViewById<Button>(Resource.Id.btnGetToken);
btnGetToken.Click += (sender, args) => GetToken();
btnNotification = FindViewById<Button>(Resource.Id.btnNotification);
btnNotification.Click += (sender, args) => SendNotification();
btnDataMessage = FindViewById<Button>(Resource.Id.btnDataMessage);
btnDataMessage.Click += (sender, args) => SendDataMessage();
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
}
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));
}
private void GetToken()
{
System.Threading.Thread thread = new System.Threading.Thread(() =>
{
try
{
string appid = AGConnectServicesConfig.FromContext(this).GetString("client/app_id");
tokenFromGetToken = HmsInstanceId.GetInstance(this).GetToken(appid, "HCM");
Log.Info("token", tokenFromGetToken);
RunOnUiThread(() =>
{
btnNotification.Visibility = Android.Views.ViewStates.Visible;
btnDataMessage.Visibility = Android.Views.ViewStates.Visible;
});
}
catch (Exception e)
{
Log.Info("token", e.ToString());
}
}
);
thread.Start();
}
public async Task<string> GetAccessToken()
{
string uri = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
var values = new Dictionary<string, string>
{
{ "grant_type", "client_credentials" },
{ "client_id", appID },
{ "client_secret", appKey }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(uri, content);
var jsonResponse = JObject.Parse(await response.Content.ReadAsStringAsync()); //Install-Package Newtonsoft.Json
string accessToken = jsonResponse["access_token"].ToString(); //It is valid for 3600 seconds
return accessToken;
}
public async void SendNotification()
{
string uriNot = "https://push-api.cloud.huawei.com/v1/" + appID + "/messages:send";
var jObject = new
{
message = new
{
notification = new
{
title = "This is title",
body = "This is body part"
},
android = new
{
notification = new
{
click_action = new
{
type = 3
}
}
},
token = new[] { tokenFromGetToken }
}
};
string myJson = JsonConvert.SerializeObject(jObject, Formatting.Indented);
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", await GetAccessToken());
var responseData = await client.PostAsync(uriNot, new StringContent(myJson, Encoding.UTF8, "application/json"));
}
public async void SendDataMessage()
{
string uriNot = "https://push-api.cloud.huawei.com/v1/" + appID + "/messages:send";
var jObject = new
{
message = new
{
data = JsonConvert.SerializeObject(new
{
title = "Message Title",
text = "Message Body",
randomKey = "You can write any key and value"
}, Formatting.None),
token = new[] { tokenFromGetToken }
}
};
string myJson = JsonConvert.SerializeObject(jObject, Formatting.Indented);
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", await GetAccessToken());
var responseData = await client.PostAsync(uriNot, new StringContent(myJson, Encoding.UTF8, "application/json"));
}
}
}
copy
<LinearLayout
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Get Token"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="150px"
android:id="@+id/btnGetToken" />
<Button
android:text="Send Notification"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="150px"
android:visibility="invisible"
android:id="@+id/btnNotification" />
<Button
android:text="Send Data Message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="150px"
android:visibility="invisible"
android:id="@+id/btnDataMessage" />
</LinearLayout>