Setup Push Notifications with Firebase in Xamarin Forms for Android

Use Google Firebase to send and receive push notifications in your Xamarin Forms Android project. ### Register the app in Google Firebase In order to setup push notifications in Xamarin Forms for Android first you have to register your app in Google Firebase.

  • Go to firebase.google.com
  • Click on Get Started
  • Click on Add Project
  • Enter the Project Name, Project Id (Android package name)
  • Compile all required informations, if required use these commands to generate the SHA1 fingerprint of the keystore (commands shown for Visual Studio for Mac version)
  • When required download the google-services.json file and add to the .Droid (or .Android) project in Visual Studio. In Visual Studio right click on the file and set it to Build Action > GoogleServicesJson. This file contains all the informations for the app to connect to the Google service.

And now some code

Add the nuget Xamarin.Firebase.Messaging to the project.

You first have to connect to Firebase, check the presence of the GooglePlayServices, and connect to a firebase topic (topics are channels of communications in order to send global push notifications to all the devices that listen to a channel), the default topic is all (on topics).

Inside the OnCreate method of MainActivity setup a code like this:

After that you have to register a FirebaseMessagingService subclass in order to receive push notifications.

Additionally i provided the SendNotification method that shows up a local push notification with the content of the received push from Firebase. Also you can handle the notification back to the Xamarin Forms app you can send a Xamarin Forms Message and register a listener inside the Xamarin Forms app (on Xamarin Forms Messaging Center)

[Service]
[IntentFilter(new[] {"com.google.firebase.MESSAGING_EVENT"})]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
    public static readonly string CHANNEL_ID = "my_notification_channel";
    //internal static readonly int NOTIFICATION_ID = 100;

    const string TAG = "MyFirebaseMsgService";

    public override void OnMessageReceived(RemoteMessage message)
    {
        var body = message.GetNotification().Body;
        var title = message.GetNotification().Title;

        Device.BeginInvokeOnMainThread(() => { SendNotification(title, body, message.Data); });
    }

    AtomicInteger atomicInteger = new AtomicInteger(0);

    void SendNotification(string messageTitle, string messageBody, IDictionary<string, string> data)
    {
        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);
        foreach (var key in data.Keys)
        {
            intent.PutExtra(key, data[key]);
        }

        var notificationId = atomicInteger.IncrementAndGet();

        var pendingIntent = PendingIntent.GetActivity(this, notificationId, intent, PendingIntentFlags.OneShot);

        // new versions of Android require a special icon with 
        // white pixels on a transparent backdrop
        // to be shown in status bar
        // https://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar#icon11
        var notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                                  .SetSmallIcon(Resource.Drawable.logo_statusbar)
                                  .SetContentTitle(messageTitle)
                                  .SetContentText(messageBody)
                                  .SetAutoCancel(true)
                                  .SetContentIntent(pendingIntent);

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(notificationId, notificationBuilder.Build());


        // optionally you can send a Xamarin Forms message to 
        // inform the Xamarin Forms Application to handle the notification
        MessagingCenter.Send(new MessageNotificationReceived()
        {
            Title = messageTitle,
            Message = messageBody,
        }, "");
    }


}

Finally as an optional you can register a single device token to send your push to a single device (on send on a single device). You do this by setting up a FirebaseInstanceIdService.

Test it

Firebase is great and can also let you to test the push with the web interface. Simply run your application and go to - console.firebase.google.com - select your project - inside the menu on Expand > Cloud Messaging and click on Send your first message