Advanced usage

User ID

User ID lets you associate events from different sources with the same user. Instead of relying only on the default visitor identifier, you can set your own user identifier, such as an email address or customer ID. To set the user ID, use the setUserId method:

getTracker().setUserId("John Doe");
tracker.userId = "John Doe"
  • A UserID (required) – A non-empty unique string that identifies the user. Passing null clears the current user ID.

userID will not be sent if the data anonymization is enabled.

User email address

Used only by Audience Manager

Warning: Audience Manager is deprecated and will be replaced by Customer Data Platform module. Learn more.

The user email address is an optional identifier. Like User ID, it can help associate events from different sources with the same user. To set the user email, use the setUserMail method:

getTracker().setUserMail("[email protected]");
tracker.userMail = "[email protected]"
  • A userMail (required) – A non-null email address

userMail is not sent when data anonymization is enabled.

Setting up an email helps the Audience Manager to enrich existing profiles or merge profiles which come from other sources (if they also have an email). For more information, see Tracking user profile attributes.

Device ID

Used only by Audience Manager

The device ID is an additional, non-empty unique string that identifies the device. By default, no device ID is set. You can set it with the setDeviceId(String deviceID) method.

To set custom deviceID, use the setDeviceId(String deviceID) method:

getTracker().setDeviceId("deviceID");
tracker.deviceId = "deviceID"

You can get deviceID via getDeviceId() method:

getTracker().getDeviceId();
tracker.deviceId

deviceID will not be sent when data anonymization is enabled.

Visitor ID

To track user sessions across different sources, the Visitor ID is used. The tracker generates the visitor ID when the tracker instance is created and stores it between app launches. You can also set the visitor ID manually with setVisitorId method:

tracker.setVisitorId("0123456789abcdef");
tracker.visitorId = "0123456789abcdef"
  • A VisitorID (required) – A unique visitor ID. It must be a 16-character hexadecimal string.

When anonymization is enabled, a new visitor ID is generated each time the application starts. Each visitor must have a different ID, and the ID must not change after it is assigned. We recommend using User ID instead of Visitor ID.

Sessions

A session represents a set of user interactions with your app. By default, Analytics closes the session after 30 minutes of inactivity since the last recorded event. You can configure the tracker to close the session automatically after the app stays in the background for a specified period. Set this period with the setSessionTimeout method.

tracker.setSessionTimeout(30 * 60 * 1000);
tracker.setSessionTimeout(30 * 60 * 1000)
  • timeout (required) – The session timeout in milliseconds.

You can manually start a new session when sending an event with the startNewSession method.

tracker.startNewSession(Boolean preserveSessionParameters);
tracker.startNewSession(preserveSessionParameters)
  • preserveSessionParameters (boolean, optional) – Specifies whether campaign data, deep link data, custom dimensions, and custom variables are transferred to the next session. The default value is false.

Dispatching

Tracked events are temporarily stored in a queue and sent in batches. By default, batches are sent every 30 seconds (30000 milliseconds). You can change the behavior with the following options:

  • setDispatchInterval(0) – Events are sent immediately.
  • setDispatchInterval(-1) – Events are not sent automatically. You can send them manually with the dispatch() method.
  • dispatchInterval (number, required) – The dispatch interval in milliseconds.
Tracker tracker = ((PiwikApplication) getApplication()).getTracker();
tracker.setDispatchInterval(-1);
// Catch and track exception
try {
    cartItems = getCartItems();
} catch (Exception e) {
    TrackHelper.track().exception(e).description(e.getMessage());
    tracker.dispatch();
    cartItems = null;
}
val tracker: Tracker = (application as PiwikApplication).tracker
tracker.dispatchInterval = -1
// Catch and track exception
try {
    cartItems = getCartItems()
} catch (e: Exception) {
    TrackHelper.track().exception(e).description(e.message)
    tracker.dispatch()
    cartItems = null
}

When more than one event is in the queue, data is sent in bulk using a POST request with a JSON payload.

Custom queries

You can use the TrackHelper utility for most common actions. In some cases, you may want full control over what is sent to the server.

The base method for any event is track. You can create your own TrackMe objects, set the parameters and then send them:

TrackMe trackMe = new TrackMe();
trackMe.set...
/* ... */
Tracker tracker = ((PiwikApplication) getApplication()).getTracker();
tracker.track(trackMe);
val trackMe = TrackMe()
trackMe.set...
/* ... */
val tracker: Tracker = (application as PiwikApplication).tracker
tracker.track(trackMe)

Default custom variables

The SDK can automatically add the platform version, OS version, and app version as custom variables with indexes 1-3. This option is enabled by default. You can change it with the setIncludeDefaultCustomVars method:

getTracker().setIncludeDefaultCustomVars(false);
tracker.includeDefaultCustomVars = false

If you need to configure custom variables separately, disable this option and see the section above about tracking custom variables.

Local storage limits

You can set limits for locally stored events, including the maximum storage size and how long events are kept in local storage. Events older than the configured limit are discarded on the next dispatch attempt. By default, the Piwik PRO backend accepts backdated events for up to 24 hours.

To change offline cache age, use the setOfflineCacheAge method:

tracker.setOfflineCacheAge(80085);
tracker.offlineCacheAge = 80085
  • limit (number, required) – The time in milliseconds after which events are deleted. Use 0 for no limit and -1 to disable the offline cache. The default value is 24 * 60 * 60 * 1000 milliseconds, which equals 24 hours.

You can also set the maximum offline cache size. If the limit is reached, the oldest files will be deleted first. To change offline cache size, use the setOfflineCacheSize method:

tracker.setOfflineCacheSize(16 * 1000 * 1000);
tracker.offlineCacheSize = 16 * 1000 * 1000
  • limit (number, required) – The size in bytes after which events are deleted. Use 0 for no limit. The default value is 4 * 1024 * 1024 bytes, which equals 4 MB.

Opt out

You can enable an app-level opt-out flag to disable Piwik PRO tracking across the entire app. This flag must be set each time the app starts and defaults to false. To set the app-level opt-out, use:

getTracker().setOptOut(true);
tracker.isOptOut = true

Warning: Setting the opt-out flag clears the queue of pending events before they are sent.

Dry run

The SDK provides a dry run flag that prevents data from being sent to Piwik. Instead, the data is printed to the console. Enable dry run when testing or debugging an implementation so test data doesn’t appear in your Piwik PRO reports.

To enable dry run, use:

getTracker().setDryRunTarget(Collections.synchronizedList(new ArrayList<Packet>()));
tracker.dryRunTarget = Collections.synchronizedList(ArrayList())
  • dryRunTarget (List<Packet>, required) – The list where packets are stored during dry run. Set it to null to disable dry run.