Skip to content
Merged
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ window.ga.trackEvent('Category', 'Action', 'Label', Value)// Label and Value are
window.ga.trackEvent('Category', 'Action', 'Label', Value, true)// Label, Value and newSession are optional, Value is numeric, newSession is true/false

//To track custom metrics:
window.ga.trackMetric(key, Value)// Key and value are numeric type, Value is optional
//(trackMetric doesn't actually send a hit, it's behaving more like the addCustomDimension() method.
// The metric is afterwards added to every hit (view, event, error, etc...) sent, but the defined scope of the custom metric in analytics backend
// (hit or product) will determine, at processing time, which hits are associated with the metric value.)
window.ga.trackMetric(Key, Value) // Key and value are numeric type

//To track an Exception:
window.ga.trackException('Description', Fatal)//where Fatal is boolean
Expand All @@ -91,7 +94,9 @@ window.ga.addTransaction('ID', 'Affiliation', Revenue, Tax, Shipping, 'Currency
window.ga.addTransactionItem('ID', 'Name', 'SKU', 'Category', Price, Quantity, 'Currency Code')// where Price and Quantity are numeric

//To add a Custom Dimension
window.ga.addCustomDimension('Key', 'Value', success, error)
//(The dimension is afterwards added to every hit (view, event, error, etc...) sent, but the defined scope of the custom dimension in analytics backend
// (hit or product) will determine, at processing time, which hits are associated with the dimension value.)
window.ga.addCustomDimension(Key, 'Value', success, error)
//Key should be integer index of the dimension i.e. send `1` instead of `dimension1` for the first custom dimension you are tracking. e.g. `window.ga.addCustomDimension(1, 'Value', success, error)`

//To set a UserId:
Expand Down Expand Up @@ -125,7 +130,7 @@ window.ga.debugMode()
// set's dry run mode on Android and Windows platform, so that all hits are only echoed back by the google analytics service and no actual hit is getting tracked!
// **Android quirk**: verbose logging within javascript console is not supported. To see debug responses from analytics execute
// `adb shell setprop log.tag.GAv4 DEBUG` and then `adb logcat -v time -s GAv4` to list messages
// (see [Android SDK Documentation on deprected Logger class](https://developers.google.com/android/reference/com/google/android/gms/analytics/Logger))
// (see https://developers.google.com/android/reference/com/google/android/gms/analytics/Logger)

//To enable/disable automatic reporting of uncaught exceptions
window.ga.enableUncaughtExceptionReporting(Enable, success, error)// where Enable is boolean
Expand Down Expand Up @@ -157,6 +162,9 @@ import { Platform } from 'ionic-angular';
}
```

**Issue for using trackMetric in Ionic 2**: currently `@ionic-native/google-analytics` defines the typescript signature with `trackMetric(key: string, value?: any)`.
So be aware to pass the metric index as a string formatted integer and a non empty string as a value, like `window.ga.trackMetric('1', 'Value', success, error)`!

# Installing Without the CLI <a name="nocli"></a>

Copy the files manually into your project and add the following to your config.xml files:
Expand Down Expand Up @@ -221,4 +229,7 @@ The following plugin methods are (currently) not supported by the UWP.SDKforGoog

Unexpected behaviour may occur on the following methods:
* `trackView()`: campaign details are currently not supported and therefore not tracked.
* `trackMetric()`: there is currently a bug in version 1.5.2 of the [UWP.SDKforGoogleAnalytics.Native package via NuGet](http://nuget.org/packages/UWP.SDKforGoogleAnalytics.Native),
that the wrong data specifier `cd` is taken for metrics, whereas `cm` should be the correct specifier.
So as long as this bug is not fixed, trackMetrics will overwrite previous addCustomDimension with same index!!

61 changes: 42 additions & 19 deletions android/UniversalAnalyticsPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public class UniversalAnalyticsPlugin extends CordovaPlugin {
public Boolean trackerStarted = false;
public Boolean debugModeEnabled = false;
public HashMap<Integer, String> customDimensions = new HashMap<Integer, String>();
public HashMap<Integer, Float> customMetrics = new HashMap<Integer, Float>();

public Tracker tracker;

Expand Down Expand Up @@ -177,9 +178,9 @@ private void addCustomDimension(Integer key, String value, CallbackContext callb
callbackContext.success("custom dimension started");
}

private <T> void addCustomDimensionsToHitBuilder(T builder) {
private <T> void addCustomDimensionsAndMetricsToHitBuilder(T builder) {
//unfortunately the base HitBuilders.HitBuilder class is not public, therefore have to use reflection to use
//the common setCustomDimension (int index, String dimension) method
//the common setCustomDimension (int index, String dimension) and setCustomMetrics (int index, Float metric) methods
try {
Method builderMethod = builder.getClass().getMethod("setCustomDimension", Integer.TYPE, String.class);

Expand All @@ -196,6 +197,23 @@ private <T> void addCustomDimensionsToHitBuilder(T builder) {
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}

try {
Method builderMethod = builder.getClass().getMethod("setCustomMetric", Integer.TYPE, Float.TYPE);

for (Entry<Integer, Float> entry : customMetrics.entrySet()) {
Integer key = entry.getKey();
Float value = entry.getValue();
try {
builderMethod.invoke(builder, (key), value);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
}
}

private void trackView(String screenname, String campaignUrl, boolean newSession, CallbackContext callbackContext) {
Expand All @@ -208,7 +226,7 @@ private void trackView(String screenname, String campaignUrl, boolean newSession
tracker.setScreenName(screenname);

HitBuilders.ScreenViewBuilder hitBuilder = new HitBuilders.ScreenViewBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

if(!campaignUrl.equals("")){
hitBuilder.setCampaignParamsFromUrl(campaignUrl);
Expand All @@ -234,7 +252,7 @@ private void trackEvent(String category, String action, String label, long value

if (null != category && category.length() > 0) {
HitBuilders.EventBuilder hitBuilder = new HitBuilders.EventBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

if(!newSession){
tracker.send(hitBuilder
Expand All @@ -260,21 +278,26 @@ private void trackEvent(String category, String action, String label, long value
}

private void trackMetric(Integer key, String value, CallbackContext callbackContext) {
if (!trackerStarted) {
callbackContext.error("Tracker not started");
if (key <= 0) {
callbackContext.error("Expected positive integer argument for key.");
return;
}

if (key >= 0) {
HitBuilders.ScreenViewBuilder hitBuilder = new HitBuilders.ScreenViewBuilder();
tracker.send(hitBuilder
.setCustomMetric(key, Float.parseFloat(value))
.build()
);
callbackContext.success("Track Metric: " + key + ", value: " + value);
} else {
callbackContext.error("Expected integer key: " + key + ", and string value: " + value);
if (null == value || value.length() == 0) {
callbackContext.error("Expected non-empty string argument for value.");
return;
}

Float floatValue;
try {
floatValue = Float.parseFloat(value);
} catch (NumberFormatException e) {
callbackContext.error("Expected string formatted number for value.");
return;
}

customMetrics.put(key, floatValue);
callbackContext.success("custom metric started");
}

private void trackException(String description, Boolean fatal, CallbackContext callbackContext) {
Expand All @@ -285,7 +308,7 @@ private void trackException(String description, Boolean fatal, CallbackContext c

if (null != description && description.length() > 0) {
HitBuilders.ExceptionBuilder hitBuilder = new HitBuilders.ExceptionBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

tracker.send(hitBuilder
.setDescription(description)
Expand All @@ -306,7 +329,7 @@ private void trackTiming(String category, long intervalInMilliseconds, String na

if (null != category && category.length() > 0) {
HitBuilders.TimingBuilder hitBuilder = new HitBuilders.TimingBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

tracker.send(hitBuilder
.setCategory(category)
Expand All @@ -329,7 +352,7 @@ private void addTransaction(String id, String affiliation, double revenue, doubl

if (null != id && id.length() > 0) {
HitBuilders.TransactionBuilder hitBuilder = new HitBuilders.TransactionBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

tracker.send(hitBuilder
.setTransactionId(id)
Expand All @@ -353,7 +376,7 @@ private void addTransactionItem(String id, String name, String sku, String categ

if (null != id && id.length() > 0) {
HitBuilders.ItemBuilder hitBuilder = new HitBuilders.ItemBuilder();
addCustomDimensionsToHitBuilder(hitBuilder);
addCustomDimensionsAndMetricsToHitBuilder(hitBuilder);

tracker.send(hitBuilder
.setTransactionId(id)
Expand Down
Loading