Untitled-1

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 ^_^ !

14 thoughts on “Let’s add Google Analytics to your Xamarin Android App ^_^

  1. Good article. I’m having issue with “ScreenViewBuilder”, i cannot manage to get a single hit on GA. Is there any special config you haven’t listed that could enable / disable the whole process. No errors though, it’s even more difficult to investigate.

      1. Hi, I’ve a question: I used your good article to integrate Analytics into my Android App but seems that Analytics doesn’t receive data.
        In analytics console I can’t see data, all is empty.

        Could you help me? which could be the problem?

        Thanks in advance 🙂

      2. Hi there,

        Glad to hear you implemented. You need to have internet access enabled in your Manifest file 🙂
        And it takes a several minutes for the hits to be displayed in GA Real-time view when you access it for the first time. Also make sure your application is connected to the internet.

  2. Hi, I made exactly as your article and
    unfortunately nothing happened on Google Analytics.
    (I checked manifest file permissions, waited some time to page refresh or 5 steps described on Xamarin Forum)

    Any other idea?
    Thanks a lot and congrats for the article!

    1. Well that’s tricky, it should work accordingly. 🙂 this implementation worked perfectly when I was writing this article.
      Not sure whether Xamarin has deprecated this version of Google Play Services library right now. You might wanna look into updating you references and check the new implementations accordingly.

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