Most of us are aware of website analytics, specifically Google Analytics, which is an incredible piece of software. I just love watching the real time view of the visitors on your site:
![GARealTime GARealTime](https://httpcodedotcom.wordpress.com/wp-content/uploads/2013/02/garealtime_thumb.jpg?w=644&h=238)
(The above image was from when Reddit broke the 100k user mark).
Did you also know that Google Analytics can be used for mobile applications?
Well it turns out that you have access to many of the same features. You can view users in real time,track exceptions and if you set up your tracking properly you can get some nice insights into how people use your application.
The SDK documentation show how easy it is to work with, but its also just as easy to work with the SDK with Phonegap (Cordova) apps.
I won’t go into the details on how to compile the SDK into your project, I’d rather show what some phonegap plugin code might look like.
For iOS:
- (void) start:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
[GAI sharedInstance].trackUncaughtExceptions = YES;
// Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
[GAI sharedInstance].dispatchInterval = 20;
// Optional: set debug to YES for extra debugging information.
[GAI sharedInstance].debug = YES;
// Create tracker instance.
id tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXXX-1"];
NSLog(@"GA Loaded and running");
tracker.sessionStart = YES;
}
- (void) trackEvent:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
id tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXX-1"];
NSString* category = [arguments objectAtIndex:1];
NSString* action = [arguments objectAtIndex:2];
NSString* label = [arguments objectAtIndex:3];
int value = [[options valueForKey:@"value"] intValue];
[tracker trackEventWithCategory:category
withAction:action
withLabel:label
withValue:[NSNumber numberWithInt:100]];
NSLog(@"GoogleAnalyticsPlugin.trackEvent::%@, %@, %@, %d",category,action,label,value);
}
- (void) trackPageView:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
id tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-XXX-1"];
NSString* pageUri = [arguments objectAtIndex:0];
[tracker trackView:pageUri];
}
For Andriod:
public class GoogleAnalyticsTracker extends CordovaPlugin {
public static final String START = "start";
public static final String TRACK_PAGE_VIEW = "trackPageView";
public static final String TRACK_EVENT = "trackEvent";
public static final String SET_CUSTOM_VARIABLE = "setCustomVariable";
public static final int DISPATCH_INTERVAL = 20;
private Tracker tracker;
private GoogleAnalytics instance;
public GoogleAnalyticsTracker() {
}
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException
{
if(instance == null){
instance = GoogleAnalytics.getInstance(cordova.getActivity().getBaseContext());
}
if(instance != null){
tracker = instance.getTracker("UA-XXX-1");
}
LOG.d("Analytics", "Analytics Loading ... " + action);
if (START.equals(action)) {
try {
LOG.d("Analytics", "Start..." + data.getString(0));
start(data.getString(0));
callbackContext.success("true");
return true;
} catch (JSONException e) {
return false;
}
} else if (TRACK_PAGE_VIEW.equals(action)) {
try {
LOG.d("Analytics", "Track Page view... " + data.getString(0));
trackPageView(data.getString(0));
callbackContext.success("true");
return true;
} catch (JSONException e) {
return false;
}
} else if (TRACK_EVENT.equals(action)) {
try {
trackEvent(data.getString(0), data.getString(1), data.getString(2), data.getLong(3));
callbackContext.success("true");
return true;
} catch (JSONException e) {
return false;
}
} else if (SET_CUSTOM_VARIABLE.equals(action)){
try {
setCustomVar(data.getInt(0), data.getString(1), data.getString(2), data.getInt(3));
callbackContext.success("true");
return true;
} catch (JSONException e) {
return false;
}
}
callbackContext.success("true");
return true;
}
private void start(String accountId) {
if(tracker != null){
tracker.setStartSession(true);
}
}
private void trackPageView(String key) {
if(tracker != null){
tracker.trackView(key);
}
}
private void trackEvent(String category, String action, String label, Long value){
if(tracker != null){
tracker.trackEvent(category, action, label, value);
}
}
Then the JavaScript that is called from your app might look like
Analytics.prototype.start = function(accountId, successCallback, failureCallback) {
return cordova.exec(
successCallback,
failureCallback,
'GoogleAnalytics',
'start',
[accountId]);
};
The other methods for pageview and event tracking follow much the same format, the key is to call the cordova.exec method.