Skip to Content
AI Powered Docs! 🤖 These docs are translated with AI, so keep an eye out for minor quirks. We're always improving!

Event Tracking

The Metrix SDK allows you to track user interactions as events in your application. Events provide statistical data about user behavior, engagement, and revenue.

Event Types

The Metrix SDK supports two types of events:

  1. Custom Events — Track any user interaction defined by your application logic
  2. Revenue Events — Track financial transactions with measurable revenue values

Creating Custom Events

Event Registration

Custom events should first be registered in your Metrix panel under Event Management. Use the event slug (identifier) in your application code.

Recording Custom Events by Slug

To record a custom event using its slug defined in the Metrix panel:

Native & Webview
MetrixAnalytics.newEvent("my_event_slug");

Recording Custom Events by Custom Name

To record a custom event using a custom name (an event with a unique slug is automatically created in the panel):

Native & Webview
MetrixAnalytics.newEventByName("my_event_name");

Recording Events with Attributes

Events can include associated attributes to provide additional context:

Map<String, Object> attributes = new HashMap<>(); attributes.put("product_name", "shirt"); attributes.put("purchase_date", "2024-11-20T11:24:03.000Z"); // use ISO 8601 to consider this attribute as s a date
Native & Webview
MetrixAnalytics.newEvent("purchase_event_slug", attributes); // OR MetrixAnalytics.newEventByName("purchase_event_name", attributes);

// Using slug MetrixAnalytics.newEvent(‘purchase_event_slug’, JSON.stringify(attributes));

// Using custom name MetrixAnalytics.newEventByName(‘purchase_event_name’, JSON.stringify(attributes));

### Event Attribute Guidelines - **Maximum attributes per event:** 50 - **Maximum key length:** 512 bytes - **Maximum value length:** 512 bytes - **Supported types:** String, Number, Boolean, Date (ISO 8601 format) > **Tip:** Use ISO 8601 format for date attributes (e.g., `2024-11-20T11:24:03.000Z`) so Metrix correctly recognizes them as dates in the platform. ### Common Event Examples #### E-commerce Purchase Event ```java Map<String, Object> attributes = new HashMap<>(); attributes.put("order_id", "ORD-12345"); attributes.put("product_ids", "PROD-001,PROD-002"); attributes.put("quantity", 2); attributes.put("subtotal", 1500.00); attributes.put("tax", 150.00); attributes.put("total", 1650.00); attributes.put("coupon_applied", true); attributes.put("coupon_code", "SAVE10"); MetrixAnalytics.newEvent("checkout_complete", attributes);

User Registration Event

Map<String, Object> attributes = new HashMap<>(); attributes.put("registration_method", "email"); attributes.put("signup_date", "2024-11-20T11:24:03.000Z"); attributes.put("referral_source", "app_store"); MetrixAnalytics.newEventByName("user_signup", attributes);

Content Consumption Event

Map<String, Object> attributes = new HashMap<>(); attributes.put("content_id", "ARTICLE-001"); attributes.put("content_title", "Getting Started with Analytics"); attributes.put("content_category", "tutorial"); attributes.put("reading_time_seconds", 180); attributes.put("scroll_depth", 85); MetrixAnalytics.newEvent("content_viewed", attributes);

In-app Action Event

Map<String, Object> attributes = new HashMap<>(); attributes.put("button_name", "Share Button"); attributes.put("share_destination", "facebook"); attributes.put("content_id", "POST-001"); MetrixAnalytics.newEventByName("content_shared", attributes);

Creating Revenue Events

Recording Revenue Events by Slug

To record a revenue event using its slug with default currency (IRR):

MetrixAnalytics.newRevenue("purchase_slug", 50000.0);

Recording Revenue Events with Currency

To record a revenue event with a specific currency:

// Supported currencies: IRR, USD, EUR MetrixAnalytics.newRevenue("purchase_slug", 50000.0, RevenueCurrency.IRR); MetrixAnalytics.newRevenue("purchase_slug", 100.0, RevenueCurrency.USD); MetrixAnalytics.newRevenue("purchase_slug", 85.0, RevenueCurrency.EUR);

Recording Revenue Events by Custom Name

To record a revenue event using a custom name:

// With default currency (IRR) MetrixAnalytics.newRevenueByName("in_app_purchase", 50000.0); // With specific currency MetrixAnalytics.newRevenueByName("in_app_purchase", 100.0, RevenueCurrency.USD);

Revenue Event Parameters

ParameterTypeDescription
slug/nameStringEvent identifier (slug) or custom event name
revenueDoubleNumeric value representing the revenue amount
currencyRevenueCurrency / StringCurrency code: IRR (default), USD, or EUR

Revenue Event Examples

In-app Purchase

// User purchases a subscription double subscriptionPrice = 99.99; MetrixAnalytics.newRevenue("subscription_purchase", subscriptionPrice, RevenueCurrency.USD);

In-app Item Purchase

// User buys virtual currency Map<String, Object> attributes = new HashMap<>(); attributes.put("item_type", "virtual_currency"); attributes.put("item_name", "Gold Coins"); attributes.put("quantity", 1000); attributes.put("unit_price", 9.99); MetrixAnalytics.newRevenue("virtual_item_purchase", 9.99, RevenueCurrency.USD);

Multiple Currency Example

// Handle different user currencies String userCurrency = getUserCurrency(); // "USD", "EUR", "IRR" double amount = getConvertedAmount(userCurrency); MetrixAnalytics.newRevenue("purchase", amount, RevenueCurrency.valueOf(userCurrency));

Subscription Renewal

// Track recurring revenue double renewalAmount = 199.99; MetrixAnalytics.newRevenueByName("subscription_renewal", renewalAmount, RevenueCurrency.USD);

Event Tracking Best Practices

1. Use Consistent Event Names

Maintain consistent event naming across all app versions to ensure continuity in analytics:

// Good: Consistent naming MetrixAnalytics.newEvent("checkout_complete"); MetrixAnalytics.newEvent("checkout_complete", attributes); // Bad: Changing event names MetrixAnalytics.newEvent("checkout_complete"); // v1 MetrixAnalytics.newEvent("purchase_complete"); // v2 - Different tracking

2. Event Timing

Record events immediately after the user interaction occurs:

// Good: Event recorded after successful action if (submitForm()) { MetrixAnalytics.newEvent("form_submitted"); } // Bad: Event recorded before validation MetrixAnalytics.newEvent("form_submitted"); submitForm(); // May fail

3. Handle Failures Gracefully

Always check for successful completion before recording events:

// Good: Only record on success ApiResponse response = makeApiCall(); if (response.isSuccessful()) { MetrixAnalytics.newEvent("api_call_successful"); } else { MetrixAnalytics.newEvent("api_call_failed"); }

4. Batch Attribute Updates

Group related attributes in a single event rather than multiple events:

// Good: All data in one event Map<String, Object> attributes = new HashMap<>(); attributes.put("category", "electronics"); attributes.put("brand", "Samsung"); attributes.put("price", 999.99); MetrixAnalytics.newEvent("product_viewed", attributes); // Bad: Multiple events for related data MetrixAnalytics.newEvent("product_category_viewed"); MetrixAnalytics.newEvent("product_brand_viewed"); MetrixAnalytics.newEvent("product_price_viewed");

5. Avoid Personally Identifiable Information (PII)

Do NOT include PII in event attributes:

// Bad: Contains PII Map<String, Object> attributes = new HashMap<>(); attributes.put("user_name", "John Doe"); // ✗ PII attributes.put("email", "john@example.com"); // ✗ PII attributes.put("phone", "989123456789"); // ✗ PII // Good: Use user tracking methods instead MetrixAnalytics.User.setFirstName("John"); MetrixAnalytics.User.setEmail("john@example.com"); // Event attributes with non-PII data Map<String, Object> attributes = new HashMap<>(); attributes.put("user_type", "premium"); // ✓ Non-PII attributes.put("registration_age_days", 365); // ✓ Non-PII

6. Limit High-Frequency Events

Avoid tracking extremely high-frequency events (e.g., every pixel scroll):

// Bad: Too frequent onScroll(() -> MetrixAnalytics.newEvent("scroll")); // Good: Track meaningful milestones if (scrollPercentage == 25) { MetrixAnalytics.newEvent("scroll_25_percent"); } if (scrollPercentage == 50) { MetrixAnalytics.newEvent("scroll_50_percent"); }

7. Use Correct Revenue Currency

Always specify the correct currency to ensure accurate revenue reporting:

// Get user's currency preference or app setting String userCurrency = preferenceManager.getCurrency(); // Record with correct currency MetrixAnalytics.newRevenue("purchase", amount, RevenueCurrency.valueOf(userCurrency));

WebView Integration

The Metrix SDK automatically synchronizes event tracking between native and JavaScript code when using the WebView bridge.

Setup

public class WebViewActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webView = findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); // Register analytics bridge MetrixAnalyticsBridge.registerAndGetInstance(webView); webView.loadUrl("file:///android_asset/page.html"); } }

JavaScript Example

<!DOCTYPE html> <html> <head> <script type="text/javascript" src="metrix_analytics.js"></script> </head> <body> <script> // Simple event document.getElementById('buyBtn').onclick = function() { MetrixAnalytics.newEvent('purchase_clicked'); }; // Event with attributes document.getElementById('shareBtn').onclick = function() { var attrs = { 'platform': 'facebook', 'content_id': 'POST-001' }; MetrixAnalytics.newEvent('content_shared', JSON.stringify(attrs)); }; // Revenue event document.getElementById('subscribeBtn').onclick = function() { MetrixAnalytics.newRevenue('subscription_purchase', 99.99, 'USD'); }; </script> </body> </html>

Event Delivery Guarantees

  • Custom Events: Sent with WHENEVER priority - queued when offline, sent when online
  • Revenue Events: Sent with WHENEVER priority - ensures no revenue data is lost
  • System Events: Sent with IMMEDIATE priority - sent before batching with other events

Event Limits and Throttling

  • Maximum attributes per event: 50
  • Maximum attribute key length: 512 bytes
  • Maximum attribute value length: 512 bytes
  • No per-event rate limiting - send events as needed, but avoid high-frequency events (see best practices)