Sunday, 22 February 2015

Adding Google Analytics to Cordova/Phone Gap Hybrid Apps

I've incorporated Google Analytics usage reporting into a hybrid app I'm currently working on and thought I'd share my experience, in the hope that you can get up and running more quickly than I did.

After a quick google search I found a plugin that seemed to be provided via Adobe, which seemed promising, but I couldn't get to work despite much further googling and debugging:

I then looked for an alternative, and found this, but with similar results:

I'm quite prepared to accept that the fact these plugins didn't work for me is probably down to misconfiguration on my part, though it seems I'm not alone as variations on the problem I was seeing have been seen by others:

I encountered the problem described in the link above with both plugins, this is no reflection on the quality of either plugin, but rather my ability to work through the issue in the time available to me. 

The answer turned out to be fairly simple and involved using Google's own javascript API for analytics, as demonstrated in this proof of concept app:

The proof of concept is an implementation of the approach described here:

I copied the code into my solution, added my app's analytics tracking id, and I was soon up and running.

I did encounter a couple of gotchas though:

Don't forget to give your android app permission to access the internet, by adding the following entry to your android-manifest.xml file:

    <uses-permission android:name="android.permission.INTERNET" />

And remember to strip the leading slash from the path to your analytics.js file if you have it squirrelled away in a subfolder. For example if your local copy of analytics.js is held under www/lib, this won't work once your code is wrapped in an APK:


...but this will:


Please let me know if you encounter any issues with the above, happy tracking. :)
Post a Comment