> ## Documentation Index
> Fetch the complete documentation index at: https://docu.truemetrics.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# Android Native Integration

> Complete guide for integrating Truemetrics SDK 1.6.3 into Android applications

The Truemetrics SDK provides advanced sensor data collection and analytics capabilities for Android
applications. This guide covers all aspects of integrating and using the SDK effectively.

## Table of Contents

* [Installation](#installation)
* [Quick Start](#quick-start)
* [Initialization Lifecycle](#initialization-lifecycle)
* [Configuration](#configuration)
* [Core Features](#core-features)
* [SDK Status](#sdk-status)
* [Statistics API](#statistics-api)
* [Best Practices](#best-practices)
* [API Reference](#api-reference)

***

## Installation

Add the following to your root-level `build.gradle` file (or `settings.gradle`):

```gradle theme={null}
repositories {
    maven {
        url "https://github.com/TRUE-Metrics-io/truemetrics_android_SDK_p_maven/raw/main"
    }
}
```

Then add the dependency to your app-level `build.gradle`:

```gradle theme={null}
dependencies {
    implementation 'io.truemetrics:truemetricssdk:1.6.3'
}
```

> [!NOTE]
>
> **Google Play foreground-service declaration (SDK 1.5.7+):** the SDK's recording service declares the
> **`location`** and **`dataSync`** foreground-service types (previously `location` + `specialUse`). In the
> Play Console foreground-service-types form, declare **"Location"** and **"Data sync"** for the Truemetrics
> recording service (and the optional sensor-watchdog service, if enabled). If your existing declaration
> listed **"Special use"** for a Truemetrics service, replace it with **"Data sync"** (keep **"Location"**).

## Quick Start

### 1. Initialize the SDK in your Application class

```kotlin theme={null}
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        val config = SdkConfiguration.Builder("YOUR_API_KEY").build()
        TruemetricsSdk.init(this, config)
    }
}
```

### 2. Start and stop recordings

```kotlin theme={null}
val sdk = TruemetricsSdk.getInstance()

// Start recording sensor data
sdk.startRecording()

// Stop recording
sdk.stopRecording()

// Check recording status
if (sdk.isRecordingInProgress()) {
    // Recording is active
}
```

***

## Initialization Lifecycle

`TruemetricsSdk.init()` returns immediately but the SDK is **not ready for use until it reaches `Status.Initialized`**. Initialization runs asynchronously in the background: it binds a foreground service, then fetches the configuration from the backend.

### State Transitions

```
Uninitialized ──► Initializing ──► Initialized
                       │
                       ├──► Error(AUTHENTICATION_ERROR)   (invalid/expired/revoked API key)
                       │
                       ├──► Error(FOREGROUND_SERVICE_START_REFUSED) ──► Initialized
                       │    (init() ran in the background; the SDK retries when
                       │     the app's UI comes to the foreground)
                       │
                       └──► stays in Initializing, retrying every 30s
                            (network unreachable, 5xx from backend, timeouts)
```

### How Long To Wait

| Condition | Typical time to `Initialized` |
| - | - |
| Good network | 1–3 seconds |
| Slow/lossy network | up to tens of seconds |
| Backend 5xx or offline | indefinite — retries every 30 seconds until it succeeds |
| Invalid API key | fails fast (under \~2 seconds) with `Status.Error(AUTHENTICATION_ERROR)` |

> [!NOTE]
>
> There is no hard timeout on initialization. Under poor connectivity the SDK stays in `Status.Initializing` and keeps retrying. Do not impose an arbitrary client-side timeout — either wait for `Status.Initialized` or a `Status.Error` whose `errorCode` is not `FOREGROUND_SERVICE_START_REFUSED` (that one clears itself, see below), or gate UI on `getDeviceId()` becoming non-null.

### Checking Initialization Status

**Recommended — observe the status flow and wait for `Status.Initialized`:**

```kotlin theme={null}
import io.truemetrics.truemetricssdk.engine.ErrorCode
import io.truemetrics.truemetricssdk.engine.state.Status
import kotlinx.coroutines.flow.first

suspend fun awaitSdkReady(): String {
    val sdk = TruemetricsSdk.getInstance()
    val ready = sdk.observeSdkStatus().first { status ->
        status is Status.Initialized ||
        status is Status.RecordingInProgress ||
        status is Status.DelayedStart ||
        // Not a failure: Android refused the foreground service because the app was
        // in the background. The SDK retries when the UI appears, so keep waiting.
        (status is Status.Error &&
            status.errorCode != ErrorCode.FOREGROUND_SERVICE_START_REFUSED)
    }
    if (ready is Status.Error) {
        throw IllegalStateException("SDK init failed: ${ready.errorCode} ${ready.message}")
    }
    return sdk.getDeviceId()!!
}
```

> [!WARNING]
>
> If your app has no UI — headless, or driven by an MDM — it never comes to the foreground,
> so the SDK gets no chance to retry. Call `deinitialize()` and then `init()` again from a
> context Android allows, such as a receiver it exempts, and then `startRecording()` again —
> `deinitialize()` drops a pending request.

**Non-blocking — react to state changes as they arrive:**

```kotlin theme={null}
sdk.observeSdkStatus().collect { status ->
    when (status) {
        is Status.Initializing -> showSpinner()
        is Status.Initialized -> enableStartButton(status.deviceId)
        is Status.Error -> showError(status.errorCode, status.message)
        else -> {}
    }
}
```

**Quick synchronous check** — `getDeviceId()` returns `null` until initialization completes:

```kotlin theme={null}
if (sdk.getDeviceId() != null) {
    // SDK is initialized
}
```

### Calling Other APIs Before Initialization Completes

* `startRecording()` — safe to call immediately after `init()`. The request is kept and runs once the service is up: both while the service is still binding, and when Android refused to start it. If initialization failed for some other reason, the call reports `Status.Error(CONFIG_ERROR)` — or leaves a more specific error in place, if one is already reported. If the SDK was never initialized, it reports `Status.Error(NOT_INITIALIZED)`. To avoid these, wait for `Status.Initialized`, or configure an auto-start (see [Recording lifecycle](#recording-lifecycle)).
* `logMetadata()` — ignored with a log warning if called before initialization. Wait for `Status.Initialized` before logging.
* `getDeviceId()`, `getActiveConfig()`, `getUploadStatistics()`, `getSensorStatistics()` — return `null` until initialization completes.

### Terminal vs. Transient Failures

| Status | Meaning | Your action |
| - | - | - |
| `Status.Initializing` (stuck) | Backend unreachable or returning 5xx; SDK auto-retries every 30s | Wait, or surface a "connecting" indicator. No need to call `init()` again. |
| `Status.Error(AUTHENTICATION_ERROR)` | API key invalid, expired, or revoked. SDK has deinitialized itself. | Do **not** retry with the same key. Fix the key, then call `init()` again. |
| `Status.Error(CONFIG_ERROR)` | `startRecording()` was called before config was loaded | Await `Status.Initialized` before calling `startRecording()`. |
| `Status.Error(NOT_INITIALIZED)` | `startRecording()` was called without an initialized SDK — before `init()`, or after `deinitialize()` | Call `init()` first. The request is not held; call `startRecording()` again once initialized. |
| `Status.Error(MISSING_NOTIFICATION_PERMISSION)` | Android 13+ notification permission not granted | Request `POST_NOTIFICATIONS`, then re-init. |
| `Status.Error(FOREGROUND_SERVICE_START_REFUSED)` | **Transient.** `init()` ran in the background, where Android refuses to start a foreground service | None. The SDK retries when your UI comes to the foreground, and a `startRecording()` made in the meantime runs then. If your app has no UI, call `deinitialize()` and then `init()` again from an exempt receiver, then `startRecording()` again — `deinitialize()` drops a pending request. |

***

## Configuration

The SDK is configured using the `SdkConfiguration.Builder` class.

### Basic Configuration

```kotlin theme={null}
val config = SdkConfiguration.Builder("YOUR_API_KEY").build()
```

### Recording lifecycle

`init()` does not start recording. A recording begins when the host calls `startRecording()`, and
continues until `stopRecording()` or `deinitialize()`.

A recording that was started is **resumed automatically** the next time the app initializes the SDK,
so an app that is killed, restarted or updated mid-recording picks up where it left off. `init()` is
what performs that resume — it never stops an active recording.

To have the SDK start recording on its own instead, configure a delay:

```kotlin theme={null}
// Start as soon as init() completes
val config = SdkConfiguration.Builder("YOUR_API_KEY")
    .delayAutoStartRecording(SdkConfiguration.AUTO_START_ON_INIT)
    .build()

// Or start after a delay
val delayed = SdkConfiguration.Builder("YOUR_API_KEY")
    .delayAutoStartRecording(30_000L)                       // milliseconds
    .build()

val units = SdkConfiguration.Builder("YOUR_API_KEY")
    .delayAutoStartRecording(2, TimeUnit.MINUTES)
    .build()
```

While a configured delay is pending, the SDK reports `Status.DelayedStart`. Calling
`stopRecording()` in that window cancels the pending start. The default is
`SdkConfiguration.EXPLICIT_START`, and any negative value means the same thing: wait for an explicit
`startRecording()`.

> [!NOTE]
>
> **Changed in 1.6.0.** Releases 1.3.0 through 1.5.x defaulted to `AUTO_START_ON_INIT`, so an app that
> called `init()` was recording even if it never called `startRecording()`. If you relied on that,
> set `delayAutoStartRecording(SdkConfiguration.AUTO_START_ON_INIT)` explicitly. A device that was
> recording when it was updated keeps recording until it is stopped once with `stopRecording()` or
> `deinitialize()`; every launch after that follows the new default.

### Custom Foreground Notification

Customize the notification shown when the SDK is running as a foreground service using the SDK's notification channel:

```kotlin theme={null}
class CustomNotificationFactory : ForegroundNotificationFactory {
    override fun createNotification(context: Context): Notification {
        // Use SDK's notification channel ID
        return NotificationCompat.Builder(context, "FOREGROUND_SERVICE")
            .setContentTitle("Truemetrics SDK Running")
            .setContentText("Collecting sensor data...")
            .setSmallIcon(R.drawable.ic_sensors)
            .setOngoing(true)
            .build()
    }
}

val config = SdkConfiguration.Builder("YOUR_API_KEY")
    .foregroundNotificationFactory(CustomNotificationFactory())
    .build()
```

***

## Core Features

### Recording Management

```kotlin theme={null}
val sdk = TruemetricsSdk.getInstance()

// Start recording
sdk.startRecording()

// Stop recording
sdk.stopRecording()

// Check recording status
val isRecording = sdk.isRecordingInProgress()
val isStopped = sdk.isRecordingStopped()

// Get recording start time
val startTime = sdk.getRecordingStartTime() // Returns timestamp in milliseconds
```

### Device ID

Get the unique device identifier (available after initialization):

```kotlin theme={null}
val deviceId = sdk.getDeviceId()

// Or get from Status
sdk.observeSdkStatus().collect { status ->
    when (status) {
        is Status.Initialized -> println("Device ID: ${status.deviceId}")
        is Status.RecordingInProgress -> println("Device ID: ${status.deviceId}")
        else -> {}
    }
}
```

> [!NOTE]
>
> The device ID may rotate automatically based on a server-configured TTL. When expired, a new ID is generated transparently on the next initialization.

### Metadata Logging

Log standardized delivery/pickup event metadata:

```kotlin theme={null}
import io.truemetrics.truemetricssdk.metadata.StandardMetadata

sdk.logMetadata(StandardMetadata(
    eventTime = "2025-01-15T14:30:00",
    eventType = "delivery_successful",
    deliveryId = "parcel_123",
    tourId = "tour_456",
    waypointLatitude = "52.5200",
    waypointLongitude = "13.4050",
    referenceLatitude = "52.5201",
    referenceLongitude = "13.4051",
    address = "Pflanzstrasse 5, 10762 Berlin",
    extra = mapOf("type_vehicle" to "car")
))
```

The map-based `logMetadata(Map<String, String>)` overload is deprecated. Use `logMetadata(StandardMetadata)` instead.

For advanced metadata with templates and tags, see [Metadata Guide](https://docu.truemetrics.cloud/metadata.md).

### Sensor Management

```kotlin theme={null}
// Enable/disable all sensors
sdk.setAllSensorsEnabled(true)

// Check if sensors are enabled
val enabled = sdk.getAllSensorsEnabled()

// Observe available sensors
sdk.sensorInfo.collect { sensors ->
    sensors.forEach { sensor ->
        println("Sensor: ${sensor.sensorName}, Status: ${sensor.sensorStatus}")
        println("Frequency: ${sensor.frequency} Hz")
        if (sensor.missingPermissions.isNotEmpty()) {
            println("Missing permissions: ${sensor.missingPermissions}")
        }
    }
}
```

### Complete Cleanup

```kotlin theme={null}
sdk.deinitialize()
```

**Warning:** After calling `deinitialize()`, the SDK instance becomes unusable. You must call
`init()` again to use the SDK.

***

## SDK Status

Monitor the SDK state using `observeSdkStatus()`:

```kotlin theme={null}
sdk.observeSdkStatus().collect { status ->
    when (status) {
        is Status.Uninitialized -> {
            // SDK not yet initialized
        }
        is Status.Initializing -> {
            // SDK is fetching config from server
            // Retries automatically on network errors or server 5xx
        }
        is Status.Initialized -> {
            // SDK initialized, deviceId available
            val deviceId = status.deviceId
        }
        is Status.RecordingInProgress -> {
            // Recording is active
            val deviceId = status.deviceId
        }
        is Status.RecordingStopped -> {
            // Recording has stopped
        }
        is Status.DelayedStart -> {
            // Waiting for auto-start delay
            val deviceId = status.deviceId
            val delayMs = status.delayMs
        }
        is Status.TrafficLimitReached -> {
            // Traffic limit reached
        }
        is Status.ReadingsDatabaseFull -> {
            // Device storage full
        }
        is Status.Error -> {
            // SDK encountered an error
            val errorCode = status.errorCode
            val message = status.message
        }
        is Status.AskForPermissions -> {
            // SDK requesting permissions
            val permissions = status.permissions
        }
    }
}
```

### Error Codes

| Error Code | Description |
| - | - |
| AUTHENTICATION\_ERROR | API key is not valid, expired or revoked |
| UPLOAD\_ERROR | Recordings couldn't be uploaded after exhausting all attempts |
| STORAGE\_FULL | Device storage is full which prevents saving sensor readings |
| MISSING\_NOTIFICATION\_PERMISSION | Notification permission not granted, foreground service cannot start |
| FOREGROUND\_SERVICE\_START\_REFUSED | `init()` ran in the background, where Android refuses to start a foreground service. Temporary: the SDK retries when the app's UI comes to the foreground |
| CONFIG\_ERROR | Configuration error |
| TRAFFIC\_USED\_UP | All allotted traffic has been used |
| SENSORS\_NOT\_WORKING | Some sensors are not working. Check if permissions are missing |
| NOT\_INITIALIZED | `startRecording()` was called before `init()`, so there is nothing to record with |

***

## Statistics API

### Upload Statistics

Monitor upload health:

```kotlin theme={null}
val uploadStats = sdk.getUploadStatistics()
if (uploadStats != null) {
    println("Successful uploads: ${uploadStats.successfulUploadsCount}")
    println("Last upload: ${uploadStats.lastSuccessfulUploadTimestamp}")
}
```

### Sensor Statistics

Get detailed sensor data quality:

```kotlin theme={null}
val sensorStats = sdk.getSensorStatistics()
sensorStats?.forEach { stat ->
    println("Sensor: ${stat.sensorName}")
    println("Configured: ${stat.configuredFrequencyHz} Hz")
    println("Actual: ${stat.actualFrequencyHz} Hz")
    println("Quality: ${stat.quality}")
}
```

Quality levels:

* **EXCELLENT**: 95-100% of configured frequency
* **GOOD**: 80-95%
* **POOR**: 50-80%
* **BAD**: less than 50%
* **UNKNOWN**: no data or not recording

***

## Best Practices

### 1. Initialization

* Always initialize in your `Application` class
* Use the application context, not activity context
* Initialize once and reuse the singleton instance

### 2. Error Handling

```kotlin theme={null}
sdk.observeSdkStatus().collect { status ->
    when (status) {
        is Status.Error -> {
            Log.e("SDK", "Error: ${status.errorCode} - ${status.message}")
        }
        is Status.ReadingsDatabaseFull -> {
            Log.w("SDK", "Storage full")
        }
        else -> {}
    }
}
```

### 3. Monitoring SDK Health

```kotlin theme={null}
fun checkSdkHealth() {
    val uploadStats = sdk.getUploadStatistics()
    if (uploadStats != null && uploadStats.successfulUploadsCount == 0) {
        Log.w("SDK", "No successful uploads yet")
    }

    val sensorStats = sdk.getSensorStatistics()
    sensorStats?.filter { it.quality == SensorDataQuality.BAD }?.forEach {
        Log.w("SDK", "Bad quality for: ${it.sensorName}")
    }
}
```

***

## API Reference

### TruemetricsSdk

| Method | Return Type | Description |
| - | - | - |
| `init(context, config)` | `TruemetricsSdk` | Initialize SDK (static) |
| `getInstance()` | `TruemetricsSdk` | Get singleton instance (static) |
| `startRecording()` | `Unit` | Start sensor recording |
| `stopRecording()` | `Unit` | Stop sensor recording |
| `isRecordingInProgress()` | `Boolean` | Check if recording active |
| `isRecordingStopped()` | `Boolean` | Check if recording stopped |
| `getRecordingStartTime()` | `Long` | Get recording start timestamp |
| `getDeviceId()` | `String?` | Get unique device identifier |
| `logMetadata(standardMetadata)` | `Unit` | Log standardized event metadata |
| `logMetadata(payload)` *(deprecated)* | `Unit` | Log custom metadata map |
| `setAllSensorsEnabled(enabled)` | `Unit` | Enable/disable all sensors |
| `getAllSensorsEnabled()` | `Boolean` | Get sensor enable status |
| `getActiveConfig()` | `Configuration?` | Get active backend configuration |
| `getUploadStatistics()` | `UploadStatistics?` | Get upload stats |
| `getSensorStatistics()` | `List<SensorStatistics>?` | Get sensor stats |
| `deinitialize()` | `Unit` | Shutdown SDK completely |

### Observable Flows

| Property/Method | Type | Description |
| - | - | - |
| `sensorInfo` | `StateFlow<Iterable<SensorInfo>>` | Available sensors info |
| `sdkStatus` | `StateFlow<Status>` | SDK operational status |
| `observeSdkStatus()` | `Flow<Status>` | Observe SDK status changes |
| `getActiveConfigFlow()` | `Flow<Configuration>?` | Observe backend config changes |

### Data Classes

#### UploadStatistics

| Property | Type | Description |
| - | - | - |
| `successfulUploadsCount` | `Int` | Total successful uploads |
| `lastSuccessfulUploadTimestamp` | `Long?` | Last upload timestamp |

#### SensorStatistics

| Property | Type | Description |
| - | - | - |
| `sensorName` | `SensorName` | Sensor identifier |
| `configuredFrequencyHz` | `Float` | Configured frequency |
| `actualFrequencyHz` | `Float` | Actual measured frequency |
| `quality` | `SensorDataQuality` | Quality assessment |

#### SensorInfo

| Property | Type | Description |
| - | - | - |
| `sensorName` | `SensorName` | Sensor identifier |
| `sensorStatus` | `SensorStatus` | Status: ON, OFF, or NA |
| `frequency` | `Float` | Polling frequency in Hz |
| `missingPermissions` | `List<String>` | Required permissions not granted |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.