How To: Azure Notification Hubs (Android Apps)

Microsoft Azure Notification Hubs enable you to send device push notifications through third-party application platforms, including the following:

  • Windows Push Notification Services (WNS) for Windows 8.

  • Microsoft Push Notification Service (MPNS) for Windows Phone.

  • Apple Push Notification service (APNs).

  • Google Cloud Messaging (GCM).

This guide describes how to perform the tasks required to implement a complete solution that uses notification hubs:

  • Create and configure a notification hub.

  • Set up an Android app that registers to receive push notifications.

  • Set up a .NET back-end service to push notifications through WNS.

  • Use advanced features (template registrations, tag-level security).

Note

Getting started with Notification Hubs provides more detailed step-by-step instructions on how to broadcast push notifications to an Android application. Also, the Azure Service Bus Notification Hubs topic provides high-level explanations of major features as well as architectural guidance.

Prerequisites

In order to perform the tasks explained in this tutorial, you must have the following:

  • Service Bus .NET SDK.

  • Android SDK (optionally Eclipse), which you can download from here.

  • Android Notification Hub SDK. You can download this SDK from here.

Notification Hub Main Concepts

A notification hub is a Service Bus entity that enables you to send push notifications to devices through platform-native notification systems. Each notification hub contains the credentials that are required to connect to the push notification services (PNS) and send push notifications to a specific app.

A notification hub contains one credential for each supported platform. This level of security enables the hub to send push notifications to a single app for each platform (in case of APNs, only to one of the environments, SandboxProduction). Also, a notification hub provides a context for security.

At a high level, notification hubs are used as follows:

  1. A notification hub is provisioned with credentials for at least one platform.

  2. A registration is created on the notification hub (eventually associated to a set of tags).

  3. A message that contains the notification content is sent to the notification hub. The message can be labeled with a tag.

  4. The notification hub pushes the notification content to all registrations with the specified tag.

While notification hubs provide a security context and are closely related to the app, registrations associate platform-specific handles (for example, tokens for APNs, ChannelURIs for WNS) to tags. Tags provide a way to target specific sets of devices/handles. For more high-level information, see Azure Service Bus Notification Hubs.

Create and configure a Notification Hub

This section creates and configures a notification hub with your WNS credentials.

Create a Google API project

Complete the first three sections on the Getting Started With GCM page (up to Obtaining an API Key). After completing these steps, you should have a project ID and an API key, which you use later to configure your application and your notification hub.

Create a Namespace

A Service Bus namespace can contain multiple entities (queues, topics, relays, and notification hubs), and provides a root security context. You can create namespaces on the . Once a namespace is created, entities can be created, updated, and deleted programmatically using the .NET Service Bus SDK (listed in the “Prerequisites” section).

Create and configure a Notification Hub

Using the , you can create a notification hub and configure it to send push notifications to a Windows Store application.

  1. Log on to the (https://manage.windowsazure.com/)

  2. In the bottom-left corner, click New.

  3. Click App Services, and then click Service Bus Notification Hub, then Quick Create.

  4. Select a name for the notification hub, a region, and the namespace in which this notification hub will be created (if there are no namespaces available, a new one with the desired name is provisioned).

    Use Quick Create to create a hub

  5. Click the label Create a new Notification Hub at the bottom right of the screen.

  6. Now, in the Service Bus tab on the left navigation pane, click the created namespace. The notification hub should appear in the list.

    New hub created in the Azure Portal

  7. Click the notification hub, and then click the Configure tab on the top.

    Notification Configure Hub for Android

  8. Insert the API key obtained earlier, and then click Save in the bottom toolbar.

Client Application

This section describes how to register to a notification hub from your client app. It is assumed that you are using Eclipse with the Android Development Tools to develop your client application.

Configure your client app to use GCM

In order to use GCM, you must target Google APIs (at least API level 8), instead of plain Android. You must also download (using Android SDK Manager) and import the following APIs in the Eclipse libs folder:

  • Google Cloud Messaging for Android library.

  • Google Play Services.

A step-by-step guide is available in the Getting started with Notification Hubs section.

Configure your client application to use a Notification Hub

First, add a reference to the Notification Hubs Android SDK:

  1. Download the following .zip file: Azure Android SDK.

  2. Copy the file notificationhubs/notification-hub-x.x.jar into the \libs folder of your Eclipse Android project.

  3. In the AndroidManifest.xml, add the following line of code just below the <uses-sdk/> element. Make sure to replace the placeholder with the app package.

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <uses-permission android:name="android.permission.WAKE_LOCK"/>
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    
    <permission android:name="<your package>.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="<your package>.permission.C2D_MESSAGE"/>
    
  4. In the main activity (usually MainActivity.java), add the following private members. Make sure to replace the placeholder with the project id you obtained from the Google API console.

    private String SENDER_ID = "<your project number>";
    private GoogleCloudMessaging gcm;
    private NotificationHub hub;
    
  5. From the , obtain the connection string with listen access by navigating to your notification hub dashboard and clicking Connection Information:

    Portal

  6. In the OnCreate method, add the following code. Make sure to replace the placeholders with your connection string with listen access obtained in the previous step, and the name of your notification hub.

    gcm = GoogleCloudMessaging.getInstance(this);
    
    String connectionString = "<your listen access connection string>";
    hub = new NotificationHub("<your notification hub name>", connectionString, this);
    

Note

In the preceding code, Service Bus credentials are embedded in your client app code. Note that embedding credentials in the app removes the ability to secure registration to specific tags. To understand and implement the correct approach for your app, see the “Security” section of the Azure Service Bus Notification Hubs topic.

Register for Native Notifications

One way to send push notifications is to have the backend specify the platform-specific payload of the notification, called native notifications. Your client app registers for native notifications by creating a native registration in the notification hub. This approach makes your client app responsible only for creating this registration in the notification hub, and keeping it up-to-date with the latest registrationId and tags. The benefits of this approach are a simple client-side configuration, and full control of the format of the notifications in the backend. The disadvantages are the need to create and send multiple platform-specific payloads from your back-end app, and a more complex implementation of per-user personalization of notifications. For more information about native vs. template registrations, see Azure Service Bus Notification Hubs.

The following code registers the provided registrationId for native notifications:

hub.register(regid, "myTag");

To make sure that the notification hub has the latest registrationId and tags (tags are optional), this function call is synchronous and should be called every time the app starts. At a low level, it creates or updates a registration for this device with the provided registrationId and set of tags.

Usually the preceding code is called right after obtaining the registrationId from GCM. As this simple example shows, in your main activity you call the following method from OnCreate:

@SuppressWarnings("unchecked")
private void registerWithNotificationHubs() {
   new AsyncTask() {
      @Override
      protected Object doInBackground(Object... params) {
         try {
            String regid = gcm.register(SENDER_ID);
            hub.register(regid, "myTag");
         } catch (Exception e) {
            return e;
         }
         return null;
     }
   }.execute(null, null, null);
}

To unregister from native registrations, issue the following call:

hub.unregister();

Register for Template Notifications

The previous section explained the advantages and disadvantages of using native registrations. Template registrations specify a template in order to convert platform-agnostic notifications into a platform-specific personalized notification. Your client app can opt to use template registrations instead, or in addition to, native registrations. Using template registrations, you can move the platform-specific part of push notifications from the app backend to the client app. The main advantages of this approach are a platform-agnostic back-end code, and the possibility of per-user personalization. The disadvantage is that changing the platform-specific payload of a notification requires updating the registration. Usually template registrations are a good fit for notifications that have always the same format and target multiple platforms. For more information about native vs. template registrations, see Azure Service Bus Notification Hubs.

Templates. A template is a string that represents the body of the notification you want to send to the device. The template refers to properties in the incoming message with a simple expression language. For example:

{
"data": {
"msg": "$(property1)"
}
}

Note the use of the expression $(property1).

When the backend sends a message that reaches this registration with a property called property1 with value value; for example, with the code snippet shown in the section “Send a Template Notification,” Service Bus sends a push notification that contains value instead of the expression, as shown here:

{
"data": {
"msg": "value"
}
}

A client can create a template registration with the following code:

String template = "{\"data\":{\"msg\":\"$(property1)\"}}";
hub.registerTemplate(regId, "myTemplate", template);hub.registerTemplate

Note that the method to create a template registration takes a registration name parameter (myTemplate in this code). This process enables a single client app to create multiple templates, each with different sets of tags.

To delete a registration for a template, issue the following call:

hub.unregisterTemplate("myTemplate");

Expression Language. The following table shows the language allowed in templates.

Expression Description

$(prop)

Reference to an event property with the given name. Property names are not case-sensitive. This expression resolves to the property’s text value or to an empty string if the property is not present.

$(prop, n)

As above, but the text is explicitly clipped at n characters. For example, $(title, 20) clips the contents of the title property at 20 characters.

.(prop, n)

As above, but the text is suffixed with three dots as it is clipped. The total size of the clipped string and the suffix does not exceed n characters. .(title, 20) with an input property of “This is the title line” results in This is the title….

%(prop)

Similar to $(name), except that the output is URI encoded.

#(prop)

Used in JSON templates.

This function works the same as $(prop) specified above, except when used in JSON templates (such as Apple templates). In this case, if this function:

  • is not surrounded by ‘{‘,’}’ (e.g. ‘myJsonProperty’ : ‘#(name)’), and

  • it evaluates to a number in Javascript format, i.e. regexp: (0|([1-9][0-9]*))(\.[0-9]+)?((e|E)(+|-)?[0-9]+)?,

then the output JSON is a number.

For example, ‘myJsonProperty’ : ‘#(name)’ becomes ‘myJsonProperty’ : 40 (and not ‘40‘).

‘text’ or “text”

A literal. Literals contain arbitrary text enclosed in single or double quotes.

expr1 + expr2*

The concatenation operator that joins two expressions into a single string.

The expressions can be any of the preceding.

When using concatenation, the entire expression must be surrounded with {}, e.g. {$(prop) + ‘ - ’ + $(prop2)}.

Application Back-end

In order to send push notifications, your app backend must connect to a notification hub.

Configure your app back-end to use a Notification Hub

To access notification hubs, download the Service Bus NuGet package:

  1. Open your back-end app project in Visual Studio.

  2. In Solution Explorer, right-click References, and select Manage NuGet packages. Search for Azure, and install the package called Azure Service Bus.

  3. At the top of any C# file in which you want to use notification hubs, add the following using statements:

using System.Runtime.Serialization;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.ServiceBus.Notifications;

Send a GCM native notification from your app backend

Make sure that your client application is correctly set up to create a native registration as explained in the section “Register for Native Notifications.” In order to send a push notification, your app backend contacts the notification hub you created.

var hubClient = NotificationHubClient.CreateClientFromConnectionString(<connection string>, "<notification hub path>");
hubClient.SendGcmNativeNotification("{ \"data\" : {\"msg\":\"Hello from Azure!\"}}");

Obtain the connection string with full access from the . Navigate to the dashboard of your notification hub and click Connection Information.

Portal

This code sends a notification to all GCM registrations. In order to target a specific set, one overload of the Send method takes a tag parameter.

hubClient.SendGcmNativeNotification(notificationBody, "destinationTag");

For more information about how to use tags in your application, see Azure Service Bus Notification Hubs.

Send a Template Notification

Make sure that your client app is correctly set up to create a template registration as explained in the section “Register for Template Notifications.” In order to send a registration to template registrations, your app backend sends a platform-agnostic message that contains a dictionary of properties. The required properties depend on the templates used in the registrations.

IDictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("property1", "value");
hubClient.SendTemplateNotification(properties, "destinationTag");

Advanced Topics

This section describes the features required for advanced scenarios, using notification hubs.

Registration management from your app backend

The Service Bus .NET SDK provides methods to create, update, and delete registrations from your app backend. These methods require your client app to pass the GCM registrationId to the backend explicitly. The backend is then responsible for refreshing all registrations with the current token.

The Notify users with Notification Hubs topic is a complete scenario tutorial that shows how to perform registrations from your app back-end.

The main difference between managing registrations in the client app and in the app back-end is in how you refer to specific registrations. In the client app, you always refer to the registrations of the current device. On the app back-end, you can retrieve registrations based on the registrationId property (note that this value is different from the registrationId obtained from GCM), and tags. Every registration has a registrationId that uniquely identifies it. You can retrieve the registrationId when you create it. For example:

var r = hubClient.CreateGcmNativeRegistration("<GCM registrationId>", new string[] {"tag"});
string registrationId = r.RegistrationId;

You can then retrieve and update a registration by using its registrationId, as in this example:

var r = hubClient.GetRegistration<GcmRegistrationDescription>(registrationId);
r.Tags.Add("newTag");
hubClient.UpdateRegistration(r);

Another option is to refer to registrations by tag. This method is especially useful when using tags as installation ids or user IDs. The following code retrieves all registrations tagged with the tag userId:Alice.

var registrations = hubClient.GetRegistrationsByTag("userId:Alice", 0, 100);

Note that you must provide skip and count parameters, and you might have to make sure that you only retrieve the expected number of registrations.

Refresh RegistrationIds. As with registration management from the client, you must make sure that the GCM registrationIds in registrations are up-to-date. To ensure this, update registrations one by one, as in the following code.

var r = hubClient.GetRegistration<GcmRegistrationDescription>(registrationId);
r.GcmRegistrationId = newGCMRegistrationId;
hubClient.UpdateRegistration(r);

When the registration management is completed in your app back-end, no reference to notification hubs has to be present in your client app: your app backend has full responsibility for creating the registrations for the clients and keeping them updated.

Note

Registrations automatically expire if not regularly updated (the expiration time is reported in the and in the registration itself when retrieved programmatically).