Muokkaa

Jaa


Tutorial: Send push notifications to Xamarin.Android apps using Notification Hubs

Overview

Note

For information about Firebase Cloud Messaging deprecation and migration steps, see Google Firebase Cloud Messaging migration.

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. A screenshot showing select All Services for an existing namespace.

  3. Type Notification Hubs in the Filter services text box. Select the star icon next to the service name to add the service to the FAVORITES section on the left menu. Select Notification Hubs.

    A screenshot showing how to filter for notification hubs.

  4. On the Notification Hubs page, select Create on the toolbar.

    A screenshot showing how to create a new notification hub.

  5. In the Basics tab on the Notification Hub page, do the following steps:

    1. In Subscription, select the name of the Azure subscription you want to use, and then select an existing resource group, or create a new one.

    2. Enter a unique name for the new namespace in Namespace Details.

    3. A namespace contains one or more notification hubs, so type a name for the hub in Notification Hub Details.

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

      Screenshot showing notification hub details.

    5. Review the Availability Zones option. If you chose a region that has availability zones, the check box is selected by default. Availability Zones is a paid feature, so an additional fee is added to your tier.

    6. Choose a Disaster recovery option: None, Paired recovery region, or Flexible recovery region. If you choose Paired recovery region, the failover region is displayed. If you select Flexible recovery region, use the drop-down to choose from a list of recovery regions.

      Screenshot showing availability zone details.

    7. Select Create.

  6. When the deployment is complete select Go to resource.

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.

    Screenshot of Notification Hub in Azure Portal with Google G C M F C M option highlighted and outlined in red.

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.

    Screenshot that highlights the Blank App template.

  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 10.0 by following these steps:

    1. Right-click your project, and select Properties.
    2. For the Compile using Android version: (Target framework) field, select Android 10.0.
    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. If you're migrating from Google Cloud Messaging to Firebase, your project's AndroidManifest.xml file might contain an outdated GCM configuration, which may cause notification duplication. Edit the file and remove the following lines inside the <application> section, if present:

    <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 WindowsAzure.Messaging.NotificationHubs;
    
  7. Add the following properties to the MainActivity class:

    internal static readonly string CHANNEL_ID = "my_notification_channel";
    
    
  8. In MainActivity.cs, add the following code to OnCreate after base.OnCreate(savedInstanceState):

    // Listen for push notifications
    NotificationHub.SetListener(new AzureListener());
    
    // Start the SDK
    NotificationHub.Start(this.Application, HubName, ConnectionString);
    
  9. Add a class named AzureListener to your project.

  10. Add the following using statements to AzureListener.cs.

    using Android.Content;
    using WindowsAzure.Messaging.NotificationHubs;
    
  11. Add the following above your class declaration, and have your class inherit from Java.Lang.Object and implement the INotificationListener:

    public class AzureListener : Java.Lang.Object, INotificationListener
    
  12. Add the following code inside AzureListener class, to process messages that are received.

        public void OnPushNotificationReceived(Context context, INotificationMessage message)
        {
            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(message.Title)
                        .SetSmallIcon(Resource.Drawable.ic_launcher)
                        .SetContentText(message.Body)
                        .SetAutoCancel(true)
                        .SetShowWhen(false)
                        .SetContentIntent(pendingIntent);
    
            var notificationManager = NotificationManager.FromContext(this);
    
            notificationManager.Notify(0, notificationBuilder.Build());
        }
    
  13. Build your project.

  14. 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: