So I just implemented Push Notifications in awesome Xamarin.Forms … ;)

Backstory…

So about one month back my boss asked me to implement Push Notification support in one of the Xamarin cross platform based enterprise apps we were working on, which is fully implemented with Xamarin.Forms ! We had a Microsoft Azure Account purchased and dedicated for this certain project, which was a lucky point for me having worked with Azure Notification Hub before.

Praising Documentations…

Being all enthusiastic, I started by going through the official Microsoft Azure Documentation. It was very well documented, they had articles for Android, iOS, Windows Phone, Xamarin.iOS, Xamarin.Android and even Baidu. But unfortunately not for Xamarin.Forms, the ultimate cross platform awesomeness from Xamarin 😦 !

Capture1

Oh well that was most certainly a saddening moment… Actually it was said that there isn’t any proper library which supports Azure Push Notifications in pure Xamarin.Forms yet…

The decision time…

The requirement of my task was a bit simple, Send a push notification to the client’s mobile phone with some parameters and values in it, and when the user tap on the push notification, the app should open up and display any given information through the push notification.

So as the requirement sounded bit simple, I thought of implementing the Azure calls natively in Xamarin (such as Xamarin.Android and Xamarin.iOS project levels), rather than worrying about not being able to implement in PCL project code.

Of course I could have also used dependency injection in this case, but I didn’t have to go that far as my requirement was a bit simple.

Something tid bits to Consider…

Took me about a few days to figure out the whole implementation and get it to working properly. I gotta say the official Azure Notification Hub documentation by Microsoft was a great help, despite it didn’t give any support for Xamarin.Forms ! So I thought of sharing some of the code I had used during my implementation here, which I believe might be useful for you and better optimized than the documented ones. I won’t be explaining everything here as most of the steps are very well documented in the Microsoft Azure documentation, in order to avoid repetition…
Please keep in mind, if this is the first time you are implementing Azure Push Notifications in your Xamarin project, please refer to the official Microsoft Azure documentation first and then only come back here, otherwise it could be a bit confusing for some of you.

Prerequisites…

Before you get started, this is what you need to keep ready… 😉

Working Azure Account – We are going to use Azure Notification Hub as our Push Notification distribution server. Your GCM and APNs services will be connected to this and Azure will handle all the delivering the notifications through them.

Create an Azure Notification Hub service – If you haven’t created a Notification Hub yet please follow the easy steps through the Azure documentation. And also under that, you can check out how to enable the Push Notification in your Windows Phone App.

Working Google Cloud Messaging Service (GCM) – We need this in order to deliver our Push Notifications to the Android users . This will be connected this to our Azure Notification Hub. If you don’t have a GCM enabled, then head into the Azure documentation and follow the well explained steps. Trust me it only takes few minutes… Get started with Notification Hubs – Xamarin.Android

Working Apple Push Notification Service (APNs) authenticated app registration – We need this in order to connect the APNs to our Azure Hub, which will deliver the Push Notifications to the iPhone users.  In iPhone dev, you need to enable Push Notification services from the provisioning profiles of your app and regenerate them. You may refer to the Azure documentation, which is very well explained.. Get started with Notification Hubs – Xamarin.iOS

So all in all, please refer to the official Azure documentation, and get the basics Project setting up done as I haven’t mentioned every detail here to avoid repetition, and then refer to this documentation. 🙂

PCL Implementation…

So you wanna open the app and direct your user to a separate page in the app when the User taps on the Notification displayed on the device ? Then you could use the following sample code in your PCL shared project.

public class App : Application
{
   public App(String PushNotifParameter = null)
   {	   
	   if (PushNotifParam == null)
	   {
		   // The root page of your application
		   MainPage = new NavigationPage(new HomePage());
	   }
	   else
	   {
		   // For Android and WinPhone
		   // Process the Push Notification click....
		   MainPage = new PushNotifMessageDisplay(PushNotifParameter);
	   }
   }
}

 

As you have seen I added a parameter with a default null in the App() constructor, so that when the user taps on the Push notification on the phone, we can call the constructor with any given parameter, so we can determine whether to direct the user to the default home page or the push notification display page.
But keep in note this method only works for Android and Windows Phone, as in iOS you can’t catch the Push Notification message tap in the FinishedLaunching() method which is the executing point in Xamarin.iOS ! But not to worry, I have solved that issue as well, which I will show you in the iOS implementation section.

Here is the push notification display page. This is where the user will be directed when they click on the Push Notification displayed on the device.

public class PushNotifMessageDisplay : ContentPage
{
	public PushNotifMessageDisplay(String parameterValue)
	{
		Title = "Awesome App";

		Button btn_GobackToHome = new Button
		{
			Text = "Go back to Homepage",
			TextColor = Color.White,
			BackgroundColor = Color.FromHex("#FF3300"),
			BorderRadius = 0,
			BorderWidth = 0,
			BorderColor = Color.FromHex("#FF3300"),
			VerticalOptions = LayoutOptions.EndAndExpand,
			HorizontalOptions = LayoutOptions.FillAndExpand,
		};

		btn_GobackToHome.Clicked += (sender, args) =>
		{
			App.Current.MainPage = new NavigationPage(new HomePage());
		};

		Content = new StackLayout
		{
			VerticalOptions = LayoutOptions.FillAndExpand,
			HorizontalOptions = LayoutOptions.FillAndExpand,
			BackgroundColor = Color.White,
			Padding = new Thickness(10, 5, 10, 10),
			Children = {
				new Label {
					VerticalOptions = LayoutOptions.CenterAndExpand,
					HorizontalOptions = LayoutOptions.CenterAndExpand,
					XAlign = TextAlignment.Center,
					FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)),
					Text = "This is the Push Notification Message Display Page ! The paramaters from the Push Notification will be displayed here..." + "\n\n" + parameterValue,
				},
				btn_GobackToHome
			}
		};
	}
}

 

You may customize the above as anyway you wish to… 😉

Xamarin.Android Implementation…

Now lets move on to the Native implementation, please keep in mind, most of these native implementation code is much similar to the official document code. But I have improved them to perform better and cater for the exact requirement I was hoping to achieve…

Create a new class called ConstantsPushNotif and add the necessary information. Please make sure to insert your Google Cloud Messaging API information and Azure Notification Hub connection information. This class will hold all the necessary constant values for accessing GCM and Azure Notification Hub through our app.

class PushNotifications_Constants
{
	public const string SenderID = "xxxxxxxxxx"; // Google API Project Number

	// Azure app specific connection string and hub path
	public const string ConnectionString = "<Listen connection string>";
	public const string NotificationHubPath = "<hub name>";
}

 

Now some of you might get confused about those values above, so here is a small how-to guide. These constant values will be used in all three native platforms projects. Or else for your ease of use, you could define those values in your PCL class as public and refer to them when required from the native project code.

Azure Hub Path / Hub Name

Capture7

Azure Hub Listening connection string

how you get the Azure Hub Listening connection string,

Capture2

Google API Project Number

Wondering how to get the Google API Project Number ? Here it is..

Capture

We need to create a broadcast receiver for receiving Push Notifications, and below is the code I have used. Most of the below code was extracted from the Azure documentation, but some I had optimized, such as the Android Notification display section and please note that I have removed all the debug messages.

[assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
[assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
//GET_ACCOUNTS is only needed for android versions 4.0.3 and below
[assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
[assembly: UsesPermission(Name = "android.permission.INTERNET")]
[assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
namespace WhateverYourNamespace.Droid
{
    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY },
        Categories = new string[] { "@PACKAGE_NAME@" })]
    public class MyBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        public static string[] SENDER_IDS = new string[] { PushNotifications_Constants.SenderID };

        public const string TAG = "MyBroadcastReceiver-GCM";
    }

    [Service] // Must use the service tag
    public class PushHandlerService : GcmServiceBase
    {
        public static string RegistrationID { get; private set; }
        private NotificationHub Hub { get; set; }

        public PushHandlerService()
            : base(PushNotifications_Constants.SenderID)
        {
            
        }

        protected override void OnError(Context context, string errorId)
        {

        }

        protected override void OnMessage(Context context, Intent intent)
        {
            var msg = new StringBuilder();

            if (intent != null && intent.Extras != null)
            {
                foreach (var key in intent.Extras.KeySet())
                    msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
            }

            string messageText = intent.Extras.GetString("msg");
            string parameterText = intent.Extras.GetString("param");
            if (!string.IsNullOrEmpty(messageText))
            {
                CreateNotification("Awesome Notification...", messageText, parameterText);
                return;
            }

            // If the incoming message's parameters couldn't be recognized, then this Notification will be published...
            CreateNotification("Awesome Notification...", msg.ToString());
        }

        protected override void OnRegistered(Context context, string registrationId)
        {
            RegistrationID = registrationId;

            Hub = new NotificationHub(PushNotifications_Constants.NotificationHubPath, PushNotifications_Constants.ConnectionString, context);
            try
            {
                Hub.UnregisterAll(registrationId);
            }
            catch (Exception ex)
            {

            }

            var tags = new List<string>() { "falcons" }; // create tags if you want

            try
            {
                var hubRegistration = Hub.Register(registrationId, tags.ToArray());
            }
            catch (Exception ex)
            {
                
            }
        }

        protected override void OnUnRegistered(Context context, string registrationId)
        {
            
        }

        void CreateNotification(string title, string desc, string parameters = null)
        {
            Intent startupIntent = new Intent(this, typeof(MainActivity));

            startupIntent.PutExtra("param", parameters.ToString());

            TaskStackBuilder stackBuilder = TaskStackBuilder.Create(this);

            stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));

            stackBuilder.AddNextIntent(startupIntent);

            const int pendingIntentId = 0;
            PendingIntent pendingIntent =
                stackBuilder.GetPendingIntent(pendingIntentId, PendingIntentFlags.OneShot);

            Notification.Builder builder = new Notification.Builder(this)
                .SetContentIntent(pendingIntent)
                .SetContentTitle(title)
                .SetContentText(desc)
                .SetSmallIcon(Resource.Drawable.icon);

            // Build the notification:
            Notification notification = builder.Build();
            notification.Flags = NotificationFlags.AutoCancel;

            // Get the notification manager:
            NotificationManager notificationManager =
                GetSystemService(Context.NotificationService) as NotificationManager;

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

 

Parameter Passing through Push Notification..

Now as shown above you might have noticed a keyword calle “param”, and thats the parameter I’m planning passing pass through. We can pass any amount of parameters or values through Push Notifications, just gotta figure out the pattern to include it in the code for each specific platform. 😉
When you move ahead this article, you may see how I have handled the “param” value in three native platform code and as well as server side. I hope you would be able to take that as an example and add more parameters as you wish. 🙂

Now lets see the code for the MainActivity class of your Xamarin.Android project. There as you can see, inside the OnCreate() method I’m catching the parameter passed through the Intent, which will be passed in by the Push Notification alert message displayed in the phone. Based on that I’m redirecting the user to the home page or the separate Notification info display page.
And also every time the app starts up it will get registered withe GCM service for updating the notification token for the device.

namespace WhateverYourNamespace.Droid
{
    [Activity(Label = "WhateverYourNamespace", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);

            string parameterValue = this.Intent.GetStringExtra("param");      
            if (parameterValue != null)
            {
                LoadApplication(new App(parameterValue));
            }
            else
            {
                LoadApplication(new App());
            }


            RegisterWithGCM();
        }

        private void RegisterWithGCM()
        {
            // Check to ensure everything's setup right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);

            // Register for push notifications
            GcmClient.Register(this, PushNotifications_Constants.SenderID);
        }
    }
}

 

So let’s head into iOS implementation…

Xamarin.iOS Implementation…

Before you begin make sure you have enabled Push Notification Services in your App’s Provisioning Profiles… If you haven’t done it yet, as I mentioned earlier please follow the official Microsoft Azure Documentation for Xamarin.iOS  which explains very well step by step..

Here is how you could make sure… In the dev center, check the Services section under your app ID..

Capture5

And check your Provisioning Profile status…

Capture6

Don’t forget to re-download all your Provisioning profiles and install them in your iOS buld host through XCode !

So when it comes to the coding, first add the Constants class as we did in Xamarin.Android..

class PushNotifications_Constants
{
	// Azure app specific connection string and hub path
	public const string ConnectionString = "<Azure connection string>";
	public const string NotificationHubPath = "<Azure hub path>";
}

 

Then replace your AppDelegate code as following…

[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
	private SBNotificationHub Hub { get; set; }
			
	public override bool FinishedLaunching(UIApplication app, NSDictionary options)
	{
		if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
		{
			var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
							   UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
							   new NSSet());

			UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
			UIApplication.SharedApplication.RegisterForRemoteNotifications();
		}
		else
		{
			UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
			UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
		}

		global::Xamarin.Forms.Forms.Init();
		LoadApplication(new App());

		return base.FinishedLaunching(app, options);
	}

	public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
	{
		Hub = new SBNotificationHub(PushNotifications_Constants.ConnectionString, PushNotifications_Constants.NotificationHubPath);

		Hub.UnregisterAllAsync(deviceToken, (error) =>
		{
			if (error != null)
			{
				Console.WriteLine("Error calling Unregister: {0}", error.ToString());
				return;
			}

			NSSet tags = null; // create tags if you want
			Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
			{
				if (errorCallback != null)
					Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
			});
		});
	}

	public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
	{
		ProcessNotification(userInfo, false);
	}

	void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
	{
		// Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
		if (null != options && options.ContainsKey(new NSString("aps")))
		{
			//Get the aps dictionary
			NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

			string alertString = string.Empty;
			string paramString = string.Empty;

			if (aps.ContainsKey(new NSString("alert")))
				alertString = (aps[new NSString("alert")] as NSString).ToString();

			if (aps.ContainsKey(new NSString("param")))
				paramString = (aps[new NSString("param")] as NSString).ToString();

			if (!fromFinishedLaunching)
			{
				//Manually show an alert
				if (!string.IsNullOrEmpty(alertString))
				{
					UIAlertView avAlert = new UIAlertView("Awesome Notification", alertString , null, 
						NSBundle.MainBundle.LocalizedString("Cancel", "Cancel"),
						NSBundle.MainBundle.LocalizedString("OK", "OK"));

					avAlert.Clicked += (sender, buttonArgs) =>
					{
						if (buttonArgs.ButtonIndex != avAlert.CancelButtonIndex)
						{
							if (!string.IsNullOrEmpty(paramString))
							{
								App.Current.MainPage = new NavigationPage(new PushNotifMessageDisplay(paramString));
							}
						}
					};

					avAlert.Show();
				}
			}
		}
	}
}

 

As you can see above I have utilized the code whereas when ReceivedRemoteNotification() gets fired by receiving the push notification from APNs, a message will be displayed, and if the user selects ‘OK’ then the user will be redirected to the notification message display page. Or else if they click ‘Cancel’ the notification will be dismissed.

So let’s move on to Windows Phone implementation.

Xamarin.WinPhone Implementation…

I must admit that Windows Phone implementation was the easiest of all, Thanks to Microsoft’s direct support.

Before you start make sure that you have enabled Push Notifications permission in your WinPhone Project’s WMAppManifest configuration.

Capture8

First of all in your App class, replace the Application_Launching method as following…

private void Application_Launching(object sender, LaunchingEventArgs e)
{
	var channel = HttpNotificationChannel.Find("MyPushChannel");
	if (channel == null)
	{
		channel = new HttpNotificationChannel("MyPushChannel");
		channel.Open();
		channel.BindToShellToast();
	}

	channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
	{
		var hub = new NotificationHub("<Azure hub path>", "<Azure connection string>");
		await hub.RegisterNativeAsync(args.ChannelUri.ToString());
	});
}

 

Its actually pretty much the official documentation code. And below is how you should change your MainPage class whereas the native firing point of the native WinPhone execution…

public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage
{
	public MainPage()
	{
		InitializeComponent();
		SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;
	}
	
	protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
	{
		base.OnNavigatedTo(e);

		global::Xamarin.Forms.Forms.Init();
          
		if (NavigationContext.QueryString.ContainsKey("param"))
		{
			string strValue = this.NavigationContext.QueryString["param"];

			LoadApplication(new WhateverYourNamespace.App(strValue));
		}
		else 
		{
			LoadApplication(new WhateverYourNamespace.App());
		}
	}  
}

 

And that’s all for the Windows Phone…. TADAAAAA ! 😀
WAIT ! We are not done yet… Now that we have developed the Push Notification enabled client apps, how we are gonna send Push Notifications to them ? 😀

Push Notification Distribution Back-end

One way to send notifications to your Push Notifications enabled apps would be through the  Debug feature in Azure Notification Hub, which is a really great feature.
Simply navigate to the “Debug” tab in your notification hub, choose the platform, type the Push Notification message and finally hit send. Well based on the type of mobile platform it gives some extra features as well, give them a try if you are interested…

Capture9

PLOT TWIST ! 😀 Or you could create your own Push Notification Distribution server… 😉

Create your own Push Notification Distribution Back-end

For that you need a Azure Hub Full Access connection string, which might cause for some confusion for some of you as we have used the Listening Access string. This connection gives us the permission to send push messages through our Azure Notification Hub.

Azure Hub Full Access connection string…

Capture4

 

Now If you want to create you own dummy server, here is some well optimized code you could use by creating a simple .net Console Application, which I coded by myself when I was playing around for the first time…

class Program
{
	static void Main(string[] args)
	{
		String PushNotif_Message = "Hello World !";
		String PushNotif_Parameter = "THISISATESTPARAMETER";
		
		Console.WriteLine("Press any key to send the Android push Notifications...");
		SendNotification_Android_Async(PushNotif_Message, PushNotif_Parameter);
		Console.ReadLine();

		Console.WriteLine("Press any key to send the Windows Phone push Notifications...");
		SendNotification_WinPhone_Async(PushNotif_Message, PushNotif_Parameter);
		Console.ReadLine();

		Console.WriteLine("Press any key to send the iPhone push Notifications...");
		SendNotification_iOS_Async(PushNotif_Message, PushNotif_Parameter);
		Console.ReadLine();

		Console.WriteLine("Completed ! :)");
		Console.ReadLine();
	}

	public static async void SendNotification_Android_Async(String Message, String parameter)
	{
		try
		{
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
			String pushMessage = "{ \"data\" : {\"msg\":\"" + Message + "\",\"param\":\"" + parameter + "\"}}";
			NotificationOutcome result = await hub.SendGcmNativeNotificationAsync(pushMessage);

			Console.WriteLine(result.State.ToString());
		}
		catch (Exception ex)
		{

		}
	}

	private static async void SendNotification_WinPhone_Async(String Message, String parameter)
	{
		try
		{
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
			string toast = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
			  "<wp:Notification xmlns:wp=\"WPNotification\">" +
				 "<wp:Toast>" +
					  "<wp:Text1>" + Message + "</wp:Text1>" +
					  "<wp:Param>?param=" + parameter + "</wp:Param>" +
				 "</wp:Toast> " +
			  "</wp:Notification>";
			NotificationOutcome result = await hub.SendMpnsNativeNotificationAsync(toast);

			Console.WriteLine(result.State.ToString());
		}
		catch (Exception ex)
		{

		}
	}

	private static async void SendNotification_iOS_Async(String Message, String parameter)
	{
		try
		{
			NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");

			var alert = "{\"aps\":{\"alert\":\"" + Message + "\",\"param\":\"" + parameter + "\"}}";
			NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(alert);

			Console.WriteLine(result.State.ToString());
		}
		catch (Exception ex)
		{
			
		}
	}
}

 

Also you can see how I have attached parameter value to my push notifications, by adding the “param” variable as I explained at the beginning of this article. Likewise you can add any amount of parameters and pass through your Push Messages, but to keep in mind you have to handle those parameters properly in the Mobile app level as well… 🙂

AAAAND THATS IT !!!!!! 😀 Hit F5 and Send the Push Notifications as you wish ! 😉

but be cautious, there is a high possibility of you going crazy by sending random push notifications to your test devices when you try this out for the first time… lol 😀 (personal experience) 😉

Eh bunch of unexplained phenomena… O_o

Untitled-1

Yep that’s right, when I was playing around with Azure Notification Hub and Push Messages, I encountered a few anomalies or in other words a few unexplainable phenomena… 😛 lol don’t worry I ain’t talking about Aliens or Ghosts.. 😉

Incompatibility in Azure Messaging Components

When I followed the Azure documentation, I downloaded the Azure Messaging component for Xamarin (for Xamarin.Android and Xamarin.iOS) as it instructed. After I finished coding, the project compiled without any issue, but then when I deployed it and executed in the device, the app started crashing. Then I tried to debug the app and realized it was giving a runtime exception in both Xamarin.Android and Xamarin.iOS projects, when it initializes the Azure library.
After a while I found out its causing the runtime error due to this,
https://bugzilla.xamarin.com/show_bug.cgi?id=29466
System.MissingMethodException: Method not found: ‘Android.Runtime.JNIEnv.StartCreateInstance’
Frankly it’s because of some incompatibilities in the Message Component library version and Xamarin.Forms ! 😦

So I tried out an older version of the Azure Messaging component for Xamarin and it luckily worked. Therefore if you are not using the latest Xamarin version, I recommend you use this version for you Xamarin Azure Messaging Component library, http://components.xamarin.com/view/azure-messaging?version=1.1.5.3

🙂

Anomalies in Azure Notification Hub

Here is another weird situation I noted, after finishing the coding I tried to send my first set of push notifications through the command line client I built. But it wasn’t working, there were no compiling errors or any runtime errors also. But then just out of random I thought of sending a debug push message right from the Azure Hub, and suddenly it all started working fine.

So for the first time if the Push Notification you send from the Command Prompt client are not being delivered to your devices, then try sending a debug test push notification from the Notification Hub directly. It will work… this is pretty strange though, hope Microsoft will fix this soon. 🙂

When you follow the official documentation code…

If you are following the Azure Documentation code when creating your Push Notification distribution back-end client, make sure to await for the response from the SendNotificaitonAsync() method.
Otherwise right after calling the method you are probably closing the Command Prompt window before the action is actually completed asynchronously. This could also cause of unsuccessful message delivery from your client to the Azure Notification Hub. Create an instance of NotificationOutcome class and await for the result from the SendNotificationAsync() method, as I have done in my code in above example and below… 😉

NotificationOutcome result = await hub.SendAppleNativeNotificationAsync(alert);

Console.WriteLine("Result : " + result.State.ToString());

 

A Ghost activity in Google Cloud Messaging API…

So once I was doing some continuous testing Xamarin.Android with Push Notifications using Azure Notification Hub, and suddenly out of nowhere Push Notifications stopped working for Android. I sent several push notifications for Android but none of them got delivered for the test devices. I was wondering whether I was sending too many pushes and the server was rejecting my requests, but it was just about 2 or 3 pushers per hour as displayed in Azure Hub statistics. I tried sending a debug message from the Azure Notification Hub as well, but it didn’t work either.

Then I checked on my Google Cloud Console, and I saw that Android Cloud Message API has gotten disabled out of nowhere, which I had enabled way before. Then I enabled it, but still no luck. So just to take a shot in the dark, I regenerated  the Public access key in the GCM and re-added it to Azure Notification Hub, and BOOM ! it started working…

Looks like some kind of a bug in GCM API, so if you ever come across anything similar as above, try out the steps I took, might also work for you… 🙂

POST UPDATE 16/09/2015

Once again proving Microsoft has done a great job at their documentation, I found out this article, where it will guide you through all your troubles in NS related issues. Did you know you could view the actual status of the published notification message ? and you could view the registered devices right from Visual Studio ? Yep ! head into this link for any issues your having, it will surely help you as it did for me… 🙂

https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-diagnosing/

Conclusion

Well folks thats all about it… I must say the new Azure Notification Hub is a great way to be used for Push Notifications and its very easily manageable. Even though it is not yet directly supported for Xamarin.Forms, you can easily get around that issue by utilizing its support for Windows Phone and Xamarin overall as I have done… 😉

Through this article I didn’t want to spoon feed everything from the scratch because there is already a great documentation out there by Microsoft (kudos to that), just wanted to share some of my personal project implementation and experience. I sincerely hope this was helpful for you all, if so please share this article with your fellow developers… 😀

Stay awesome fellow Geeks ! ^_^

Advertisements

22 thoughts on “So I just implemented Push Notifications in awesome Xamarin.Forms … ;)

  1. Great blog post! I created the Notification Hub and added the code to my Windows Phone 8.1 app as instructed, but I can’t get it to work.

    I get 20 errors and 1 warning when I add change the MainPage class as instructed. I’m also not sure what values to enter in place of “param”. Can you be more specific about that? By the way, I had to add the Windows Azure Service Bus Managed for Windows Store and Windows Phone” NuGet package to get the App class, replace the Application_Launching method to work. I’m using Visual Studio 2013 and a Windows Phone 8.1 test device. When I take out the MainPage class and push the message from Azure, I get “The notification was successfully sent to Push Notifica….” under Outcome. I never see the message in my Windows Phone app.

    Here is the MainPage class I’m commenting out.

    // public MainPage()
    // {
    // InitializeComponent();
    // SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape;

    // global::Xamarin.Forms.Forms.Init();

    // SaveFilesToIsoStore();

    // LoadApplication(new MyApp.App()); // new in 1.3
    // }

    Any idea what the problem might be?

    Thanks, Brian

    1. Hi Brian,

      Thanks for the feedback and nice to hear you have tried it out.
      I have clearly mentioned at the beginning of the application to go over the Windows Azure Documentation first and the try out the code here, so you get the basic idea. Because I didn’t want to repeat the same stuff microsoft has documented.
      This code is for Windows Phone 8 projects, not for 8.1 Universal versions. If you had gone through the documentation, they have a separate implementation for that, https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-windows-store-dotnet-get-started/
      Please go through that documentation and try again, or switch to a Windows Phone 8 based project.
      “param” is the example parameter value I have added to the code to show how to pass parameter values through push notifications to the app. And in each implementation I have shown how the “param” value is captured and used in the app.

      Best Regards,
      – Udara.

  2. I commented out some more code in my MainPage class and now here is the last error.

    Error 2 ‘MyApp.App’ does not contain a constructor that takes 1 arguments C:\SOMEPATH\MainPage.xaml.cs 52 20 MyApp.WinPhone

    Any idea what might be causing this error?

    Thanks, Brian

  3. Thanks for the reply. OK, I’m targeting Windows 8.0 now, but I’m still getting the constructor error. I followed the Azure Notification Hub documentation to the letter, but I can’t get the code to compile without errors. I assume that I’m missing something, but from reading your documentation, all I need to do is create the Azure Notification Hub, edit the App class, MainPage class and add Push Notification to the manifest in order for this to work.

  4. your code save my life. I was a long time trying to open a xamarin.forms from Android Push and you show how to do that. Very thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s