# Android SDK (client)

> Install the Ours Privacy Android SDK to capture privacy-first analytics in Android apps with event tracking and user identification.

Source: https://docs.oursprivacy.com/docs/android-sdk

Use the Ours Privacy Android SDK to track events, identify users, and collect app opens, sessions, and screens from your Android app.

* [Maven Central package](https://central.sonatype.com/artifact/com.oursprivacy/oursprivacy-android)
* [GitHub repository](https://github.com/with-ours/ours-privacy-android): full README, API reference, and release notes

## Install

Add the dependency to your app's `build.gradle` (use the latest version from [Maven Central](https://central.sonatype.com/artifact/com.oursprivacy/oursprivacy-android)):

```groovy
dependencies {
    implementation 'com.oursprivacy:oursprivacy-android:<latest>'
}
```

Make sure `mavenCentral()` is listed in your repositories block.

The SDK declares the `INTERNET` permission for you. Add `ACCESS_NETWORK_STATE` to your `AndroidManifest.xml` so the SDK holds events while the device is offline:

```xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
```

## Quick Start

Create one instance for the lifetime of your app, typically in your `Application` subclass, and initialize it with your source's API token:

```java
import com.oursprivacy.android.opmetrics.OursPrivacyAPI;
import com.oursprivacy.android.opmetrics.OursPrivacyInitOptions;
import com.oursprivacy.android.opmetrics.OursPrivacyUserProperties;

OursPrivacyAPI op = new OursPrivacyAPI(getApplicationContext());
op.initialize("YOUR_API_TOKEN", OursPrivacyInitOptions.builder().build());

op.track("Button Pressed");

// After login
op.identify(
    OursPrivacyUserProperties.builder()
        .externalId("user-123")
        .email("user@example.com")
        .build()
);
```

Events are batched and sent every 10 seconds. Call `op.flush()` to send them immediately, and `op.reset()` on logout to start a new visitor. For default properties, a custom server URL, and the rest of the API, see the [README on GitHub](https://github.com/with-ours/ours-privacy-android#readme).

### Wait for consent

If your app asks for consent first, start opted out and opt in once the person agrees:

```java
op.initialize(
    "YOUR_API_TOKEN",
    OursPrivacyInitOptions.builder()
        .optedOutByDefault(true)
        .build()
);

// When consent is granted
op.optInTracking();
```

`optedOutByDefault` applies only until a choice is saved, so a returning user keeps the choice they made. While opted out, the SDK sends nothing. `op.optOutTracking()` also clears unsent events, and the next opt-in starts a new session.

## App lifecycle and screens

Turn on automatic lifecycle tracking to fill in app opens, sessions, and engagement in [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics). It is off by default. The SDK reads your app version and build from the app's package info.

```java
op.initialize(
    "YOUR_API_TOKEN",
    OursPrivacyInitOptions.builder()
        .trackAutomaticEvents(true)
        .build()
);
```

| Event                        | When it is sent                                                       | Event-specific properties                                  |
| ---------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------- |
| `$mobile_first_open`         | First tracked app open for this installation and source               | None                                                       |
| `$mobile_app_open`           | Each tracked foreground entry                                         | None                                                       |
| `$mobile_session_start`      | First tracked open in a new session                                   | None                                                       |
| `$mobile_session_engagement` | A foreground-time checkpoint, screen change, or background transition | `engagement_duration_ms`; `screen_name` when known         |
| `$mobile_session_end`        | When an expired session is observed, when possible                    | None                                                       |
| `$mobile_app_update`         | First tracked open after the app version or build changes             | `previous_app_version` and `previous_app_build` when known |
| `$mobile_screen_view`        | Your app calls `trackScreen()` for a new visible screen               | `screen_name`                                              |

A session continues when the app returns to the foreground within 30 minutes, and counts as engaged after 10 seconds in the foreground. `$mobile_session_end` is best effort, because an app can close without warning.

Call `trackScreen()` from your navigation code when a destination appears. The SDK does not detect screens on its own, including in Compose or custom navigation.

```java
op.trackScreen("Schedule");
```

Pass a fixed label from a list in your app, such as `Schedule`: up to 80 characters, starting with a letter, using only letters, numbers, spaces, underscores, and hyphens. `trackScreen()` ignores any other label and logs a warning. Never build a label from a URL, route parameter, patient detail, or screen content.

Manual `track()` and `trackScreen()` calls work whether or not lifecycle tracking is on. Send [standard healthcare events](https://docs.oursprivacy.com/docs/standard-healthcare-events) with the same names and properties as your other sources.

Lifecycle and screen events carry device, OS, and app version details, but not your default properties or link attribution. Keep each event under 196 of your own properties and 1 MB; a larger event is still sent, but it doesn't appear in Mobile Analytics.

### Older automatic events and crashes

Automatic tracking also sends the older `$ae_first_open`, `$ae_session`, and `$ae_updated` events. They count differently from the `$mobile_*` events, so build reports and mappings on `$mobile_*`.

Crash capture is a separate option and off by default. Add `.trackAutomaticCrashes(true)` to the builder to send `$ae_crashed` events with the exception reason. Exception text can contain patient details, so review it before you turn this on.

## Web-to-app identity

When your app is opened by a link carrying `ours_visitor_id`, the SDK sets that visitor ID so later events land on the same visitor profile as their web activity. It also reads supported UTM parameters and ad-platform click IDs from the link, attaches them to the events you track afterward, and sends a `$deep_link_opened` event with those values (not the raw URL).

Hand the URL over with `op.trackDeepLink(url)`, or pass it as `initialURL` in the init options. If your app already holds the visitor ID, from a WebView or a native bridge, set it directly with `op.setVisitorId("550e8400-e29b-41d4-a716-446655440000")`. To pass the visitor ID to another SDK, such as a [mobile measurement partner](https://docs.oursprivacy.com/docs/mmp), read it with `op.getVisitorId()`.

The SDK hooks nothing in the operating system, so your activity has to hand over the URL it was opened with, on first launch and while the app is already running:

```kotlin
// MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    intent?.data?.let { op.trackDeepLink(it.toString()) }
}

override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    intent.data?.let { op.trackDeepLink(it.toString()) }
}
```

Your activity also needs an `<intent-filter>` in `AndroidManifest.xml` with the `VIEW` action and the `BROWSABLE` category, or Android never delivers the link to your app:

```xml
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https" android:host="links.example.com" />
</intent-filter>
```

On Android, the UTM parameters and click IDs from the latest link survive an app restart. A later link replaces them for later events; events already tracked keep their own values. Keep patient details out of the links you send people.

[Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution) covers how app attribution works end to end, and when you need a mobile measurement partner alongside it.

## Compatibility

* Android 6.0 (API 23) and later
* `compileSdk` 37 or later
* Java 17

## Need Help?

* [GitHub Issues](https://github.com/with-ours/ours-privacy-android/issues)
* [support@oursprivacy.com](mailto:support@oursprivacy.com)

## Next Steps

* [Client SDKs overview](https://docs.oursprivacy.com/docs/client-overview): pick the right SDK for each surface.
* [iOS SDK](https://docs.oursprivacy.com/docs/ios-sdk): the native iOS counterpart.
* [React Native SDK](https://docs.oursprivacy.com/docs/react-native-sdk) or [Flutter SDK](https://docs.oursprivacy.com/docs/flutter-sdk): if you are shipping a cross-platform mobile app.
* [Mobile app attribution](https://docs.oursprivacy.com/docs/mobile-app-attribution): how app attribution works, and when you need a mobile measurement partner.
* [Mobile Analytics](https://docs.oursprivacy.com/docs/mobile-analytics): read app opens, sessions, screens, and tracked events in the dashboard.
