Tag Archives: Google Analytics Tracking

Google Analytics tracking implementation in Xamarin …

It all began a while back when my boss tasked me to implement Google Analytics Tracking in one of the enterprise mobile applications we were developing using Xamarin platform, and to be specific the whole app was based on Xamarin Forms platform, harnessing the true cross platform abilities of Xamarin…

Since the first day of the development, it’s been a bit hard but a massive learning curve, due to the lack of articles regarding Google Analytics implementation in Xamarin, specifically Xamarin Forms. And yes, I did go through some back and forth mess, as for the lack of resources… But somehow I managed to successfully implement Google Analytics Tracking in our Xamarin based enterprise application.

Therefore I decided to share the experience and the knowledge I gained, with our fellow Xamarin Developer Community and ultimately save the precious time of a another developer, with the hopes of filling the gap of the lack of articles in Google Analytics implementation in Xamarin. 🙂 So here is the series of articles I wrote in that pursue…

Google Analytics implementation in Xamarin Android –

Let’s add Google Analytics to your Xamarin Android App ^_^

Untitled-1

https://theconfuzedsourcecode.wordpress.com/2015/07/06/lets-add-google-analytics-to-your-xamarin-android-app-_/

Google Analytics implementation in Xamarin iOS –

Let’s add Google Analytics to your Xamarin iOS App ^_^

Untitled-2

https://theconfuzedsourcecode.wordpress.com/2015/07/09/lets-add-google-analytics-to-your-xamarin-ios-app-_/

Google Analytics implementation in Windows Phone –

Let’s add Google Analytics to your Windows Phone App ^_^

Untitled-3

https://theconfuzedsourcecode.wordpress.com/2015/07/17/lets-add-google-analytics-to-your-windows-phone-app-_/

Google Analytics implementation in Xamarin Forms –

Okay Finally, Let’s add Google Analytics to Xamarin Forms …

Untitled-1

https://theconfuzedsourcecode.wordpress.com/2015/07/18/okay-finally-lets-add-google-analytics-to-xamarin-forms/

Well there it goes… Google Analytics tracking implementation in Xamarin ! 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin, and you may save another developer’s precious time as well… 😉

Cheers ! Stay Awesome ^_^ !

Advertisements

Okay Finally, Let’s add Google Analytics to Xamarin Forms …

Okay Finally ? O.o Wait ! Let me get to that… After my previous two posts on Google Analytics implementation on Xamarin AndroidXamarin iOS, and Windows Phone I thought of completing this series of posts with Google Analytics implementation on Xamarin Forms, a final frontier for the true awesomeness Xamarin cross platform-ability… 😉 If you haven’t gone through the previous three posts, it’s alright ! I’m writing this article with everything  necessary for someone to start from scratch for Xamarn Forms implementation of Google Analytics.. 🙂 

Untitled-1

Google Analytics is a great way to track your User’s activities in your website or application. We all know that Google has given an extensive support for Websites and and native mobile applications implementation of Google Analytics. But what about Cross Platform applications ? Specially when it comes to our beloved Xamarin (Xamarin Forms) ?

Official component, and a catch eh ?

Now if you take a look at the official Google Analytics component for Xamarin… You may find a not-so-little catch there…

https://components.xamarin.com/view/googleanalytics

Untitled2

Hope you saw the catch…

It’s only available for Xamarin iOS ! 😦 What about Xamarin Android, Windows Phone ? and specially awesome Xamarin Forms ??? That’s quiet not so fair.. lol

And yes just like you, I have been going through the same puzzled moment… So I looked for 3rd party libraries for implementing Google Analytics in Xamarin Forms.

In Search for 3rd party Libraries…

I was very surprised to see how hard it was to find third party libraries for Xamarin Forms Google Analytics implementation. But after a deep searching I came across two libraries.

1. FrazzApps’ Google Analytics Connector

First of all I came across this library called FrazzApps’ Google Analytics Connector

https://www.nuget.org/packages/FrazzApps.Xamarin.Forms.GoogleAnalyticsConnector/

but unfortunately it was still on the Alpha release level, and when I looked into its’ code, I saw that they were using the Analytics Measurement Protocol which is used for parsing parameters through a URL to Google Analytics in order to track the activities.

This has a disadvantages, as we are passing parameters through a URL the Google Analytics server wouldn’t have any idea about the context of the application, such as from what kind of a device environment these tracking information are coming from and so on. But this library is certainly great for simple tracking. I’m pretty sure this will be a great use for Xamarin Forms once its completely developed.

2. Google Analytics SDK for Windows 8 and Windows Phone

Finally I found about this Library which was previously used for Windows Phone based Google Analytics tracking, this also supports Xamarin PCL projects.

https://googleanalyticssdk.codeplex.com/

This seem to be a quite promising library but I had some trouble implementing it, and I wanted to try out native Google Analytics implementation with Xamarin, so I decided to drop it for now and move on. Even though I strongly recommend you give a try for this library, please share your feedback with me if any of you were able to implement this.

Decision Time…

With almost no proper library support for implementing Google Analytics in Xamarin Forms, I was hopeless. But something struck me,

I was abIe to natively implement Google Analytics on Xamarin Android and Xamarin iOS ! As well as on Windows Phone, using separate libraries…

What if call those natively implemented functionalities from our Xamarin Forms PCL code ? Well thanks to the mighty Dependency Service of Xamarin of course… 😉

PROBLEM SOLVED !!!!!! 😀

Likewise I decided to implement Google Analytics in my Xamarin Forms project natively and call the necessary functionalities using Xamarin Dependency Service from our PCL project code. So let’s get started….

(I’m gonna assume that you are already aware of DependencyService in Xamarin.Forms platform 🙂 )

Setting up the Stuff…

Before we begin coding we need to do some setting up of the libraries for our Xamarin Android, Xamarin iOS and Xamarin WinPhone. Below are the Libraries we will be using for Google Analytics implementation in our native projects projects…

Xamarin Android – Google Play Services
Capture

Xamarin iOS – Google Analytics for Xamarin iOS
Untitled2

Xamarin WinPhone – Google Analytics SDK for Windows 8 and Windows Phone
Untitled5

So let’s get started one by one…

Setting up the Stuff on Xamarin Android Project…

In simple terms open up your Nuget Package manager and search for “Google Play Services” and install it in your Xamarin Android project. If you manage to install without any issue, then you are good to go.

But for some this could be a pretty much tricky process, and if you come across any difficulties or issues, I have written a complete article on how to add the Google Play Services component into your Xamarin Android project. Please follow through it and come back here… 😉
https://theconfuzedsourcecode.wordpress.com/2015/06/25/how-to-add-google-play-services-to-your-xamarin-android-project/

Once you set up the Google Play Services library in your Xamarin Android project, make sure to add internet connectivity permission in you Android Manifest file… 🙂

Next let’s move on to your Xamarin iOS setting up…

Setting up the Stuff on Xamarin iOS Project…

This is a bit easy,  praise the official Google Analytics component for Xamarin iOS😉 Go ahead download it.. 
https://components.xamarin.com/view/googleanalytics

Once you have downloaded, we need to add the DLLs to your Xamarin iOS project References. You can do that by navigating into the following path in the folder you downloaded and extracted the library files to, which should be something similar to this “C:\…\googleanalytics-3.0.12\googleanalytics-3.0.12\lib\ios-unified\”. Add the “GoogleAnalytics.iOS.dll” to your project references.

Please note that this is for the Xamarin iOS Unified SDK, not for the classic SDK ! 🙂 I wouldn’t be going into the class sdk as everyone is migrating to the ios unified SDK.

Setting up the Stuff on Xamarin WinPhone Project…

For Xamarin WinPhone open up your Nuget Package manager and search for “GoogleAnalyticsSDK” and easily install Google Analytics SDK for Windows 8 and Windows Phone in your Xamarin WinPhone project.

Unlike in other two platforms we need to configure our Google Analytics Tracker info into this library through a file, for that open up the “analytics.xml” file which was automatically being created by the library we just installed. This xml file is very important because the library will set up itself automatically through the configurations we insert through this file.

Untitled1

Go ahead and add the necessary information, and specially no matter what add your Google Analytics Mobile App Tracking code.

Untitled7

Also this xml file allows us to set up a whole list of configuration for our App tracking, and I’ll show you some of the most important configurations you need to pay attention to.

Untitled8

I have enabled the automated Exceptions tracking, in which case I don’t need to track every single exception that occurs in the application manually, but you can also set it to false on your choice. The rest of the two Properties Advertising Id Collection, Auto Activity Tracking can be enabled or disabled upon your choice.

Untitled9

There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we shouldn’t exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

Well that concludes the Setting up of the libraries in your native projects… 🙂 Let’s dive into Coding… 😉

Let the Coding begin…

As you have already learned in Xamarin in order to call the Native platform code, we need to use the Xamarin Dependency Service. Whereas here also we going to do the same, let’s start with the PCL project code implementation…

Let the Xamarin PCL Project Coding begin…

So to get started, let’s first of all implement the interface class in your PCL project we are going to be using with Xamarin Dependency Service…. Create the IGAService interface class as following…

namespace WhateverYourNamespace.Services
{
	public interface IGAService
	{
		void Track_App_Page(String PageNameToTrack);

		void Track_App_Event(String GAEventCategory, String EventToTrack);

		void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException);
	}
}

 

I have added three methods that I’m going to implement in the native projects, Tracking Page Views, Tracking Events, Tracking Exceptions… And you can see I have defined some parameters in those methods, I have added them because those information are required when we pass the data to the Google Analytics. Those method usage and parameters will be discussed step by step later…

In Google Analytics order to track any Event, such as a button click, check box selection and son on, you can use the following method.

In order to track an Event in Google Analytics, we need to have an Event Category, therefore we need to create a small struct along with the type of categories you need to track, this actually depends completely upon your requirement. You can have types of event categories such as. “Sales”, “Order”, “Shopping Cart” and so on… 🙂

public struct GAEventCategory
{
	public static String Category1 { get { return "Category1"; } set { } }
	public static String Category2 { get { return "Category2"; } set { } }
	public static String Category3 { get { return "Category3"; } set { } }
};

 

Whenever we are calling the  Track_App_Event() method, we will be passing the above struct values for the GAEventCategory parameter.

I kept a separate class to handle all the Google Analytics, where as I recommend you should do the same, which will make it easier.. 😉 Go ahead and create GAService class. In this class we are gonna implement all the GA functionalities we need to execute, whereas those methods will be calling the necessary IGAService interface methods through Xamarin Dependency Service…

// Google Analytics Services access point
public class GASConnect
{
	public static void Track_App_Page(String PageNameToTrack)
	{
		DependencyService.Get<IGAService>().Track_App_Page(PageNameToTrack);
	}

	public static void Track_App_Event(String GAEventCategory, String EventToTrack)
	{
		DependencyService.Get<IGAService>().Track_App_Event(GAEventCategory.ToString(), EventToTrack);
	}

	public static void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
	{
		DependencyService.Get<IGAService>().Track_App_Exception(ExceptionMessageToTrack, isFatalException);
	}
}

 

Well that’s the initial coding for Xamarin PCL project… 😉

Go ahead and Build your PCL project, next let it get into our Native project code implementation. We need to implement our IGAService interface in our native platform projects…

Let the Xamarin Android Project Coding begin…

Let’s start with Xamarin Android, you need to implement the IGAService interface, for that create GAService class…

[assembly: Dependency(typeof(WhateverYourNamespace.Droid.Services.GAService))]

namespace WhateverYourNamespace.Droid.Services
{
    public class GAService : IGAService
    {
        public string TrackingId = "XX-XXXXXXXX-X";

        private static GoogleAnalytics GAInstance;
        private static Tracker GATracker;
		
		#region Instantiation ...
        private static GAService thisRef;
        public GAService()
        {
            // no code req'd
        }

        public static GAService GetGASInstance()
        {
            if (thisRef == null)
                // it's ok, we can call this constructor
                thisRef = new GAService();
            return thisRef;
        }
        #endregion
        
        public void Initialize_NativeGAS(Context AppContext = null)
        {
            GAInstance = GoogleAnalytics.GetInstance(AppContext.ApplicationContext);
            GAInstance.SetLocalDispatchPeriod(10);

            GATracker = GAInstance.NewTracker(TrackingId);
            GATracker.EnableExceptionReporting(true);
            GATracker.EnableAdvertisingIdCollection(true);            
        }
    }
}

 

As for initializing we need to have instances with in this class as below and make sure to add the tracking code you get from your Google Analytics dashboard to the TrackingId value…

We are going to initialize the Google Analytics tracking service by calling the Initialize_NativeGAS() method, and for that we need to have a reference for the Android Context of your application, therefore we pass in the current Android Context as a parameter as shown above.

There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we shouldn’t exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

I have enabled the automated Exceptions tracking, in which case I don’t need to track every single exception that occurs in the application manually, but you can also set it to false on your choice as well as the Property Advertising Id Collection.

Now that we have initialized our Google Analytics natively, let’s implement the rest of the methods. Add the method implementations as follows… Make sure your final implementation is as follows…

[assembly: Dependency(typeof(WhateverYourNamespace.Droid.Services.GAService))]

namespace WhateverYourNamespace.Droid.Services
{
    public class GAService : IGAService
    {
        public string TrackingId = "XX-XXXXXXXX-X";

        private static GoogleAnalytics GAInstance;
        private static Tracker GATracker;
		
		#region Instantiation ...
        private static GAService thisRef;
        public GAService()
        {
            // no code req'd
        }

        public static GAService GetGASInstance()
        {
            if (thisRef == null)
                // it's ok, we can call this constructor
                thisRef = new GAService();
            return thisRef;
        }
        #endregion
        
        public void Initialize_NativeGAS(Context AppContext = null)
        {
            GAInstance = GoogleAnalytics.GetInstance(AppContext.ApplicationContext);
            GAInstance.SetLocalDispatchPeriod(10);

            GATracker = GAInstance.NewTracker(TrackingId);
            GATracker.EnableExceptionReporting(true);
            GATracker.EnableAdvertisingIdCollection(true);
            GATracker.EnableAutoActivityTracking(true);
        }

        public void Track_App_Page(String PageNameToTrack)
        {
            GATracker.SetScreenName(PageNameToTrack);
            GATracker.Send(new HitBuilders.ScreenViewBuilder().Build());
        }

        public void Track_App_Event(String GAEventCategory, String EventToTrack)
        {
            HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder();
            builder.SetCategory(GAEventCategory);
            builder.SetAction(EventToTrack);
            builder.SetLabel("AppEvent");

            GATracker.Send(builder.Build());
        }

        public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
        {
            HitBuilders.ExceptionBuilder builder = new HitBuilders.ExceptionBuilder();
            builder.SetDescription(ExceptionMessageToTrack);
            builder.SetFatal(isFatalException);

            GATracker.Send(builder.Build());
        }
    }
}

 

Now I’m not going to explain the method implementation of Page Views, Events and Exceptions tracking each line by line, otherwise this article would be too long. If you need more descriptive explanation please refer to my article on Google Analytics implementation Xamarin Android article..

Untitled-1Google Analytics implementation Xamarin Android article..

For further reading…

 

Also we to call the initialization method at the application start in Xamarin Android project level, for that change your OnCreate method in MainActivity class as follows…

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

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

	GAService.GetGASInstance().Initialize_NativeGAS(this);

	LoadApplication(new App());
}

 

Aaaand you are done with Xamarin Android implementation.. 🙂

Let the Xamarin iOS Project Coding begin…

Here also we are going to follow the same implementation procedure… We are going to implement the IGAService interface, for that create GAService class.

I’m not going to explain the initialization code step by step as I have done before, just keep in mind its the same concept of setting the Tracking Code, Dispatch Interval, and Uncaught Exception tracking properties and so on… So I’m going to jump into the full implemenation including the methods…

[assembly: Dependency(typeof(WhateverYourNamespace.iOS.Services.GAService))]

namespace WhateverYourNamespace.iOS.Services
{
    public class GAService : IGAService
    {
        public string TrackingId = "XX-XXXXXXXX-X";

        public IGAITracker Tracker;
        const string AllowTrackingKey = "AllowTracking";

        #region Instantition...
        private static GAService thisRef;
        public GAService()
        {
            // no code req'd
        }

        public static GAService GetGASInstance()
        {
            if (thisRef == null)
                // it's ok, we can call this constructor
                thisRef = new GAService();
            return thisRef;
        }
        #endregion

        public void Initialize_NativeGAS()
        {
            var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

            GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

            GAI.SharedInstance.DispatchInterval = 10;
            GAI.SharedInstance.TrackUncaughtExceptions = true;

            Tracker = GAI.SharedInstance.GetTracker("Test App", TrackingId);
        }

        public void Track_App_Page(String PageNameToTrack)
        {
            GAI.SharedInstance.DefaultTracker.Set(GAIConstants.ScreenName, PageNameToTrack);
            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateScreenView().Build());
        }

        public void Track_App_Event(String GAEventCategory, String EventToTrack)
        {
            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent(GAEventCategory, EventToTrack, "AppEvent", null).Build());
            GAI.SharedInstance.Dispatch(); // Manually dispatch the event immediately
        }

        public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
        {
            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateException(ExceptionMessageToTrack, isFatalException).Build());
        }
    }
}

 

We don’t need to pass in any context parameters or anything to our Initialize_NativeGAS() method like we did in Xamarin Android. Because in Xamarin iOS GA library it keeps a static shared instance of the GA tracking service where we can easy access.

As you can see above I have used the previously explained AllowTrackingKey variable to give the user option to opt out from the Tracking events by adding it to the SharedUserDefaults.

The method implementation is almost the same as Xamarin Android, but only the keywords and syntaxes are different.  If you need more descriptive explanation on the above code implementation please refer to my article on Google Analytics implementation Xamarin iOS article..

Untitled-2Google Analytics implementation Xamarin iOS article..

For further reading…

 

Also we need to call the initialization method at the application start in Xamarin iOS project level, You need to modify your FinishedLaunching method as follows,

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();

	GAService.GetGASInstance().Initialize_NativeGAS();

	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

 

Aaaand you are done with Xamarin iOS implementation.. 🙂

Let the Xamarin WinPhone Project Coding begin…

Here also we are going to follow the same implementation procedure… We are going to implement the IGAService interface, for that create GAService class.

I’m not going to explain the initialization code step by step as I have done before, just keep in mind its the same concept of setting the Tracking Code, Dispatch Interval, and Uncaught Exception tracking properties and so on… So I’m going to jump into the full implemenation including the methods…

[assembly: Dependency(typeof(WhateverYourNamespace.WinPhone.Services.GAService))]

namespace WhateverYourNamespace.WinPhone.Services
{
    public class GAService : IGAService
    {
        #region Instantition...
        private static GAService thisRef;
        public GAService()
        {
            // no code req'd
        }

        public static GAService GetGASInstance()
        {
            if (thisRef == null)
                // it's ok, we can call this constructor
                thisRef = new GAService();
            return thisRef;
        }
        #endregion

        public void Initialize_NativeGAS()
        {
            // No requirement for initializing in Windows Phone, its done by the 
            // library itself using the values given in the analytics.xml file
        }

        public void Track_App_Page(String PageNameToTrack)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendView(PageNameToTrack);
        }

        public void Track_App_Event(String GAEventCategory, String EventToTrack)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendEvent(GAEventCategory, EventToTrack, "AppEvent", 0);
        }

        public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendException(ExceptionMessageToTrack, isFatalException);
        }
    }
}

 

As you may have noticed above, we have left our Initialize_NativeGAS() method as empty, unlike in our Xamarin Android and iOS implementations where we initialized all the GA library components. It is because GA Library we have used for Xamarin WinPhone project, takes care of all that configuration and initialization by itself, with the help of the  “analytics.xml” file, which we configured at the beginning of this tutorial.

If you need more descriptive explanation on the above code implementation please refer to my article on Google Analytics implementation Windows Phone article..

Untitled-3

Google Analytics implementation Windows Phone article..

For further reading…

 

 

Aaaand you are done with Xamarin WinPhone implementation.. 🙂

Well that concludes all our Native Platform implementation, next let’s see how we could use this implementation in our PCL project… 🙂

Finally let’s FIRE IT UP… ! 😉

Well as our IGAService and its native GAService classes is ready to be called in through Xamarin Dependency Service,  let’s see how to access it and start tracking our App. 🙂

Here is how you could use our above class for Page Tracking, Event Tracking and Exception Tracking.

Let’s track a Page View…

Wherever you want to track a page view in your app, call our GASConnect class Track_App_Page() method in your PCL Project and pass in the Page Name as you wish… Yep it’s that easy, after all that implemenation..

// Track a page
GASConnect.Track_App_Page("Home Page");

 

Furthermore I suggest you do that in the ContentPage’s Appearing event such as below..

// Call the method in Page Appearing event
public class Page_Home : ContentPage 
{
	public Page_Home()
	{
	
		this.Appearing += (sender, e) =>
		{
			GASConnect.Track_App_Page("Home Page");
		};
	}
}

Let’s track an Event…

Wherever you want to track an event in your app, call our GASConnect class Track_App_Event() method in your PCL Project and pass in the Event Category Type and Descirption as you wish…

// Track an event
GASConnect.Track_App_Event(GAEventCategory.Category1, "hey ! Category 1 type event ocurred !");   

// Track an event
GASConnect.Track_App_Event(GAEventCategory.Category1, "hey ! Category 2 type event ocurred !");   

 

Let’s track an Exception…

Wherever you want to track an exception in your app, call our GASConnect class Track_App_Exception() method in your PCL Project and when you pass in the Exception message, you can either take the whole ex.StackTrace() or ex.Massage() or both together as a value of your exception in anyway you wish…

// Track an Exception
GASConnect.Track_App_Exception(ex.Message, false); 

 

After calling those methods you will be able to see the live tracking information in your Google Anlytics Dashboard online. Just log in to the Real-Time Overview  and you will be able to see everything there. Just keep in mind, as there is a dispatch period of 10 seconds, it might take a while for the actual tracking data to be displayed in the Real-Time tracking view in Google Analytics… 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin Forms, and you may save another developer’s precious time as well… 😉

Cheers ! Stay Awesome ^_^ !

Let’s add Google Analytics to your Windows Phone App ^_^

After my two previous posts on, Adding Google Analytics for Xamarin Android and Adding Google Analytics for Xamarin iOS the time has come for Windows Phone implementation of Google Analytics… 😉
Well I managed to blog about the major two platforms implementation Android and iOS, so why not blog about the 3rd rival’s implementation, awesome Windows Phone.. ^_^

Untitled-3

I’m not gonna lie to you, when it comes to Google Analytics implementation its pretty much easy thanks to the extended 3rd party library support. Couple of years back I recall looking for a library for this same scenario and I tried out several 3rd party libraries, but none of them served the purpose pretty well. But later I found out this library for Google Analytics implementation on Windows Phone…

https://googleanalyticssdk.codeplex.com/

Untitled5

I have been using this library for all my Windows Phone and Windows Store apps since long time back and it worked perfectly and still serves the purpose very well. So in this article I will be showing you how to implement this library in your project for Google Analytics tracking.

This library has got some good documentation about how to implement it on Windows Phone, with easy to use code samples. But I’m gonna add some decorations to it and explain you how to implement it from the scratch.

Setting up the Library…

In order to set up the library we need to get it from NuGet Package Manager in your Visual Studio… Go ahead Right click on your References and go to Manage NuGet Packages which opens up the NuGet Package Manager..

Untitled2

Select the Online section and search for “GoogleAnalyticsSDK“, hit Enter ! Once the results comes up hit Install…

Untitled3

Let it install… ^_^

Untitled4

Wait for itttttt….. 😛

Untitled5

And you are DONE ! but not quite yet… 😉

We need to configure our Google Analytics Tracker info into the library, for that open up the “analytics.xml” file which was automatically being created by the library we just installed. This xml file is very important because the library will set up itself automatically through the configurations we insert through this file.

Untitled1

Go ahead and add the necessary information, and specially no matter what add your Google Analytics Mobile App Tracking code. If you haven’t acquired Google Analytics mobile app tracking code yet, then here’s some tip, https://support.google.com/analytics/answer/2587086?hl=en

Untitled7

Also this xml file allows us to set up a whole list of configuration for our App tracking, and I’ll show you some of the most important configurations you need to pay attention to.

Untitled8

I have enabled the automated Exceptions tracking, in which case I don’t need to track every single exception that occurs in the application manually, but you can also set it to false on your choice. The rest of the two Properties Advertising Id Collection, Auto Activity Tracking can be enabled or disabled upon your choice.

Untitled9

There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we shouldn’t exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

POST UPDATE 16/09/2015

If anyone is wondering whether its possible to set up above configuartion from code behind, the answer is, YES ! IT IS POSSIBLE !
You can easily create an EasyTrackerConfig object and set up all the configuration from code behind instead of setting it up in the analytics.xml file as follows where I have configured it in the Initialize() method.

public void Initialize()
{
	var config = new GoogleAnalytics.EasyTrackerConfig();
	config.AppName = "You App Name";
	config.AppVersion = "1.0.0";
	config.TrackingId = "XX-XXXXXX";

	GoogleAnalytics.EasyTracker.Current.Config = config;
}

 

Well that’s the end of setting up the library and GA tracking code… let’s get into coding…

Let the Coding begin…

Just as I have done in my previous articles, I recommend that you keep a separate class for handling all the Google Analytics functionalities. So go ahead and create GAService class. In this class we are gonna implement all the GA functionalities we need to execute.

public class GAService
{
	public void Initialize()
	{
		// No requirement for initializing in Windows Phone, its done by the 
		// library itself using the values given in the analytics.xml file
	}
}

 

Now that we have done with creating the class, next let’s dive into coding the actions… 😉

Trust me its going to be very much simple, thanks to the simplicity of this library we are using…

Let’s track a Page View…

In order to track a Page you may need to add the following method to our GAService class.

public void Track_App_Page(String PageNameToTrack)
{
	GoogleAnalytics.EasyTracker.GetTracker().SendView(PageNameToTrack);
}

 

This library, Google Analytics SDK comes with a special feature called “EasyTracker” which makes it very easy to access GA functionalities. There’s no need of any instantiation,  as the library takes care of all that by itself.

As you can see above we are passing in the Page Name we need to track and we are creating a Page View with the SendView() method,  which is used to create a new a screen view hit. Keep in mind whatever the name you pass in to the method will be recorded in Google Analytics, whenever we need to track a page view, we will be calling this method.

Let’s track an Event…

In order to track any Event, such as a button click, check box selection and son on, you can use the following method. This is very much likely how we did in Xamarin Android, but the syntaxes are a bit different.

In order to track an Event in Google Analytics, we need to have an Event Category, therefore we need to create a small struct along with the type of categories you need to track, this actually depends completely upon your requirement. You can have types of event categories such as. “Sales”, “Order”, “Shopping Cart” and so on… 🙂

public struct GAEventCategory
{
	public static String Category1 { get { return "Category1"; } set { } }
	public static String Category2 { get { return "Category2"; } set { } }
	public static String Category3 { get { return "Category3"; } set { } }
};

 

Now let’s implement the method, for this method we will be passing the above struct values for the GAEventCategory parameter. And for the EventToTrack parameter, you can send whatever event/ event description you want to record in Google Analytics.

public void Track_App_Event(String GAEventCategory, String EventToTrack)
{
	GoogleAnalytics.EasyTracker.GetTracker().SendEvent(GAEventCategory, EventToTrack, "AppEvent", 0);
}

 

As shown above we are using the SendEvent() with the EasyTracker call to create a new event and we are setting up the category and event action as it’s passed in as parameters. Also you can set Labels in Google Analytics for any of your events, but as a general I have set the default label to “AppEvent”, but you can use labeling if you want to generate more complex and detailed tracking, where as Google Analytics is a truly great tool. The library also provides you an extra long parameter at the end, most probably in case you needed to add some other numeric information for the event, but I have set it to 0 by default.

Let’s track an Exception…

Now we all know that exceptions O.o are such a nasty bastard in any application. And its a good habit to keep a track on them. As I have mentioned above,

Untitled8

This Tacker setting captures all the Exceptions that occurs in the application, but keep in mind, this only tracks the unhandled exceptions. Now how about the handled exceptions ? what if we need to keep a track on a certain type of exceptions that’s already being handled in the application.

For such instances you may use the following piece of code… 😉 Just like we did in Xamarin, if you want to record an Exception event in Google Analytics, you need to mention whether it’s a Fatal Exception or not. Therefore you need to pass in a Boolean mentioning whether it’s fatal or not as coded in the below method.

public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
{
	GoogleAnalytics.EasyTracker.GetTracker().SendException(ExceptionMessageToTrack, isFatalException);
}

 

We are using the SendException() method call for this hit in the same way I have used in the other two events above. And when you pass in the Exception message, you can either take the whole ex.StackTrace() or ex.Massage() or both together as a value of your exception in anyway you wish. 🙂 

And now just like we did in Xamarin Android we need to do some decorations to our GAService class…

Just a little decorating…

Now I have unified the access to the Google Analytics tracking by including all the methods in one single class, but in order to access it we need to instantiate right ? That’s why we need to add a little Singleton pattern decoration to our class. Or else you could also make the methods static and straightaway call them, but its your wish.. 🙂

#region Instantition...
private static GAService thisRef;
private GAService()
{
	// no code req'd
}

public static GAService GetGASInstance()
{
	if (thisRef == null)
		// it's ok, we can call this constructor
		thisRef = new GAService();
	return thisRef;
}
#endregion

 

Now that way we can keep a single instance and use it to execute all the functions.

After all that’s done your GAService class should look like this… 🙂

namespace WhateverYourNamespace
{
    public class GAService
    {
        #region Instantition...
        private static GAService thisRef;
        private GAService()
        {
            // no code req'd
        }

        public static GAService GetGASInstance()
        {
            if (thisRef == null)
                // it's ok, we can call this constructor
                thisRef = new GAService();
            return thisRef;
        }
        #endregion

        public void Initialize()
        {
            // No requirement for initializing in Windows Phone, its done by the 
            // library itself using the values given in the analytics.xml file
        }

        public void Track_App_Page(String PageNameToTrack)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendView(PageNameToTrack);
        }

        public void Track_App_Event(String GAEventCategory, String EventToTrack)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendEvent(GAEventCategory, EventToTrack, "AppEvent", 0);
        }

        public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
        {
            GoogleAnalytics.EasyTracker.GetTracker().SendException(ExceptionMessageToTrack, isFatalException);
        }
    }
}

 

Finally let’s FIRE IT UP… ! 😉

Well as our GAService class is ready, let’s see how to access it and start tracking our App. 🙂

// Track a page
GAService.GetGASInstance().Track_App_Page("Home Page");

// Track an event
GAService.GetGASInstance().Track_App_Event(GAEventCategory.Category1, "hey ! Category 1 type event ocurred !");   

// Track an Exception
GAService.GetGASInstance().Track_App_Exception(ex.Message, false); 

 

After calling those methods you will be able to see the live tracking information in your Google Anlytics Dashboard online. Just log in to the Real-Time Overview  and you will be able to see everything there. Just keep in mind, as there is a dispatch period of 10 seconds, it might take a while for the actual tracking data to be displayed in the Real-Time tracking view in Google Analytics… 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers and you may save another developer’s time as well… 😉

Cheers ! Stay Awesome ^_^ !

Let’s add Google Analytics to your Xamarin iOS App ^_^

After my previous post about how to add Google Analytics to your Xamarin Android app, I thought of writing an article for Xamarin iOS as well based on my own experience. 🙂

When I was implementing Google Analytics in one of my Xamarin iOS projects, it wasn’t such a complicated process, thanks to the official Xamarin component for GA (Google Analytics) but then again, I couldn’t find much articles based on its code implementation, whereas I had to begin with simple example they have given in the Xamarin Component Store.

Untitled-2

Now the whole concept of the Google Analytics implementation in Xamarin iOS is pretty much same as the implementation in Xamarin Android, but the coding approach and syntax are different.

Therefore I thought of sharing my experience and coding approach with you fellow Xamarin developers out there, which I’m pretty sure will be very much helpful for you all. 😉

Setting up the Library…

First of all, follow me and praise the official Google Analytics component for Xamarin iOS… 😉 Go ahead download it..

https://components.xamarin.com/view/googleanalytics

Untitled2

Once you have downloaded, we need to add the DLLs to your project References. You can do that by navigating into the following path in the folder you downloaded and extracted the library files to, which should be something similar to this “C:\…\googleanalytics-3.0.12\googleanalytics-3.0.12\lib\ios-unified\”. Add the “GoogleAnalytics.iOS.dll” to your project references.

Please note that this is for the Xamarin iOS Unified SDK, not for the classic SDK ! 🙂 I wouldn’t be going into the class sdk as everyone is migrating to the ios unified SDK.

Let the Coding begin…

Just as I have done in my previous article, I recommend that you keep a separate class for handling all the Google Analytics functionalities. So go ahead and create GAService class. In this class we are gonna implement all the GA functionalities we need to execute.

As for initializing we need to have instances with in this class as below and make sure to add the tracking code you get from your Google Analytics dashboard to the TrackingId value…

public string TrackingId = "XX-XXXXXXXX-X";

public IGAITracker Tracker;
const string AllowTrackingKey = "AllowTracking";

 

As you can see above, except for the Google Analytics instance I have added a string called “AllowTrackingKey“, this is going to be used for allowing the user to opt out of the analytics tracking upon their choice. I have just added it to this code, for the sake of good practices, but you can remove it from here and later in the code implementation if you wish to.

In the constructor, we need to initialize the Google Analytics tracking service, and for that we need to have a reference and we do not need to pass in any references like we did in Xamarin Android. 🙂 Because in Xamarin GA it keeps a static shared instance of the GA tracking service where we can easy access.

public void Initialize()
{
	var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));
	NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

	GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

	GAI.SharedInstance.DispatchInterval = 10;
	GAI.SharedInstance.TrackUncaughtExceptions = true;

	Tracker = GAI.SharedInstance.GetTracker("Test App", TrackingId);
}

 

As you can see above I have used the previously explained AllowTrackingKey variable to give the user option to opt out from the Tracking events by adding it to the SharedUserDefaults.

Here we are using the Shared instance that Xamarin GA provides in order to instantiate it with our configuration. There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we should not exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

For some reason exception for the AutoExceptionTracking I couldn’t find any methods or properties to enable AutoActivityTracking and AdvertisingIdCollection, like we did in Xamarin Android. Probably they can not be supported in iOS platform.

Now that we have done with the initialization, next let’s dive into coding the actions… 😉

Let’s track a Page View…

In order to track a Page you may need to add the following method to our GAService class.

public void Track_App_Page(String PageNameToTrack)
{
	GAI.SharedInstance.DefaultTracker.Set(GAIConstants.ScreenName, PageNameToTrack);
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateScreenView().Build());
}

 

As you can see above we are passing in the Page Name we need to track and we are setting it to our GA tracker instance . Then within the Send() method call we are creating a new Screen View with the GAIDictionaryBuilder (there are several types of GAI Dictionary Builders which you could use based on several types events you need to track), specifically calling the CreateScreenView(), which is used to create a new a screen view hit. Keep in mind whatever the name you pass in to the method will be recorded in Google Analytics, whenever we need to track a page view, we will be calling this method.

Let’s track an Event…

In order to track any Event, such as a button click, check box selection and son on, you can use the following method. This is very much likely how we did in Xamarin Android, but the syntaxes are a bit different.

In order to track an Event in Google Analytics, we need to have an Event Category, therefore we need to create a small struct along with the type of categories you need to track, this actually depends completely upon your requirement. You can have types of event categories such as. “Sales”, “Order”, “Shopping Cart” and so on… 🙂

public struct GAEventCategory
{
	public static String Category1 { get { return "Category1"; } set { } }
	public static String Category2 { get { return "Category2"; } set { } }
	public static String Category3 { get { return "Category3"; } set { } }
};

 

Now let’s implement the method, for this method we will be passing the above struct values for the GAEventCategory parameter. And for the EventToTrack parameter, you can send whatever event/ event description you want to record in Google Analytics.

public void Track_App_Event(String GAEventCategory, String EventToTrack)
{
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent(GAEventCategory, EventToTrack, "AppEvent", null).Build());
	GAI.SharedInstance.Dispatch(); // Manually dispatch the event immediately // just for demonstration // not much recommended 
}

 

As shown above we are using the GAIDictionaryBuilder with the CreateEvent method call to create a new event and we are setting up the category and event action as it’s passed in as parameters. Also you can set Labels in Google Analytics for any of your events, but as a general I have set the default label to “AppEvent”, but you can use labeling if you want to generate more complex and detailed tracking, where as Google Analytics is a truly great tool.

Also you may notice that I have called the method Dispatch() right at the bottom, this is just to show you that, we can manually dispatch the Analytics data on demand as we wish, without waiting for the default dispatch to occur. 🙂 Like wise even in other events you can call the dispatch method and immediate send the tracking data to GA servers, but I wouldn’t recommend that as it could clog up your bandwidth usage.

Let’s track an Exception…

Now we all know that exceptions O.o are such a nasty bastard in any application. And its a good habit to keep a track on them. As I have mentioned above,

GAI.SharedInstance.TrackUncaughtExceptions = true;

 

This Tacker setting captures all the Exceptions that occurs in the application, but keep in mind, this only tracks the unhandled exceptions. Now how about the handled exceptions ? what if we need to keep a track on a certain type of exceptions that’s already being handled in the application.

For such instances you may use the following piece of code… 😉 Just like we did in Xamarin Android, if you want to record an Exception event in Google Analytics, you need to mention whether it’s a Fatal Exception or not. Therefore you need to pass in a Boolean mentioning whether it’s fatal or not as coded in the below method.

public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
{
	GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateException(ExceptionMessageToTrack, isFatalException).Build());
}

 

We are using the GAIDictionaryBuilder with CreateException method call for this hit in the same method I have used in the other two events above. And when you pass in the Exception message, you can either take the whole ex.StackTrace() or ex.Massage() or both together as a value of your exception in anyway you wish. 🙂 

And now just like we did in Xamarin Android we need to do some decorations to our GAService class…

Just a little decorating…

Now I have unified the access to the Google Analytics tracking by including all the methods in one single class, but in order to access it we need to instantiate right ? That’s why we need to add a little Singleton pattern decoration to our class. Or else you could also make the methods static and straightaway call them, but its your wish.. 🙂

#region Instantition...
private static GAService thisRef;
private GAService()
{
	// no code req'd
}

public static GAService GetGASInstance()
{
	if (thisRef == null)
	// it's ok, we can call this constructor
	thisRef = new GAService();
	return thisRef;
}
#endregion

 

Now that way we can keep a single instance and use it to execute all the functions.

After all that’s done your GAService class should look like this… 🙂

namespace WhateverYourNamespace
{
	public class GAService
	{
		public string TrackingId = "XX-XXXXXXXX-X";

		public IGAITracker Tracker;
		const string AllowTrackingKey = "AllowTracking";

		#region Instantition...
		private static GAService thisRef;
		private GAService()
		{
			// no code req'd
		}

		public static GAService GetGASInstance()
		{
			if (thisRef == null)
			// it's ok, we can call this constructor
			thisRef = new GAService();
			return thisRef;
		}
		#endregion

		public void Initialize()
		{
			var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));
			NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

			GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

			GAI.SharedInstance.DispatchInterval = 10;
			GAI.SharedInstance.TrackUncaughtExceptions = true;

			Tracker = GAI.SharedInstance.GetTracker("Test App", TrackingId);
		}

		public void Track_App_Page(String PageNameToTrack)
		{
			GAI.SharedInstance.DefaultTracker.Set(GAIConstants.ScreenName, PageNameToTrack);
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateScreenView().Build());
		}

		public void Track_App_Event(String GAEventCategory, String EventToTrack)
		{
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent(GAEventCategory, EventToTrack, "AppEvent", null).Build());
			GAI.SharedInstance.Dispatch(); // Manually dispatch the event immediately
		}

		public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
		{
			GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateException(ExceptionMessageToTrack, isFatalException).Build());
		}
	}
}

 

Finally let’s FIRE IT UP… ! 😉

Well as our GAService class is ready, let’s see how to access it and start tracking our App. 🙂

You need to modify your FinishedLaunching method as follows,

public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
	window = new UIWindow (UIScreen.MainScreen.Bounds);

	GAService.GetGASInstance().Initialize();

	viewController = new HomePage ();
	navController = new UINavigationController (viewController);
	window.RootViewController = navController;
	window.MakeKeyAndVisible();
	
	return true;
}

 

As you can see above I am first of all initializing our Google Analytics services through the GetGASInstance() method.

Here is how you could use our above class for Page Tracking, Event Tracking and Exception Tracking.

// Track a page
GAService.GetGASInstance().Track_App_Page("Home Page");

// Track an event
GAService.GetGASInstance().Track_App_Event(GAEventCategory.Category1, "hey ! Category 1 type event ocurred !");   

// Track an Exception
GAService.GetGASInstance().Track_App_Exception(ex.Message, false); 

 

After calling those methods you will be able to see the live tracking information in your Google Anlytics Dashboard online. Just log in to the Real-Time Overview  and you will be able to see everything there. Just keep in mind, as there is a dispatch period of 10 seconds, it might take a while for the actual tracking data to be displayed in the Real-Time tracking view in Google Analytics… 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin iOS, and you may save another developer’s time as well… 😉

Cheers ! Stay Awesome ^_^ !

Let’s add Google Analytics to your Xamarin Android App ^_^

We all praise Google Analytics whenever we need to track the usage of our mobile applications. Thanks the amazing momentum of Google Analytics its pretty much easy to implement it in any Web application or mobile application. But when it comes to Cross Platform implementation such as in Xamarin, it’s a bit new approach.

There was this time I wanted to implement Google Analytics in one of my Xamarin Android Apps, and when I looked up over the internet I couldn’t find any proper documentation. And having Google pulled out the Google Analytics support from the Xamarin Google Analytics Component, was a huge disappointment. It was later attached into Google Play Services Library and even regarding that, there weren’t any proper documentation about the implementation.

Untitled-1

So I went through a little bit of an annoyance when implementing GA (Google Analytics) in my Xamarin Android project, which is why I thought of sharing some of the coding approaches and experience with you, fellow developers. As there aren’t much tutorials or documentation available for this topic, I’m pretty sure this will be helpful for fellow Xamarin developers out there… 🙂

Setting up the Library…

Now as the first step we need to set up the DLL libraries in our project. As I have mentioned we need to add the Google Play Services library to our project in order to access Google Analytics tracking services.

This is a bit tricky process, and I have written a complete article on how to add the Google Play Services component into your Xamarin Android project. Please follow through it and come back here… 😉
https://theconfuzedsourcecode.wordpress.com/2015/06/25/how-to-add-google-play-services-to-your-xamarin-android-project/Untitled-1

Well once you are done, let’s get to the next step…

Let the Coding begin…

I kept a separate class to handle all the Google Analytics, where as I recommend you should do the same, which will make it easier.. 😉 Go ahead and create GAService class. In this class we are gonna implement all the GA functionalities we need to execute.

As for initializing we need to have instances with in this class as below and make sure to add the tracking code you get from your Google Analytics dashboard to the TrackingId value…

public string TrackingId = "XX-XXXXXXXX-X";

private static GoogleAnalytics GAInstance;
private static Tracker GATracker;

 

In the constructor, we need to initialize the Google Analytics tracking service, and for that we need to have a reference for the Android Context of your application, therefore pass in the current Android Context as a parameter like below.

public void Initialize(Context AppContext)
{
	GAInstance = GoogleAnalytics.GetInstance(AppContext.ApplicationContext);
	GAInstance.SetLocalDispatchPeriod(10);

	GATracker = GAInstance.NewTracker(TrackingId);
	GATracker.EnableExceptionReporting(true);
	GATracker.EnableAdvertisingIdCollection(true);
	GATracker.EnableAutoActivityTracking(true);
}

 

There up above as you can see I have set the Local dispatch period to “10”, which means all the tracking data will be automatically uploaded to the online GA service in every 10 seconds, this is a good approach considering we shouldn’t exhaust the network resources by uploading tracking information every single second. You can change the value to anything you wish but I recommend you keep it around this value.

I have enabled the automated Exceptions tracking, in which case I don’t need to track every single exception that occurs in the application manually, but you can also set it to false on your choice. The rest of the two Properties Advertising Id Collection, Auto Activity Tracking can be enabled or disabled upon your choice.

Now that we have done with the initialization, next let’s dive into coding the actions… 😉

Let’s track a Page View…

In order to track a Page you may need to add the following method to our GAServices class.

public void Track_App_Page(String PageNameToTrack)
{
	GATracker.SetScreenName(PageNameToTrack);
	GATracker.Send(new HitBuilders.ScreenViewBuilder().Build());
}

 

As you can see above we are passing in the Page Name we need to track and we are setting it to our GA tracker instance through SetScreeName method. Then within the Send() method call we are creating a new HitBuilder (there are several types of Hit Builders which you could use based on several events you need to track), specifically ScreenViewBuilder, which is used to track Page views of the app. Keep in mind whatever the name you pass in to the method will be recorded in Google Analytics, whenever we need to track a page view, we will be calling this method.

Let’s track an Event…

In order to track any Event, such as a button click, check box selection and son on, you can use the following method.

In order to track an Event in Google Analytics, we need to have an Event Category, therefore we need to create a small struct along with the type of categories you need to track, this actually depends completely upon your requirement. You can have types of event categories such as. “Sales”, “Order”, “Shopping Cart” and so on… 🙂

public struct GAEventCategory
{
	public static String Category1 { get { return "Category1"; } set { } }
	public static String Category2 { get { return "Category2"; } set { } }
	public static String Category3 { get { return "Category3"; } set { } }
};

 

Now let’s implement the method, for this method we will be passing the above struct values for the GAEventCategory parameter. And for the EventToTrack parameter, you can send whatever event/ event description you want to record in Google Analytics.

public void Track_App_Event(String GAEventCategory, String EventToTrack)
{
	HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder();
	builder.SetCategory(GAEventCategory);
	builder.SetAction(EventToTrack);
	builder.SetLabel("AppEvent");

	GATracker.Send(builder.Build());
}

 

As shown above we are using the EventBuilder for the HitBuilders type and we are setting up the category and event action as its passed in as parameters. Also you can set Labels in Google Analytics for any of your events, but as a general I have set the default label to “AppEvent”, but you can use labeling if you want to generate more complex and detailed tracking, where as Google Analytics is a truly great tool. 🙂

Let’s track an Exception…

Now we all know that exceptions O.o are such a nasty bastard in any application. And its a good habit to keep a track on them. As I have mentioned above,

GATracker.EnableExceptionReporting(true);

 

This Tacker setting captures all the Exceptions that occurs in the application, but keep in mind, this only tracks the unhandled exceptions. Now how about the handled exceptions ? what if we need to keep a track on a certain type of exceptions that’s already being handled in the application.

For such instances you may use the following piece of code… 😉 In Google Analytics, if you want to record an Exception event, you need to mention whether its a Fatal Exception or not. Therefore you need to pass in a Boolean mentioning whether its fatal or not as coded in the below method.

public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
{
	HitBuilders.ExceptionBuilder builder = new HitBuilders.ExceptionBuilder();
	builder.SetDescription(ExceptionMessageToTrack);
	builder.SetFatal(isFatalException);

	GATracker.Send(builder.Build());
}

 

We are using an ExceptionBuilder for this hit in the same method I have used in the other two events above. And when you pass in the Exception message, you can either take the whole ex.StackTrace() or ex.Massage() or both together value of your exception as you wish. 🙂

Just a little decorating…

Now I have unified the access to the Google Analytics tracking by including all the methods in one single class, but in order to access it we need to instantiate right ? That’s why we need to add a little Singleton pattern decoration to our class. Or else you could also make the methods static and straightaway call them, but its your wish.. 🙂

#region Instantiation ...
private static GAService thisRef;
private GAService()
{
	// no code req'd
}

public static GAService GetGASInstance()
{
	if (thisRef == null)
		// it's ok, we can call this constructor
		thisRef = new GAService();
	return thisRef;
}
#endregion

 

Now that way we can keep a single instance and use it to execute all the functions.

After all that’s done your GAService class should look like this… 🙂

namespace WhateverYourNamespace
{
    public class GAService
    {
        public string TrackingId = "XX-XXXXXXXX-X";

        private static GoogleAnalytics GAInstance;
        private static Tracker GATracker;
		
		#region Instantiation ...
		private static GAService thisRef;
		private GAService()
		{
			// no code req'd
		}

		public static GAService GetGASInstance()
		{
			if (thisRef == null)
				// it's ok, we can call this constructor
				thisRef = new GAService();
			return thisRef;
		}
		#endregion
        
        public void Initialize(Context AppContext)
        {
            GAInstance = GoogleAnalytics.GetInstance(AppContext.ApplicationContext);
            GAInstance.SetLocalDispatchPeriod(10);

            GATracker = GAInstance.NewTracker(TrackingId);
            GATracker.EnableExceptionReporting(true);
            GATracker.EnableAdvertisingIdCollection(true);
            GATracker.EnableAutoActivityTracking(true);
        }

        public void Track_App_Page(String PageNameToTrack)
        {
            GATracker.SetScreenName(PageNameToTrack);
            GATracker.Send(new HitBuilders.ScreenViewBuilder().Build());
        }

        public void Track_App_Event(String GAEventCategory, String EventToTrack)
        {
            HitBuilders.EventBuilder builder = new HitBuilders.EventBuilder();
            builder.SetCategory(GAEventCategory);
            builder.SetAction(EventToTrack);
            builder.SetLabel("AppEvent");

            GATracker.Send(builder.Build());
        }

        public void Track_App_Exception(String ExceptionMessageToTrack, Boolean isFatalException)
        {
            HitBuilders.ExceptionBuilder builder = new HitBuilders.ExceptionBuilder();
            builder.SetDescription(ExceptionMessageToTrack);
            builder.SetFatal(isFatalException);

            GATracker.Send(builder.Build());
        }
    }
}

 

Finally let’s FIRE IT UP… ! 😉

Well as our GAService class is ready, let’s see how to access it and start tracking our App. 🙂

You need to modify your OnCreate method as follows,

protected override void OnCreate(Bundle bundle)
{
	base.OnCreate(bundle);
	
	SetContentView(Resource.Layout.Main);

	GAService.GetGASInstance().Initialize(this);
	
}

 

As you can see above I am first of all initializing our Google Analytics services through the GetGASInstance method.

Here is how you could use our above class for Page Tracking, Event Tracking and Exception Tracking.

// Track a page
GAService.GetGASInstance().Track_App_Page("Home Page");

// Track an event
GAService.GetGASInstance().Track_App_Event(GAEventCategory.Category1, "hey ! Category 1 type event ocurred !");   

// Track an Exception
GAService.GetGASInstance().Track_App_Exception(ex.Message, false); 

 

After calling those methods you will be able to see the live tracking information in your Google Anlytics Dashboard online. Just log in to the Real-Time Overview  and you will be able to see everything there. Just keep in mind, as there is a dispatch period of 10 seconds, it might take a while for the actual tracking data to be displayed in the Real-Time tracking view in Google Analytics… 🙂

Well there it goes folks, hope this post was helpful for you and prolly saved you a lot of time… 🙂 Please share this among other developers as there aren’t much tutorials on Google Analytics tracking for Xamarin Android, and you may save another developer’s time as well… 😉

Cheers ! Stay Awesome ^_^ !