Android (0.4.0)
Tracker#
1. Overview#
The Snowplow Android Tracker allows you to track Snowplow events from your Android applications and games. It supports applications using the Android SDK 11 and above.
The tracker should be straightforward to use if you are comfortable with Java development; its API is modelled after Snowplow's Python Tracker so any prior experience with that tracker is helpful but not necessary. If you haven't already, have a look at the Android Tracker Setup guide before continuing.
1.1. Demo App#
If you would like to see the Tracker in action you can download our demonstration android app here. You will need to enable installation of applications from unknown sources.
Within the app you will simply need to supply an endpoint and hit start! The application will then send all types of events available to the tracker to this endpoint.
For a walkthrough go here.
2 Initialization#
Assuming you have completed the Android Tracker Setup for your project, you are now ready to initialize the Android Tracker.
2.1 Importing the module
Import the Android Tracker's classes into your Android code like so:
import com.snowplowanalytics.snowplow.tracker.*;
That's it - you are now ready to initialize a Tracker instance.
2.2 Creating a Tracker
To instantiate a tracker in your code (can be global or local to the process being tracked) simply instantiate the Tracker interface with one of the following:
// Create an Emitter
Emitter e1 = new Emitter
.EmitterBuilder("com.collector.acme", getContext())
.build();
// Make and return the Tracker object
Tracker t1 = new Tracker
.TrackerBuilder(e1, "myNamespace", "myAppId")
.build();
This is the most basic Tracker creation possible. Note that getContext() is an Android global function. You can expand on this creation with the following builder options:
// Create an Emitter
Emitter e2 = new Emitter
.EmitterBuilder("com.collector.acme", getContext())
.build();
// Create a Tracker with all options
Tracker t2 = new Tracker
.TrackerBuilder(e2, "myNamespace", "myAppId")
.base64(false) // Optional - defines if we use base64 encoding
.platform(DevicePlatforms.Mobile) // Optional - defines what platform the event will report to be on
.subject(new Subject.SubjectBuilder().build()) // Optional - a subject which contains values appended to every event
.build();
As you can see there is a fair amount of modularity to the Trackers creation.
The below are required arguments for the TrackerBuilder({{ ... }}) segment of the constructor:
| Argument Name | Description | Required? |
|---|---|---|
emitter | The emitter which sends the events | Yes |
namespace | The name of the tracker instance | Yes |
appId | The application ID | Yes |
We also have several extra builder options:
| Function | Description | Options | Default |
|---|---|---|---|
subject | The subject that defines a user | Subject, null | null |
platform | The platform that the Tracker is running on | DevicePlatforms.{{ Enum Option }} | DevicePlatforms.Mobile |
base64 | Whether to enable Base64 encoding | True, False | True |
level | The level of logging to do | LogLevel.{{ Enum Option}} | LogLevel.OFF |
2.3.1 emitter
The emitter to which the tracker will send events. See Emitters for more on emitter configuration.
2.3.2 subject
The user which the Tracker will track. This should be an instance of the Subject class. You don't need to set this during Tracker construction; you can use the Tracker.setSubject method afterwards. In fact, you don't need to create a subject at all. If you don't, though, your events won't contain user-specific data such as timezone and language.
2.3.3 namespace
If provided, the namespace argument will be attached to every event fired by the new tracker. This allows you to later identify which tracker fired which event if you have multiple trackers running.
2.3.4 appId
The appId argument lets you set the application ID to any string.
2.3.5 base64
By default, unstructured events and custom contexts are encoded into Base64 to ensure that no data is lost or corrupted. You can turn encoding on or off using the Boolean base64Encoded argument.
2.3.6 platform
The 'platform' allows you to pick from a list of allowed platforms which define what type of device/service the event is being sent from.
2.3.7 Change the tracker's platform with setPlatform
You can change the platform by calling:
tracker.setPlatform(DevicePlatforms.Mobile);
// OR
tracker.setPlatform(DevicePlatforms.Desktop);
// OR
tracker.setPlatform(DevicePlatforms.{{ Valid Enum Option }})
There are several different DevicePlatforms options to choose from.
For a full list of supported platforms, please see the Snowplow Tracker Protocol.
2.3.8 Change the tracker's subject with setSubject
You can change the subject by creating a new Subject object and then calling:
tracker.setSubject(newSubject);
See Adding extra data: the Subject class for more information on the Subject.
2.3.9 Change the tracker's emitter with setEmitter
You can change the emitter by creating a new Emitter object and then calling:
tracker.setEmitter(newEmitter);
3. Adding extra data: the Subject class#
You may have additional information about your application's environment, current user and so on, which you want to send to Snowplow with each event. The Subject appended to the Tracker allows you to easily add information to each event that is sent from the Tracker.
3.1 Subject setter functions#
The Subject class has a set of set...() methods to attach extra data relating to the user to all tracked events:
setUserIdsetScreenResolutionsetViewportsetColorDepthsetTimezonesetLanguagesetIpAddresssetUseragentsetNetworkUserIdsetDomainUserId
Here are some examples:
Subject s1 = new Subject.SubjectBuilder().build();
s1.setUserID("Kevin Gleason");
s1.setLanguage("en-gb");
s1.setScreenResolution(1920, 1080);
After that, you can add your Subject to your Tracker like so:
Tracker t1 = new Tracker
.TrackerBuilder(emitter, "myNamespace", "myAppId")
.subject(s1) // Include your subject here!
.build();
// Or you can set the subject after creation
// This will also override any currently set Subject object
t1.setSubject(s1);
To update the Trackers subject without changing the subject attached already you can use the following:
t1.getSubject().setUserId("Gleason Kevin"); // Because object references are passed by value in Java
3.1.1 Set user ID with setUserId
You can set the user ID to any string:
setUserId(String userId)
Example:
subj.setUserId("alexd");
3.1.2 Set screen resolution with setScreenResolution
If your Java code has access to the device's screen resolution, then you can pass this in to Snowplow too:
setScreenResolution(int width, int height)
Both numbers should be positive integers; note the order is width followed by height. Example:
subj.setScreenResolution(1366, 768);
3.1.3 Set viewport dimensions with setViewport
If your Java code has access to the viewport dimensions, then you can pass this in to Snowplow too:
setViewport(int width, int height)
Both numbers should be positive integers; note the order is width followed by height. Example:
subj.setViewport(300, 200);
3.1.4 Set color depth with setColorDepth
If your Java code has access to the bit depth of the device's color palette for displaying images, then you can pass this in to Snowplow too:
setColorDepth(int depth)
The number should be a positive integer, measured in bits per pixel. Example:
subj.setColorDepth(32);
3.1.5 Set timezone with setTimezone
This method lets you pass a user's timezone in to Snowplow:
setTimezone(String timezone)
The timezone should be a string:
subj.setTimezone("Europe/London");
3.1.6 Set the language with setLanguage
This method lets you pass a user's language in to Snowplow:
setLanguage(String language)
The language should be a string:
subj.setLanguage("en");
3.1.7 setIpAddress#
This method lets you pass a user's IP Address in to Snowplow:
setIpAddress(String ipAddress)
The IP address should be a string:
subj.setIpAddress("127.0.0.1");
3.1.8 setUseragent#
This method lets you pass a useragent in to Snowplow:
setUseragent(String useragent)
The useragent should be a string:
subj.setUseragent("Agent Smith");
3.1.9 setNetworkUserId#
This method lets you pass a Network User ID in to Snowplow:
setNetworkUserId(String networkUserId)
The network user id should be a string:
subj.setNetworkUserId("network-id");
3.1.10 setDomainUserId#
This method lets you pass a Domain User ID in to Snowplow:
setDomainUserId(String domainUserId)
The domain user id should be a string:
subj.setDomainUserId("domain-id");
3.2 Additional contexts sent by this tracker#
This Tracker not only appends the generic subject information to each event; it will also attempt to gather more specific information about the mobile it is hosted on.
3.2.1 mobile_context#
The mobile_context is comprised of the following fields:
androidIdfa-> The host phones unique AdvertisingIdcarrier-> The host phones phones network carrierdeviceModel-> The host phones phones modeldeviceManufacturer-> The host phones phones manufacturerosVersion-> The host phones phones operating system versionosType-> The host phones phones operating system type
To ensure you gather all of this information you will need to create your Subject with the following argument:
Subject subject = new Subject.SubjectBuilder().context(getContext()).build();
Note that getContext() is an Android global function. It is needed to grab information that is related to the client specifically.
3.2.2 geolocation_context#
The geolocation_context is comprised of the following fields:
latitude-> The host phones latitude measurelongitude-> The host phones longitude measurealtitude-> The host phones altitude measurelatitudeLongitudeAccuracy-> The host phones position accuracyspeed-> The host phones speedbearing-> The host phones current bearing
To ensure you gather all of this information you will need to create your Subject with the following argument:
Subject subject = new Subject.SubjectBuilder().context(getContext()).build();
Note that getContext() is an Android global function.
You will also need to include the following in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
This will make the functions for checking these metrics available for the tracker to use.
3.3 Getting the Android Idfa Code#
The Android Idfa code is a unique identifier for google advertising. You can get this code using this library in two ways:
- Use the utility function available:
import com.snowplowanalytics.snowplow.tracker.utils.Util;
// Context is your application context object
String androidIdfa = Util.getAdvertisingId(context);
Please note that this function will only work when run from a different thread than the UI/Main thread of your application.
- Get it from the Subject class:
If you created a Tracker Subject with your application's context then the ID will have already been populated.
String androidIdfa = tracker.getSubject().getSubjectMobile().get("androidIdfa");
4. Tracking specific events#
Snowplow has been built to enable you to track a wide range of events that occur when users interact with your websites and apps. We are constantly growing the range of functions available in order to capture that data more richly.
Tracking methods supported by the Android Tracker at a glance:
| Function | *Description |
|---|---|
trackScreenView() | Track the user viewing a screen within the application |
trackPageView() | Track and record views of web pages. |
trackEcommerceTransaction() | Track an ecommerce transaction and its items |
trackStructuredEvent() | Track a Snowplow custom structured event |
trackUnstructuredEvent() | Track a Snowplow custom unstructured event |
4.1 Common
All events are tracked with specific methods on the tracker instance, of the form trackXXX(), where XXX is the name of the event to track.
4.1.1 SelfDescribingJson
A SelfDescribingJson is used as a wrapper around either a TrackerPayload, another SelfDescribingJson or a Map object. After creating the object you want to wrap, you can create a SelfDescribingJson using the following:
// This is the Map we have created
Map<String, String> eventData = new HashMap<>();
eventData.put("Event", "Data")
// We wrap that map in a SelfDescribingJson before sending it
SelfDescribingJson json = new SelfDescribingJson("iglu:com.acme/example/jsonschema/1-0-0", eventData);
You can create a SelfDescribingJson with the following arguments:
| Argument | Description | Required? | Type |
|---|---|---|---|
schema | JsonSchema that describes the data | Yes | String |
data | Data that will be validated by the schema | No | Map<String, String>, Map<String, Object>, TrackerPayload, SelfDescribingJson |
SelfDescribingJson is used for recording custom contexts and unstructured events.
4.1.2 Custom contexts
In short, custom contexts let you add additional information about the circumstances surrounding an event in the form of a Map object. Each tracking method accepts an additional optional contexts parameter after all the parameters specific to that method:
t1.trackPageView(String pageUrl, String pageTitle, String referrer);
t1.trackPageView(String pageUrl, String pageTitle, String referrer, List<SelfDescribingJson> context);
t1.trackPageView(String pageUrl, String pageTitle, String referrer, double timestamp);
t1.trackPageView(String pageUrl, String pageTitle, String referrer, List<SelfDescribingJson> context, double timestamp);
The context argument should consist of a List of SelfDescribingJson representing an array of one or more contexts. The format of each individual context element is the same as for an unstructured event.
If a visitor arrives on a page advertising a movie, the context dictionary might look like this:
{
"schema": "iglu:com.acme_company/movie_poster/jsonschema/2.1.1",
"data": {
"movie_name": "Solaris",
"poster_country": "JP",
"poster_year": "1978"
}
}
To construct this as a SelfDescribingJson:
// Create a Map of the data you want to include...
Map<String, String> dataMap = new HashMap<>();
dataMap.put("movie_name", "solaris");
dataMap.put("poster_country", "JP");
dataMap.put("poster_year", "1978");
// Now create your SelfDescribingJson object...
SelfDescribingJson context1 = new SelfDescribingJson("iglu:com.acme/movie_poster/jsonschema/2.1.1", dataMap);
// Now add this JSON into a list of SelfDescribingJsons...
List<SelfDescribingJson> contexts = new ArrayList<>();
contexts.add(context1);
Note that even if there is only one custom context attached to the event, it still needs to be placed in an array.
4.1.3 Timestamp override
In all the trackers, we offer a way to override the timestamp if you want the event to show as tracked at a specific time. If you don't, we create a timestamp while the event is being tracked.
Here are some example:
t1.trackPageView("www.page.com", "Example Page", "www.referrer.com");
t1.trackPageView("www.page.com", "Example Page", "www.referrer.com", contexts);
t1.trackPageView("www.page.com", "Example Page", "www.referrer.com", contexts, 1423583655000);
t1.trackPageView("www.page.com", "Example Page", "www.referrer.com", 1423583655000);
4.2 Track screen views with trackScreenView()
Use trackScreenView() to track a user viewing a screen (or equivalent) within your app. Arguments are:
| Argument | Description | Required? | Type |
|---|---|---|---|
name | Human-readable name for this screen | No | String |
id | Unique identifier for this screen | No | String |
context | Custom context for the event | No | List<SelfDescribingJson> |
timestamp | Optional timestamp for the event | No | Long |
Examples:
t1.trackScreenView("HUD > Save Game", "screen23");
t1.trackScreenView("HUD > Save Game", contextList, 1423583655000);