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.
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 😦 !
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.
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. 🙂
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.
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.
You may customize the above as anyway you wish to… 😉
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.
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
Azure Hub Listening connection string
how you get the Azure Hub Listening connection string,
Google API Project Number
Wondering how to get the Google API Project Number ? Here it is..
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.
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.
So let’s head into 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..
And check your Provisioning Profile status…
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..
Then replace your AppDelegate code as following…
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.
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.
First of all in your App class, replace the Application_Launching method as following…
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…
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…
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…
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…
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…
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,
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=126.96.36.199
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… 😉
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… 🙂
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 ! ^_^