I recently needed to add Google Analytics support to a couple Xamarin Forms applications I am working on. I was a bit surprised that I didn’t find anything that was simply ready-built out in NuGet – it seems like a lot of people would, or at least should, be using some form of analytics for their mobile applications.
Since I’m a fan of generating APIs, and since I like freely sharing things that aren’t part of core business functions, I wrote a simple PCL library, pushed the code out to Github and published it to NuGet.
I didn’t add everything that GA supports – I don’t currently need features for ECommerce or Social Interactions. What it does provide it the ability to publish Events, Screen Views and Timing information.
First, you’ll need a GA account and then a Tracking ID for your application. Once that’s done, you just spin up an AnalyticsService instance:
var analytics = new AnalyticsService("UA-XXXXXXXX-X", applicationName: "My Xamarin App");
That’s all there is to it. You’re now ready to start tracking. GA has the ability to track things in a “session”, which allows you to get a feel for all of the activities a user did during that session. I typically start a session when the user opens the app or logs in, and close the session when they leave or log out. It’s as simple as this:
analytics.TrackSessionStart(); // do stuff you want to track analytics.TrackSessionEnd();
Tracking a screen view is just as simple:
If you want to track a specific event, let’s say a user clicking on a button click (Help, for example), you’d simply do something along these lines:
analytics.TrackEvent("user action", "button click", label: "help");
If you want to keep track of how long something takes – anything from data loads to how long a user sits on a page or whatever, you can track Timing like this:
analytics.TrackTiming("navigation", "Screen1", 5000);
While these are powerful, they do require you as a developer to do a fair bit of work to track everything you want. To simplify that, I also added support for GA directly into the OpenNETCF IoC library’s NavigationService. I’ll do a separate blog entry on how that works, but basically all you have to do is initialize tracking with your Tracking ID and the NavigationService will track all of your screen changes and timings for you with zero added code on your part.