Tutorial: Push notifications to Xamarin.Android apps using Azure Notification Hubs

Overview

This tutorial shows you how to use Azure Notification Hubs to send push notifications to a Xamarin.Android application. You create a blank Xamarin.Android app that receives push notifications by using Firebase Cloud Messaging (FCM). You use your notification hub to broadcast push notifications to all the devices running your app. The finished code is available in the NotificationHubs app sample.

In this tutorial, you take the following steps:

  • Create a Firebase project and enable Firebase Cloud Messaging
  • Create a notification hub
  • Create a Xamarin.Android app and connect it to the notification hub
  • Send test notifications from the Azure portal

Prerequisites

Create a Firebase project and enable Firebase Cloud Messaging

  1. Sign in to the Firebase console. Create a new Firebase project if you don't already have one.

  2. After you create your project, select Add Firebase to your Android app.

    Add Firebase to your Android app

  3. On the Add Firebase to your Android app page, take the following steps:

    1. For the Android package name, enter a name for your package. For example: tutorials.tutoria1.xamarinfcmapp.

      Specify the package name

    2. Select Register app.

    3. Select Download google-services.json. Then save the file into the folder of your project and select Next. If you haven't created the Visual Studio project yet, you can do this step after you create the project.

      Download google-services.json

    4. Select Next.

    5. Select Skip this step.

      Skip the last step

  4. In the Firebase console, select the cog for your project. Then select Project Settings.

    Select Project Settings

  5. If you haven't downloaded the google-services.json file, you can do download it on this page.

    Download google-services.json from the General tab

  6. Switch to the Cloud Messaging tab at the top. Copy and save the Server key for later use. You use this value to configure your notification hub.

    Copy server key

Create a notification hub

  1. Sign in to the Azure portal.

  2. Select All services on the left menu, and then select Notification Hubs in the Mobile section. Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. After you add Notification Hubs to FAVORITES, select it on the left menu.

    Azure portal - select Notification Hubs

  3. On the Notification Hubs page, select Add on the toolbar.

    Notification Hubs - Add toolbar button

  4. On the Notification Hub page, do the following steps:

    1. Enter a name in Notification Hub.

    2. Enter a name in Create a new namespace. A namespace contains one or more hubs.

    3. Select a value from the Location drop-down list box. This value specifies the location in which you want to create the hub.

    4. Select an existing resource group in Resource Group, or create a name for a new resource group.

    5. Select Create.

      Azure portal - set notification hub properties

  5. Select Notifications (the bell icon), and then select Go to resource. You can also refresh the list on the Notification Hubs page and select your hub.

    Azure portal - notifications -> Go to resource

  6. Select Access Policies from the list. Note that the two connection strings are available to you. You'll need them later to handle push notifications.

    Important

    Do not use the DefaultFullSharedAccessSignature policy in your application. This is meant to be used in your back end only.

    Azure portal - notification hub connection strings

Configure GCM/FCM settings for the notification hub

  1. Select Google (GCM/FCM)/ in the Settings section on the left menu.

  2. Enter the server key you noted down from the Google Firebase Console.

  3. Select Save on the toolbar.

Your notification hub is configured to work with FCM, and you have the connection strings to both register your app to receive notifications and to send push notifications.

Create a Xamarin.Android app and connect it to notification hub

Create Visual Studio project and add NuGet packages

Note

The steps documented in this tutorial are for Visual Studio 2017.

  1. In Visual Studio, open the File menu, select New, and then select Project. In the New Project window, do these steps:

    1. Expand Installed, Visual C#, and then click Android.

    2. Select Android App (Xamarin) from the list.

    3. Enter a name for the project.

    4. Select a location for the project.

    5. Select OK

      New Project dialog

  2. On the New Android App dialog box, select Blank App, and select OK.

    New Project dialog

  3. In the Solution Explorer window, expand Properties, and click AndroidManifest.xml. Update the package name to match the package name you entered when adding Firebase Cloud Messaging to your project in the Google Firebase Console.

    Package name in GCM

  4. Set the target Android version for the project to Android 9.0 (pie) by following these steps:

    1. Right-click your project, and select Properties.
    2. For the Compile using Android version: (Target framework) field, select Android 9.0 (Pie).
    3. Select Yes on the message box to continue with changing the target framework.
  5. Add required NuGet packages to the project by following these steps:

    1. Right-click your project, and select Manage NuGet Packages....

    2. Switch to the Installed tab, select Xamarin.Android.Support.Design, and select Update in the right pane to update the package to the latest version.

    3. Switch to the Browse tab. Search for Xamarin.GooglePlayServices.Base. Select Xamarin.GooglePlayServices.Base in the result list. Then, select Install.

      Google Play Services NuGet

    4. In the NuGet Package Manager window, search for Xamarin.Firebase.Messaging. Select Xamarin.Firebase.Messaging in the result list. Then, select Install.

    5. Now, search for Xamarin.Azure.NotificationHubs.Android. Select Xamarin.Azure.NotificationHubs.Android in the result list. Then, select Install.

Add the Google Services JSON File

  1. Copy the google-services.json file that you downloaded from the Google Firebase Console to the project folder.

  2. Add google-services.json to the project.

  3. Select google-services.json in the Solution Explorer window.

  4. In the Properties pane, set the Build Action to GoogleServicesJson. If you don't see GoogleServicesJson, close Visual Studio, relaunch it, reopen the project, and retry.

    GoogleServicesJson build action

Set up notification hubs in your project

Registering with Firebase Cloud Messaging

  1. Open the AndroidManifest.xml file and insert the following <receiver> elements into the <application> element:

    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
    <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
        <category android:name="${applicationId}" />
        </intent-filter>
    </receiver>
    
  2. Add the following statements before the application element.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    
  3. Gather the following information for your Android app and notification hub:

    • Listen connection string: On the dashboard in the Azure portal, choose View connection strings. Copy the DefaultListenSharedAccessSignature connection string for this value.
    • Hub name: Name of your hub from the Azure portal. For example, mynotificationhub2.
  4. In the Solution Explorer window, right-click your project, select Add, and then select Class.

  5. Create a Constants.cs class for your Xamarin project and define the following constant values in the class. Replace the placeholders with your values.

    public static class Constants
    {
        public const string ListenConnectionString = "<Listen connection string>";
        public const string NotificationHubName = "<hub name>";
    }
    
  6. Add the following using statements to MainActivity.cs:

    using Android.Util;
    using Android.Gms.Common;
    
  7. Add the following properties to the MainActivity class. The TAG variable will be used to show an alert dialog when the app is running:

    public const string TAG = "MainActivity";
    internal static readonly string CHANNEL_ID = "my_notification_channel";
    
  8. Add the following method to the MainActivity class. It checks whether Google Play Services are available on the device.

    public bool IsPlayServicesAvailable()
    {
        int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.Success)
        {
            if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
                Log.Debug(TAG, GoogleApiAvailability.Instance.GetErrorString(resultCode));
            else
            {
                Log.Debug(TAG, "This device is not supported");
                Finish();
            }
            return false;
        }
    
        Log.Debug(TAG, "Google Play Services is available.");
        return true;
    }
    
  9. Add the following method to the MainActivity class that creates a notification channel.

    private void CreateNotificationChannel()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            // Notification channels are new in API 26 (and not a part of the
            // support library). There is no need to create a notification
            // channel on older versions of Android.
            return;
        }
    
        var channelName = CHANNEL_ID;
        var channelDescription = string.Empty;
        var channel = new NotificationChannel(CHANNEL_ID, channelName, NotificationImportance.Default)
        {
            Description = channelDescription
        };
    
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
    
  10. In MainActivity.cs, add the following code to OnCreate after base.OnCreate(savedInstanceState):

    if (Intent.Extras != null)
    {
        foreach (var key in Intent.Extras.KeySet())
        {
            if(key!=null)
            {
                var value = Intent.Extras.GetString(key);
                Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
            }
        }
    }
    
    IsPlayServicesAvailable();
    CreateNotificationChannel();
    
  11. Add a class named MyFirebaseMessagingService to your project.

  12. Add the following using statements to MyFirebaseMessagingService.cs.

    using Android.Util;
    using Firebase.Messaging;
    using Android.Support.V4.App;    
    using WindowsAzure.Messaging;
    
  13. Add the following above your class declaration, and have your class inherit from FirebaseMessagingService:

    [Service]
    [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
    [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
    public class MyFirebaseMessagingService : FirebaseMessagingService
    
  14. Add the following code to MyFirebaseMessagingService.cs to process messages that are received.

        const string TAG = "MyFirebaseMsgService";
        NotificationHub hub;
    
        public override void OnMessageReceived(RemoteMessage message)
        {
            Log.Debug(TAG, "From: " + message.From);
            if (message.GetNotification() != null)
            {
                //These is how most messages will be received
                Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
                SendNotification(message.GetNotification().Body);
            }
            else
            {
                //Only used for debugging payloads sent from the Azure portal
                SendNotification(message.Data.Values.First());
    
            }
        }
    
        void SendNotification(string messageBody)
        {
            var intent = new Intent(this, typeof(MainActivity));
            intent.AddFlags(ActivityFlags.ClearTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
    
            var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID);
    
            notificationBuilder.SetContentTitle("FCM Message")
                        .SetSmallIcon(Resource.Drawable.ic_launcher)
                        .SetContentText(messageBody)
                        .SetAutoCancel(true)
                        .SetShowWhen(false)
                        .SetContentIntent(pendingIntent);
    
            var notificationManager = NotificationManager.FromContext(this);
    
            notificationManager.Notify(0, notificationBuilder.Build());
        }
    
  15. Add the following methods to the MyFirebaseMessagingService class to receive the FCM registration token and send it to the Notification Hubs instance (hub).

        public override void OnNewToken(string token)
        {
            Log.Debug(TAG, "FCM token: " + token);
            SendRegistrationToServer(token);
        }
    
        void SendRegistrationToServer(string token)
        {
            // Register with Notification Hubs
            hub = new NotificationHub(Constants.NotificationHubName,
                                        Constants.ListenConnectionString, this);
    
            var tags = new List<string>() { };
            var regID = hub.Register(token, tags.ToArray()).RegistrationId;
    
            Log.Debug(TAG, $"Successful registration of ID {regID}");
        }
    
  16. Build your project.

  17. Run your app on your device or loaded emulator

Send test notification from the Azure portal

You can test receiving notifications in your app with the Test Send option in the Azure portal. It sends a test push notification to your device.

Azure portal - Test Send

Push notifications are normally sent in a back-end service like Mobile Services or ASP.NET through a compatible library. If a library isn't available for your back-end, you can also use the REST API directly to send notification messages.

Next steps

In this tutorial, you sent broadcast notifications to all your Android devices registered with the backend. To learn how to push notifications to specific Android devices, advance to the following tutorial: