Architecture & DesignHow To Implement Azure Push Notifications in Android Apps

How To Implement Azure Push Notifications in Android Apps

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

Notifications are a very integral part of any mobile application. In the mobile world, we term them push notifications, when any message is sent from the server to the app; the message is displayed even when the app is not open. In this article, we will walk through the steps to integrate an Android App with the Azure notification service. Because notifications are platform specific, in this article, we will look at the steps specific to Android.

Description

To begin with, the first step is to do the configurations in Google Cloud.

Configure GCM

This can be done in two ways:

On Google Cloud Platform

  1. Navigate to Google Cloud and create a new project.
  2. Once the project is created, click the menu icon on the left, expand the “API Manager” menu, and click “Credentials,” as shown in Figure 1:

    Expanding the API manager
    Figure 1: Expanding the API manager

  3. On the credentials page, we need the API Server Key to complete the configuration on Azure portal. Copy the key and save it in Notepad.

    Obtaining the API Server Key
    Figure 2: Obtaining the API Server Key

  4. Click the Home button again and, on the dashboard, click Project” → “Manage Project Settings.”

    Clicking "Project" → "Manage Project Settings"
    Figure 3: Clicking “Project” → “Manage Project Settings”

  5. On the ‘Project Settings’ page, copy the Project Number and save it in Notepad.

    Copying the Project Number
    Figure 4: Copying the Project Number

Using Firebase Console

  1. If you are using Firebase Console, create a project in Firebase Console.
  2. Click the gear icon and select Project Settings.

    Selecting the project settings
    Figure 5: Selecting the project settings

  3. On the project settings page, click the ‘Cloud Messaging’ tab.

    Clicking the 'Cloud Messaging' tab
    Figure 6: Clicking the ‘Cloud Messaging’ tab

  4. On the screen, there are two keys to integrate with Azure; we will use “Legacy server key.” Save the legacy server key and the sender ID in Notepad.
Note: A project created in Firebase or Google Console is visible on both sites.

Configure Azure

Once the project is created in Google Cloud, the next step is to integrate it on the Azure portal. Now, navigate to the Azure portal and create a ‘Notification Hub.’ Just follow these steps to do so:

  1. On the Azure portal, click the “+” in the left menu and search for “Notification Hub.” On the filtered list, click ‘Notification Hub,’ fill in the required information, and finish creating the ‘Notification Hub.’ For this example, we name our notification hub ‘DemoNotifications.’

    Naming the notification hub
    Figure 7: Naming the notification hub

  2. Once created, click “All Resources” and then ‘DemoNotifications’ → ‘Notification Services’ → GCM, as shown in Figure 8:

    Selecting GCM
    Figure 8: Selecting GCM

  3. Click “Google (GCM)” and paste the ‘legal server key’/’server key’ saved in the ‘Configure GCM’ section.

This completes the Azure configuration changes. The next step is to register the device to receive notifications.

In Xamarin Studio, create a new multi-platform Xamarin Forms project. Add the “Google Cloud Messaging Client” component under the components folder:

Adding the "Google Cloud Messaging Client" component
Figure 9: Adding the “Google Cloud Messaging Client” component

Add a class file named “DemoBroadcastReceiver.cs” and add the following code to it:

[BroadcastReceiver(Permission = Constants.PERMISSION_GCM_INTENTS)]
// Allow GCM on boot and when app is closed
[IntentFilter(new[] { Intent.ActionBootCompleted })]
[IntentFilter(new string[] { Constants.INTENT_FROM_GCM_MESSAGE },
Categories = new string[] { "<Package name>"})]
[IntentFilter(new string[]
   { Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
   Categories = new string[] { "<Package name>"})]
[IntentFilter(new string[]
   { Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
Categories = new string[] { "<Package name>" })]
public class DemoGcmBroadcastReceiver :
   GcmBroadcastReceiverBase<DemoGcmService>

{
   // The SENDER_ID is the project number/sender ID
   // from the Google Console/Firebase
   public static string[] SENDER_IDS = { "Sender ID" };
}

Set the value of the sender ID with the saved project number/sender ID in the ‘Configure GCM’ section. Replace ‘<Package name>’ with the app’s package name.

Add another class file, named ‘DemoGcmService.cs.’ This file has a prefix [Service] and is inherited from ‘GcmService.’ Add the following code to the class:

1. [Service]
   public class DemoGcmService : GcmServiceBase
   {
      static NotificationHub hub;
2.    public DemoGcmService() :
         base(DemoGcmBroadcastReceiver.SENDER_IDS)
      {
      }
3.    public static void Initialize(Context context)
      {
         var cs = "<Azure Listner End Point>";
         var hubName = "<Notification hub name>";
         // Azure notification
         hub = new NotificationHub(hubName, cs, context);
      }
4.    public static void Register(Context Context)
      {
         GcmClient.Register(Context,
            DemoGcmBroadcastReceiver.SENDER_IDS);
      }
5.    protected override void OnRegistered(Context context,
         string registrationId)
      {
         // Receive registration ID and register it on Azure
         if (hub != null)
            hub.Register(registrationId, "TEST");
      }
6.    protected override void OnUnRegistered(Context context,
         string registrationId)
      {
         if (hub != null)
         hub.Unregister();
      }
7.    protected override void OnMessage(Context context,
         Intent intent)
      {
         var notificationManager =
            GetSystemService(Context.NotificationService)
            as NotificationManager;
         var title = "hello";
         var desc = intent.Extras.GetString("message");

         var uiIntent = new Intent(this, typeof(MainActivity));
         PendingIntent intent1 = PendingIntent.GetActivity(this,
            0, uiIntent, PendingIntentFlags.CancelCurrent);
         Android.App.Notification.Builder builder = new
               Android.App.Notification.Builder(this)
            .SetContentTitle(title)
            .SetContentText(desc)
            .SetFullScreenIntent(intent1, true)
            .SetAutoCancel(true)
            .SetSmallIcon(Android.Resource.Drawable
               .SymActionEmail);

         // Build the notification:
         Android.App.Notification notification =
            builder.Build();

         notification.Defaults = NotificationDefaults.All;

         // Publish the notification:
         const int notificationId = 0;
         notificationManager.Notify(notificationId,
            notification);

      }
8.    protected override bool OnRecoverableError(Context context,
         string errorId)
      {
         // On Recoverable Error
         return true;
      }
9.    protected override void OnError(Context context,
         string errorId)
      {
         // On Error
      }
}   // End of class

Let’s walk through the code. Line 1 prefixes the class as a [service] and is a required step. Stub 2 defines a constructor where we pass the sender’s ID—the project number created in Google Console. In Stub 3, we create an instance of the Azure notification hub. To get the connection string for the Notification hub, navigate to Azure Portal → ‘All Resources’ →. Click the notification hub that was created earlier. On the Notification hub, click ‘Access Policies.’ (see Figure 10)

Showing 'Access Policies'
Figure 10: Showing ‘Access Policies’

Copy the connection string with ‘Listen’ permissions to replace the connection string placeholder in Stub 3. Replace the ‘Notification hub name’ with the name of the Notification hub created in Azure. Step 4 registers the current context with the GCM component. Once Step 4 is completed successfully, it executes Step 5 to register the device with Azure. Step 6 is called when the user doesn’t want to receive the notifications.

Step 7 is an important step; it’s called when a message is received. It creates an instance of the notification manager, which is responsible for displaying the message on the UI. In this example, the schema of the message received is:

{"data":{"message":"Notification Hub test notification"}}

So, the line

var desc = intent.Extras.GetString("message");

gets the body of the message. Next, we create an Intent and pass the Intent to the notification builder with the message. Then, create a notification object using the notification builder and pass the notification object to the notification manager to display the message. The message finally displayed to the user is shown in Figure 11:

The final user notification
Figure 11: The final user notification

To test this, navigate to the notification hub created in Azure and click ‘Test Send,’

Preparing to click 'Test Send'
Figure 12: Preparing to click ‘Test Send’

Select the platform as ‘Android’ and click Send.

Summary

In this article, we went through the steps to configure the GCM with Azure and the App level changes to enable push notification. With Azure notification, the configuration and implementation have become simpler. Step 7, where we create an Intent, can be further extended to have a custom view to display rich notifications.

Reference

Sending Push Notifications from Azure Mobile Apps

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories