# Events

Batch allows you to track events that happen in your application. They automatically keep track of their count, the last time it happened and their value.

> **Important**\
> Newly tracked events are hidden by default. You will need to manually display them from the dashboard settings.

### Tracking events

Events are easy to use, but have some rules:

* Event names are strings. They should be made of letters, numbers or underscores *(\[a-z0-9\_])* and can't be longer than 30 characters.
* A custom data object can be attached. See the section "Event Attributes", right under this one.
* Custom attributes have some reserved keys. See the section "Reserved event attributes" under "Event Attributes" for more info.

Here's an example:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
// Simple event
Batch.Profile.trackEvent("ad_seen")

// Event with custom attributes
Batch.Profile.trackEvent("add_to_cart", BatchEventAttributes().apply {
  // Custom attributes
  put("sub_category", "bags")
  // Compatibility reserved key
  put("\$label", "activity")
})
```

{% endtab %}

{% tab title="Java" %}

```java
// Simple event
Batch.Profile.trackEvent("ad_seen");

// Event with custom attributes
BatchEventAttributes attributes = BatchEventAttributes()
  .put("sub_category", "bags") // Custom attributes
  .put("$label", "activity");  // Compatibility reserved key

Batch.Profile.trackEvent("add_to_cart", attributes);
```

{% endtab %}
{% endtabs %}

> Please test your implementation using our [debug tool](/developer/sdk/ios/profile-data/debug.md) and [profile view](https://batch.com/getting-started/other/dashboard/01-userbase#profile-view) before releasing your app on the store.

#### Event attributes

Custom attributes can be attached to events using `BatchEventAttributes`. You will then use them when calling `Batch.Profile.trackEvent()`.

Attribute names are **strings**. They should be made of letters, numbers or underscores *(\[a-z0-9\_])* and can't be longer than 30 characters *(e.g. has\_premium)*. They will be automatically lowercased, so trying to use the same key with different casing will overwrite the previously set value.

Values must be any of the following types:

* **String** must not be longer than 300 characters and can't be empty. For better results, you should make them upper/lowercase and trim the whitespaces.
* **Float/Double**.
* **Integer/Long**.
* **Boolean**
* **Date** (using `java.util.Date`)
* **URL** (using `java.net.URI`) not longer than 2048 characters and must follow the format `scheme://[authority][path][?query][#fragment]`
* **List\<String | BatchEventAttributes>**, You can set array of strings (max 300 chars) and array of objects. Max 25 items. You cannot mix several attribute types in one array. Arrays can't be nested.
* **Object** (using `BatchEventAttributes`, Objects cannot have more than 3 levels of nesting.

{% hint style="info" %}
Setting a value for an existing key will overwrite it. Any attempt to add an invalid attribute will fail and the event will **NOT** be tracked. You can use the `validateEventAttributes` method which return a list of human-readable errors to ensure your event is valid before sending it.
{% endhint %}

**Reserved event attributes**

Some event attributes have reserved keys, and are all prefixed by a `$` sign. This is the list of currently reserved event attributes. You cannot set an event attribute starting by a *$* sign.

<table><thead><tr><th width="99.2265625">Key</th><th>Description</th></tr></thead><tbody><tr><td><code>$label</code></td><td><p><strong>String</strong> - <em>Optional</em></p><p>Event label. Must be a string, will automatically be bridged as label for application event compatibility. Max 200 chars.</p></td></tr><tr><td><code>$tags</code></td><td><p><strong>NSArray</strong> - Optional</p><p>Event tags. Must be an array of string, will automatically be bridged as tags for application event compatibility. Max 10 items of type string, each no longer than 64chars. The SDK will automatically lowercase them, so two same strings with different casing do not count as two different tags</p></td></tr></tbody></table>

In Batch SDK v1 you were able to set a *label* and *tags* at the root of an event, with the limit of 1 label and 10 tags.

Batch SDK v2 introduced Object and Array types in event attributes. You can set more than one array on profiles events. This is only supported for profiles, and not on the install-centric data model, which currently powers push notification and In-App messages.

However, it's still possible to set a label and tags on events in the install-centric data model by using `$label` and `$tags`, and activate compatibility flows. This way, you will be able to use this data for your push and in-app communications.

{% hint style="warning" %}
If you are not running any orchestrations on the Mobile Engagement Platform (MEP), you should use String and Array attributes instead of legacy `$label` and `$tags.`
{% endhint %}

**Example**

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
val attributes = BatchEventAttributes().apply {
  put("sub_category", "man_clothes")
  put("end_of_sale_date", Date(1713432899086L))
  putObjectList("items_list",
    listOf(
      BatchEventAttributes().apply {
        put("name", "Basic Tee")
        put("size", "M")
        put("price", 23.99)
        put("item_url", URI("https://batch-store.com/basic-tee"))
        put("item_image", URI("https://batch-store.com/basic-tee/black/image.png"))
        put("in°sales", true)
      },
      BatchEventAttributes().apply {
        put("name", "Short socks pack x3")
        put("size", "38-40")
        put("price", 15.99)
        put("item_url", URI("https://batch-store.com/short-socks-pack-x3"))
        put("item_image", URI("https://batch-store.com/short-socks-pack-x3/image.png"))
        put("in_sales", false)
      },
    )
  )
  put("\$label", "accessories")
  putStringList("\$tags", listOf("first_purchase", "in_promo"))
}

val errors = attributes.validateEventAttributes()
if (errors.isEmpty()) {
  Batch.Profile.trackEvent("validated_purchase", attributes)
} else {
  Log.w("Events", errors.toString())
}
```

{% endtab %}

{% tab title="Java" %}

```java
BatchEventAttributes attributes = new BatchEventAttributes()
  .put("sub_category", "man_clothes")
  .put("end_of_sale_date", new Date(1713432899086L))
  .putObjectList("items_list", Arrays.asList(
    new BatchEventAttributes() {{
      put("name", "Basic Tee");
      put("size", "M");
      put("price", 23.99);
      put("item_url", URI.create("https://batch-store.com/basic-tee"));
      put("item_image", URI.create("https://batch-store.com/basic-tee/black/image.png"));
      put("in_sales", true);
    }},
    new BatchEventAttributes() {{
      put("name", "Short socks pack x3");
      put("size", "38-40");
      put("price", 15.99);
      put("item_url", URI.create("https://batch-store.com/short-socks-pack-x3"));
      put("item_image", URI.create("https://batch-store.com/short-socks-pack-x3/image.png"));
      put("in_sales", false);
    }}
  ))
  .put("$label", "accessories")
  .putStringList("$tags", Arrays.asList("first_purchase", "in_promo"));

List<String> errors = attributes.validateEventAttributes();
if (errors.isEmpty()) {
  Batch.Profile.trackEvent("validated_purchase", attributes);
} else {
  Log.w("Events",errors.toString());
}
```

{% endtab %}
{% endtabs %}

### Tracking user location

You can natively track a user location. This uses Android's standard Location object, which you usually get from the Location Service or Fused Location API. You can also instanciate one manually from a latitude/longitude.

Here's an example:

{% tabs %}
{% tab title="Kotlin" %}

```kotlin
override fun onLocationChanged(location: Location?) {
    location?.let {
        Batch.Profile.trackLocation(location)
    }
}
```

{% endtab %}

{% tab title="Java" %}

```java
@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        Batch.Profile.trackLocation(location);
    }
}
```

{% endtab %}
{% endtabs %}

This data will allow you to send [geo-targeted push notifications](https://doc.batch.com/getting-started/features/mobile-engagement-platform/push/user-targeting#last-location) from the dashboard or the Campaigns API.

{% hint style="info" %}
The SDK will throttle location tracking to optimize network and battery usage. You can track one location event every 30 seconds, any attempt at updating the location sooner will be ignored by the SDK.
{% endhint %}

### Background events

Sending events from the background is supported on Android using a `Service`.

To do so, call `Batch.onServiceCreate()` and `Batch.onServiceDestroy()` in your service's lifecycle methods. Standard Batch event tracking methods will automatically work.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.batch.com/developer/sdk/android/profile-data/events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
