donderdag 21 mei 2015

Creating (remote) push notifications with Azure and Xamarin.Android

Creating push notifications in Xamarin.Android is not that hard. But it needs some preparation, with preparation I mean that Google Cloud Messaging has to be configured and a server has to be prepared. In this case I am using Azure as server. In my case this server was created by my fellow college, so I don't know all the steps to configure this. But I have read some tutorials about creating the Azure server.

I got most of my code from the tutorial that can be found at, BUT be aware following this tutorial will not give a working example:
http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-notification-hubs-android-get-started/

After configuring the server and the GCM the actual coding can start. It is not very hard to create a notification, but in the tutorial are some mistakes I'll point these out.

First of all a constants class is created in the tutorial, this is done to make the SenderID, ConnectionString and NotificationHubPath to be shared through all the classes. So in this way it only has to be declared once.

public class Constant
    {
        public const string SenderID = "<googleprojectnumber>"; // Google API Project Number

        // Azure app specific connection string and hub path
        public const string ConnectionString = "azure connection string";
        public const string NotificationHubPath = "hub path";


        public Constant ()
        {
        }
    }


Now the broadcastreceiver will be created. First of all the needed permission needed to be added.

[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 NotificationsTest
{
    [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[] { Constant.SenderID };

        public const string TAG = "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(Constant.SenderID)
        {
            Log.Info(MyBroadcastReceiver.TAG, "PushHandlerService() constructor");
        }

        protected override void OnRegistered(Context context, string registrationId)
        {
            Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
            RegistrationID = registrationId;

            createNotification("PushHandlerService-GCM Registered...", "The device has been Registered, Tap to View!");

            Hub = new NotificationHub (Constant.NotificationHubPath, Constant.ConnectionString, this);

            try
            {
                Hub.UnregisterAll(registrationId);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                Debugger.Break();
            }

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

            try
            {

                //Instead of doing a NativeRegister we have to do a normal Register else this part will not work. And to register more than 1 tag, a for loop needs to be used to register all the tags.
                
for(int i = 0; i < tags.Count;i++){
                  Hub.Register(registrationId, tags[i]);
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                Debugger.Break();
            }
        }

        protected override void OnMessage(Context context, Intent intent)
        {
            Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");

            var msg = new StringBuilder();

            if (intent != null && intent.Extras != null) {
                foreach (var key in intent.Extras.KeySet())
  //if the message is a JSON string for example the "key" is the object, for example this can be managed with if(key=="ObjectName"){ .... }         msg.AppendLine (key + "=" + intent.Extras.Get (key).ToString ());
                   

            }

            string messageText = intent.Extras.GetString("msg");

            if (!string.IsNullOrEmpty(messageText))
            {
                createNotification("New hub message!", messageText);
                return;
            }
             
            createNotification("Person changed Location", msg.ToString());
        }

        void createNotification(string title, string desc)
        {
            //Create notification
            var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

            //Create an intent to show ui
            var uiIntent = new Intent(this, typeof(MainActivity));

            //Create the notification
            var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);

            //Auto cancel will remove the notification once the user touches it
            notification.Flags = NotificationFlags.AutoCancel;

            //Set the notification info
            //we use the pending intent, passing our ui intent over which will get called
            //when the notification is tapped.
            notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));

            //Show the notification
            notificationManager.Notify(1, notification);
        }

        #region implemented abstract members of GcmServiceBase

        protected override void OnError (Context context, string errorId)
        {
            throw new NotImplementedException ();
        }

        protected override void OnUnRegistered (Context context, string registrationId)
        {
            throw new NotImplementedException ();
        }

        #endregion
    }


Only the mainactivity has to be adjusted after the class above is created.

[Activity (Label = "NotificationsTest", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        int count = 1;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            RegisterWithGCM ();

            SetContentView (Resource.Layout.Main);
        }

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

            // Register for push notifications
            System.Diagnostics.Debug.WriteLine("Registering...");
            GcmClient.Register(this, Constant.SenderID);
        }
    }


This is all what it takes to create a notification, ofcourse this is just a rough example of how it is used. It still needs some customization. Feel free to leave a comment below if you have any questions about this.

Geen opmerkingen:

Een reactie posten