Get started with Azure Notification Hubs for Android apps and Firebase Cloud Messaging



This article demonstrates push notifications with Google Firebase Cloud Messaging (FCM). If you are still using Google Cloud Messaging (GCM), see Sending push notifications to Android with Azure Notification Hubs and GCM.

This tutorial shows you how to use Azure Notification Hubs and Firebase Cloud Messaging to send push notifications to an Android application. In this tutorial, you create a blank Android app that receives push notifications by using Firebase Cloud Messaging (FCM).

The goal of this article is to help you get started using Azure Notification Hubs as quickly as possible. The article presents a very simple broadcast scenario that focuses on the basic concepts of Notification Hubs.

If you are already familiar with Notification Hubs, you might want to select another topic from the left navigation or go to the relevant articles in the "Next steps" section.

We take your feedback seriously. If you have any difficulty completing this topic, or if you have recommendations for improving this content, we invite you to provide feedback at the end of the article.

The completed code for this tutorial can be downloaded from GitHub here.



To complete this tutorial, you must have an active Azure account. If you don't have an account, you can create a free trial account in just a couple of minutes. For details, see Azure Free Trial.

  • In addition to an active Azure account mentioned above, this tutorial requires the latest version of Android Studio.
  • Android 2.3 or higher for Firebase Cloud Messaging.
  • Google Repository revision 27 or higher is required for Firebase Cloud Messaging.
  • Google Play Services 9.0.2 or higher for Firebase Cloud Messaging.
  • Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Android apps.

Create a new Android Studio Project

  1. In Android Studio, start a new Android Studio project.

    Android Studio - new project

  2. Choose the Phone and Tablet form factor and the Minimum SDK that you want to support. Then click Next.

    Android Studio - project creation workflow

  3. Choose Empty Activity for the main activity, click Next, and then click Finish.

Create a project that supports 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. Then follow the instructions that are provided.

    Add Firebase to your Android app

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

    Select Project Settings

  4. Select the General tab in your project settings. Then download the google-services.json file that contains the Server API key and Client ID.
  5. Select the Cloud Messaging tab in your project settings, and then copy the value of the Legacy server key. You use this value to configure the notification hub access policy.

Configure a new notification hub

  1. Sign in to the Azure portal.

  2. Select Create a resource > Web + Mobile > Notification Hub.

    Azure portal - create a notification hub

  3. In the Notification Hub box, type a unique name. Select your Region, Subscription, and Resource Group (if you have one already).

    If you don't already have a service bus namespace, you can use the default name, which is created based on the hub name (if the namespace name is available).

    If you already have a service bus namespace that you want to create the hub in, follow these steps

    a. In the Namespace area, select the Select Existing link.

    b. Select Create.

    Azure portal - set notification hub properties

  4. After you've created the namespace and notification hub, open it by selecting All resources and then select the created notification hub from the list.

    Azure portal - notification hub portal page

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


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

    Azure portal - notification hub connection strings

  6. Under Notification Services select Google (GCM). Enter the FCM server key you copied earlier from the Firebase console and click Save.

  Azure Notification Hubs - Google (GCM)

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

Connect your app to the notification hub

Add Google Play services to the project

  1. Open the Android SDK Manager by clicking the icon on the toolbar of Android Studio or by clicking Tools -> Android -> SDK Manager on the menu. Locate the target version of the Android SDK that is used in your project, open it by clicking Show Package Details, and choose Google APIs, if it is not already installed.
  2. Click the SDK Tools tab. If you haven't already installed Google Play Service, click Google Play Services as shown below. Then click Apply to install.

    Note the SDK path, for use in a later step.

  3. Open the build.gradle file in the app directory.

  4. Add this line under dependencies:

        compile ''
  5. Click the Sync Project with Gradle Files icon in the tool bar.
  6. Open AndroidManifest.xml and add this tag to the application tag.

    <meta-data android:name=""
            android:value="@integer/google_play_services_version" />

Adding Azure Notification Hubs libraries

  1. In the Build.Gradle file for the app, add the following lines in the dependencies section.

        compile ''
        compile ''
  2. Add the following repository after the dependencies section.

        repositories {
            maven {
                url ""

Updating the AndroidManifest.xml.

  1. To support FCM, you must implement an Instance ID listener service in your code, which is used to obtain registration tokens using Google's FirebaseInstanceId API. In this tutorial, the name of the class is MyInstanceIDService.

    Add the following service definition to the AndroidManifest.xml file, inside the <application> tag.

        <service android:name=".MyInstanceIDService">
                <action android:name=""/>
  2. Once you have received your FCM registration token from the FirebaseInstanceId API, you will use it to register with the Azure Notification Hub. You will support this registration in the background using an IntentService named RegistrationIntentService. This service will also be responsible for refreshing your FCM registration token.

    Add the following service definition to the AndroidManifest.xml file, inside the <application> tag.

  3. You need to also define a receiver to receive notifications. Add the following receiver definition to the AndroidManifest.xml file, inside the <application> tag. Replace the <your package> placeholder with your actual package name shown at the top of the AndroidManifest.xml file.

        <receiver android:name=""
                <action android:name="" />
                <category android:name="<your package name>" />
  4. Add the following necessary FCM-related permissions below the </application> tag. Make sure to replace <your package> with the package name shown at the top of the AndroidManifest.xml file.

    For more information on these permissions, see Setup a GCM Client app for Android and Migrate a GCM Client App for Android to Firebase Cloud Messaging.

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
        <uses-permission android:name="" />

Adding code

  1. In the Project View, expand app > src > main > java. Right-click your package folder under java, click New, and then click Java Class. Add a new class named NotificationSettings.

    Android Studio - new Java class

    Make sure to update these three placeholders in the following code for the NotificationSettings class:

    • SenderId: The Sender ID you obtained earlier in the Cloud Messaging tab of your project settings in the Firebase console.
    • HubListenConnectionString: The DefaultListenAccessSignature connection string for your hub. You can copy that connection string by clicking Access Policies in your hub on the Azure portal.
    • HubName: Use the name of your notification hub that appears in the hub blade in the Azure portal.

      NotificationSettings code:

        public class NotificationSettings {
            public static String SenderId = "<Your project number>";
            public static String HubName = "<Your HubName>";
            public static String HubListenConnectionString = "<Enter your DefaultListenSharedAccessSignature connection string>";
  2. Using the steps preceding, add another new class named MyInstanceIDService. This is your Instance ID listener service implementation.

    The code for this class calls your IntentService to refresh the FCM token in the background.

        import android.content.Intent;
        import android.util.Log;
        public class MyInstanceIDService extends FirebaseInstanceIdService {
            private static final String TAG = "MyInstanceIDService";
            public void onTokenRefresh() {
                Log.d(TAG, "Refreshing GCM Registration Token");
                Intent intent = new Intent(this, RegistrationIntentService.class);
  3. Add another new class to your project named, RegistrationIntentService. This is the implementation for your IntentService that handles refreshing the FCM token and registering with the notification hub.

    Use the following code for this class.

        import android.content.Intent;
        import android.content.SharedPreferences;
        import android.preference.PreferenceManager;
        import android.util.Log;        
        public class RegistrationIntentService extends IntentService {
            private static final String TAG = "RegIntentService";
            private NotificationHub hub;
            public RegistrationIntentService() {
            protected void onHandleIntent(Intent intent) {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                String resultString = null;
                String regID = null;
                String storedToken = null;
                try {
                    String FCM_token = FirebaseInstanceId.getInstance().getToken();
                    Log.d(TAG, "FCM Registration Token: " + FCM_token);
                    // Storing the registration ID that indicates whether the generated token has been
                    // sent to your server. If it is not stored, send the token to your server,
                    // otherwise your server should have already received the token.
                    if (((regID=sharedPreferences.getString("registrationID", null)) == null)){
                        NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
                                NotificationSettings.HubListenConnectionString, this);
                        Log.d(TAG, "Attempting a new registration with NH using FCM token : " + FCM_token);
                        regID = hub.register(FCM_token).getRegistrationId();
                        // If you want to use tags...
                        // Refer to :
                        // regID = hub.register(token, "tag1,tag2").getRegistrationId();
                        resultString = "New NH Registration Successfully - RegId : " + regID;
                        Log.d(TAG, resultString);
                        sharedPreferences.edit().putString("registrationID", regID ).apply();
                        sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
                    // Check if the token may have been compromised and needs refreshing.
                    else if ((storedToken=sharedPreferences.getString("FCMtoken", "")) != FCM_token) {
                        NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
                                NotificationSettings.HubListenConnectionString, this);
                        Log.d(TAG, "NH Registration refreshing with token : " + FCM_token);
                        regID = hub.register(FCM_token).getRegistrationId();
                        // If you want to use tags...
                        // Refer to :
                        // regID = hub.register(token, "tag1,tag2").getRegistrationId();
                        resultString = "New NH Registration Successfully - RegId : " + regID;
                        Log.d(TAG, resultString);
                        sharedPreferences.edit().putString("registrationID", regID ).apply();
                        sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
                    else {
                        resultString = "Previously Registered Successfully - RegId : " + regID;
                } catch (Exception e) {
                    Log.e(TAG, resultString="Failed to complete registration", e);
                    // If an exception happens while fetching the new token or updating our registration data
                    // on a third-party server, this ensures that we'll attempt the update at a later time.
                // Notify UI that registration has completed.
                if (MainActivity.isVisible) {
  4. In your MainActivity class, add the following import statements above the class declaration.

        import android.content.Intent;
        import android.util.Log;
        import android.widget.TextView;
        import android.widget.Toast;
  5. Add the following private members at the top of the class. You use these to check the availability of Google Play Services as recommended by Google.

        public static MainActivity mainActivity;
        public static Boolean isVisible = false;    
        private static final String TAG = "MainActivity";
        private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
  6. In your MainActivity class, add the following method to the availability of Google Play Services.

        * Check the device to make sure it has the Google Play Services APK. If
        * it doesn't, display a dialog that allows users to download the APK from
        * the Google Play Store or enable it in the device's system settings.
        private boolean checkPlayServices() {
            GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
            int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
            if (resultCode != ConnectionResult.SUCCESS) {
                if (apiAvailability.isUserResolvableError(resultCode)) {
                    apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                } else {
                    Log.i(TAG, "This device is not supported by Google Play Services.");
                    ToastNotify("This device is not supported by Google Play Services.");
                return false;
            return true;
  7. In your MainActivity class, add the following code that checks for Google Play Services before calling your IntentService to get your FCM registration token and register with your notification hub.

        public void registerWithNotificationHubs()
            if (checkPlayServices()) {
                // Start IntentService to register this application with FCM.
                Intent intent = new Intent(this, RegistrationIntentService.class);
  8. In the OnCreate method of the MainActivity class, add the following code to start the registration process when activity is created.

        protected void onCreate(Bundle savedInstanceState) {
            mainActivity = this;
            NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, MyHandler.class);
  9. To verify app state and report status in your app, add these additional methods to the MainActivity.

        protected void onStart() {
            isVisible = true;
        protected void onPause() {
            isVisible = false;
        protected void onResume() {
            isVisible = true;
        protected void onStop() {
            isVisible = false;
        public void ToastNotify(final String notificationMessage) {
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity.this, notificationMessage, Toast.LENGTH_LONG).show();
                    TextView helloText = (TextView) findViewById(;
  10. The ToastNotify method uses the "Hello World" TextView control to report status and notifications persistently in the app. In your activity_main.xml layout, add the following ID for that control.

  11. Next you will add a subclass for your receiver you defined in the AndroidManifest.xml. Add another new class to your project named MyHandler.

  12. Add the following import statements at the top of

        import android.content.Context;
        import android.content.Intent;
        import android.os.Bundle;
  13. Add the following code for the MyHandler class making it a subclass of

    This code overrides the OnReceive method, so the handler reports notifications that are received. The handler also sends the push notification to the Android notification manager by using the sendNotification() method. The sendNotification() method should be executed when the app is not running and a notification is received.

        public class MyHandler extends NotificationsHandler {
            public static final int NOTIFICATION_ID = 1;
            private NotificationManager mNotificationManager;
            NotificationCompat.Builder builder;
            Context ctx;
            public void onReceive(Context context, Bundle bundle) {
                ctx = context;
                String nhMessage = bundle.getString("message");
                if (MainActivity.isVisible) {
            private void sendNotification(String msg) {
                Intent intent = new Intent(ctx, MainActivity.class);
                mNotificationManager = (NotificationManager)
                PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                        intent, PendingIntent.FLAG_ONE_SHOT);
                Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(ctx)
                                .setContentTitle("Notification Hub Demo")
                                .setStyle(new NotificationCompat.BigTextStyle()
  14. In Android Studio on the menu bar, click Build > Rebuild Project to make sure that no errors are present in your code.

  15. Run the app on your device and verify it registers successfully with the notification hub.


    Registration may fail on the initial launch until the onTokenRefresh() method of instance ID service is called. The refresh should initiate a successful registration with the notification hub.

Sending push notifications

You can test receiving push notifications in your app by sending them via the Azure portal - look for the Troubleshooting Section in the hub, as shown below.

Azure Notification Hubs - Test Send

Push notifications are normally sent in a back-end service like Mobile Apps or ASP.NET using a compatible library. If a library is not available for your back-end you can also use the REST API directly to send notification messages.

Here is a list of some other tutorials you may want to review for sending notifications:

Testing your app

Push notifications in the emulator

If you want to test push notifications inside an emulator, make sure that your emulator image supports the Google API level that you chose for your app. If your image doesn't support native Google APIs, you end up with the SERVICE_NOT_AVAILABLE exception.

In addition to the above, ensure that you have added your Google account to your running emulator under Settings > Accounts. Otherwise, your attempts to register with GCM may result in the AUTHENTICATION_FAILED exception.

Running the application

  1. Run the app and notice that the registration ID is reported for a successful registration.

    Testing on Android - Channel registration

  2. Enter a notification message to be sent to all Android devices that have registered with the hub.

    Testing on Android - sending a message

  3. Press Send Notification. Any devices that have the app running shows an AlertDialog instance with the push notification message. Devices that don't have the app running but were previously registered for push notifications receive a notification in the Android Notification Manager. Those can be viewed by swiping down from the upper-left corner.

    Testing on Android - notifications

Next steps

We recommend the Use Notification Hubs to push notifications to users tutorial as the next step. It demonstrates how to send notifications from an ASP.NET backend using tags to target specific users.

If you want to segment your users by interest groups, check out the Use Notification Hubs to send breaking news tutorial.

To learn more general information about Notification Hubs, see our Notification Hubs Guidance.