Skip to Content
truemetrics Docs

SDK integration

Android Native Integration

Integrate the truemetrics SDK 1.7.0 into an Android app

The truemetrics SDK records sensor data on the courier’s phone and uploads it. Your app initializes the SDK, starts and stops recording, and logs one metadata event per delivery attempt. To let a coding agent do the integration, use the agent prompt.

Requirements

  • Android 7.0 (API 24) or newer: minSdk 24.
  • Kotlin Gradle plugin (org.jetbrains.kotlin.android) 2.1 or newer. The SDK is built with Kotlin 2.2; an older plugin fails with “Module was compiled with an incompatible version of Kotlin”.
  • JVM target 11 or newer in your app module. AGP and JDK as your build needs.
  • kotlinx-coroutines in the app to observe the SDK status. From Java, use androidx.lifecycle:lifecycle-livedata-ktx instead.
  • An SDK API key from truemetrics, see API keys.

Installation

Add the truemetrics Maven repository, in settings.gradle(.kts) under dependencyResolutionManagement, or in the root build.gradle(.kts) under allprojects:

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://github.com/TRUE-Metrics-io/truemetrics_android_SDK_p_maven/raw/main") }
    }
}

Then add the dependency to your app module:

dependencies {
    implementation("io.truemetrics:truemetricssdk:1.7.0")
}

If you update from an earlier version, see Updating from an earlier version.

Sentry. The SDK’s manifest removes Sentry’s SentryInitProvider and SentryPerformanceProvider from your app, so Sentry does not start by itself. If your app uses Sentry, start it in code with SentryAndroid.init(this) in Application.onCreate(), and add <meta-data android:name="io.sentry.auto-init" android:value="false" /> to your app’s manifest.

Permissions

The SDK’s manifest merges these permissions into your app. Do not remove any of them with tools:node="remove". After an SDK update, check the merged list again in app/build/outputs/logs/manifest-merger-*-report.txt.

PermissionRequested at runtimeUsed for
ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATIONYesLocation
ACCESS_BACKGROUND_LOCATIONYes, Android 10+Location while the app is not in front
ACTIVITY_RECOGNITIONYes, Android 10+Motion detection
READ_PHONE_STATENoNothing: the SDK declares it but does not use it. Keep it in the manifest and do not request it.
POST_NOTIFICATIONSYes, Android 13+Showing the SDK’s notification
FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION, FOREGROUND_SERVICE_DATA_SYNCNoThe recording service
HIGH_SAMPLING_RATE_SENSORSNoSensor rates above 200 Hz
INTERNET, ACCESS_NETWORK_STATE, CHANGE_NETWORK_STATENoUpload
WAKE_LOCKNoRecording while the screen is off

The SDK does not ask for permissions itself. Request them in your app before recording starts: right after login, and on app start for a user who is already logged in. Reuse your app’s permission flow if it has one. Order:

  1. Show a prominent disclosure first: an in-app dialog stating that the app collects location data in the background, also when the app is closed or not in use, and what it is used for. Google Play requires it before the first location request.
  2. ACCESS_FINE_LOCATION together with ACCESS_COARSE_LOCATION.
  3. ACCESS_BACKGROUND_LOCATION, in a separate request after the foreground location was granted. On Android 11 and newer, Android sends the user to the settings page for “Allow all the time”.
  4. ACTIVITY_RECOGNITION and POST_NOTIFICATIONS.

When a permission is still missing, the SDK reports Status.AskForPermissions(permissions) (SDK status). Request the listed permissions then, in the order above: ACCESS_BACKGROUND_LOCATION in its own request after the foreground location, because Android 11 and newer ignore a request that mixes them. The list holds only what the sensors need, never POST_NOTIFICATIONS. If your app’s flow supports it, also ask to exclude the app from battery optimization.

Google Play Console. Declare background location access, and the foreground service types Location and Data sync for the truemetrics recording service. If an older declaration lists Special use for a truemetrics service, replace it with Data sync.

Timeline of a courier's day: init after login, the SDK goes from Initializing to Initialized, startRecording at route start, RecordingInProgress, stopRecording at route end, deinitialize at logout. The SDK's notification is visible from init to deinitialize.
WhenCall
Login succeededinit()
App start with a user already logged in (Application.onCreate(), main process only)init()
Route start: the courier leaves the depotstartRecording(), if isRecordingInProgress() is false
Each delivery or pickup attempt reaches its final statelogMetadata(), see Metadata
Route end, end of shift, or a daily cutoff (e.g. 22:00)stopRecording()
Logoutdeinitialize()
  • Initialize once per process, and again only after deinitialize() has returned.
  • Start recording once per route and stop it once. Do not stop and start per stop, per delivery, per screen, or when the app goes to the background. The one exception is a break that must not be recorded.
  • Never stop recording from a crash handler or a lifecycle callback (onDestroy, onTaskRemoved, app swiped away). A recording that was started and not stopped survives a crash, an OS kill, an app update or a reboot, and resumes on the next init().
  • Deinitialize on logout only, not at route end: uploading the remaining data stops at deinitialize() and continues only after the next init().
  • Do not call startRecording() on a plain app start; a started recording resumes on its own.

Notification. init() starts the SDK’s foreground service, and its notification stays visible until a few seconds after deinitialize(), also while no recording is running. Plan your app’s UX and the Play declaration for it. On Android 13 and newer without POST_NOTIFICATIONS, the service still runs and Android does not show the notification in the drawer.

Quick start

Initialize in your Application while a user is logged in, and again after each login:

import android.app.Application
import io.truemetrics.truemetricssdk.TruemetricsSdk
import io.truemetrics.truemetricssdk.config.SdkConfiguration

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        // Your own session check. Main process only.
        if (session.isLoggedIn) initTruemetrics()
    }

    fun initTruemetrics() {
        val config = SdkConfiguration.Builder(BuildConfig.TRUEMETRICS_API_KEY).build()
        TruemetricsSdk.init(this, config)
    }
}

Keep the API key in your build config or secrets, never in source control. Do not add a foreground check around init(): onCreate() can run in the background, and the SDK then finishes starting once your UI is shown (see FOREGROUND_SERVICE_START_REFUSED below).

Start and stop at route start and end:

import io.truemetrics.truemetricssdk.TruemetricsSdk

fun onRouteStarted() {
    val sdk = TruemetricsSdk.getInstance()
    if (!sdk.isRecordingInProgress()) sdk.startRecording()
}

fun onRouteFinished() {
    // Unconditionally: right after init(), isRecordingInProgress() is still false.
    TruemetricsSdk.getInstance().stopRecording()
}

Initialization

init() returns at once. The SDK then starts its foreground service and fetches its configuration from truemetrics.

Uninitialized ──► Initializing ──► Initialized
                       │
                       ├──► Error(AUTHENTICATION_ERROR)   API key rejected, no saved configuration
                       │
                       ├──► Error(FOREGROUND_SERVICE_START_REFUSED) ──► Initialized
                       │    init() ran in the background; the SDK retries when
                       │    the app's UI comes to the foreground
                       │
                       └──► stays Initializing, retrying every 30 s
                            (no network, server error, timeout)

There is no timeout. Offline and without a cached configuration (first init() after install or after deinitialize()), the SDK stays Initializing and keeps retrying. Do not add a client-side timeout or assert.

When Android cannot bind the SDK’s service, for example when init() runs before the device has been unlocked for the first time after a restart, the SDK reports Error(FOREGROUND_SERVICE_START_REFUSED) and starts by itself the next time your UI comes to the foreground.

Calling init() again while the SDK is running keeps the running session, and the new configuration is not applied. To switch the API key or another setting, call deinitialize() first. The first init() with a different API key deletes the readings and metadata that were not yet uploaded under the previous key.

When the SDK is ready

The SDK is ready from the first Initialized, RecordingInProgress, RecordingStopped, DelayedStart, TrafficLimitReached, ReadingsDatabaseFull or AskForPermissions status after each init() until deinitialize(), also through later errors. There is no direct call for it, and getDeviceId() is not a readiness signal: it returns an ID while the SDK is still Initializing, and that ID can change once the configuration arrives.

When a permission is missing, AskForPermissions follows Initialized (or DelayedStart) at once. observeSdkStatus() delivers both, but an observer that starts later, or one that collects sdkStatus, receives only AskForPermissions. Do not wait for Initialized alone.

import androidx.lifecycle.lifecycleScope
import io.truemetrics.truemetricssdk.TruemetricsSdk
import io.truemetrics.truemetricssdk.engine.state.Status
import kotlinx.coroutines.launch

fun Status.isReady() = this is Status.Initialized || this is Status.RecordingInProgress ||
    this is Status.RecordingStopped || this is Status.DelayedStart ||
    this is Status.TrafficLimitReached || this is Status.ReadingsDatabaseFull ||
    this is Status.AskForPermissions

// In an Activity or Fragment
lifecycleScope.launch {
    TruemetricsSdk.getInstance().observeSdkStatus().collect { status ->
        when (status) {
            is Status.Initialized -> log("truemetrics device ID: ${status.deviceId}")
            is Status.Error -> log("truemetrics error: ${status.errorCode} ${status.message}")
            else -> {}
        }
        if (status.isReady()) sendQueuedMetadata()
    }
}

Calls before the SDK is ready

  • startRecording() and stopRecording(): safe right after init(). The latest request is kept and runs once the service is up, also after a refused start. A stopRecording() before init() is discarded; a startRecording() before init() or after deinitialize() reports Error(NOT_INITIALIZED).
  • logMetadata(): after init(), the event is held in memory and logged once the SDK is ready. It is lost if the app’s process ends or deinitialize() is called before that, if initialization fails (for example with an invalid API key), and it can be lost while the status is Error(FOREGROUND_SERVICE_START_REFUSED). Before init() or after deinitialize() it is dropped, with a log warning. To lose no event, keep your own queue until the SDK is ready; see Metadata.
  • getActiveConfig(), getUploadStatistics(), getSensorStatistics(): null until the service is up.

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 a refused start. Call init() again from a context Android allows, such as a receiver it exempts. A startRecording() made meanwhile, and a recording that was to resume, run then. Do not call deinitialize() first: it ends the recording.

Configuration

import io.truemetrics.truemetricssdk.config.SdkConfiguration

val config = SdkConfiguration.Builder("YOUR_API_KEY").build()

Recording start

init() does not start recording; recording runs from startRecording() until stopRecording() or deinitialize(), or until truemetrics stops it remotely on your request (Remote start and stop). This explicit start (SdkConfiguration.EXPLICIT_START, the default) is the recommended setup. A recording that was started resumes on the next init().

An auto-start is possible but not recommended for courier apps:

import io.truemetrics.truemetricssdk.config.SdkConfiguration
import java.util.concurrent.TimeUnit

// Start as soon as init() completes
val onInit = SdkConfiguration.Builder("YOUR_API_KEY")
    .delayAutoStartRecording(SdkConfiguration.AUTO_START_ON_INIT)
    .build()

// Or after a delay
val delayed = SdkConfiguration.Builder("YOUR_API_KEY")
    .delayAutoStartRecording(2, TimeUnit.MINUTES)
    .build()

While a delay is pending, the SDK reports Status.DelayedStart; stopRecording() in that window cancels the start. Any negative value means explicit start.

SDK 1.3.0 to 1.5.x started recording on init() by default. When you update from one of them, a device that was recording keeps recording until it is stopped once with stopRecording() or deinitialize().

Remote start and stop

On your request, truemetrics can start or stop recording on a device remotely, through the configuration the SDK fetches:

  • Once. The SDK starts or stops recording a single time. Your app’s startRecording() and stopRecording() work as usual afterwards.
  • Held on. A stopped recording is started, and stopRecording() is ignored while the hold lasts. At init() recording starts right away, without a configured start delay.
  • Held off. A running recording is stopped, and startRecording() and an auto-start are ignored while the hold lasts.

When a hold is lifted, recording stays as it is until your app or another request changes it. deinitialize() always stops recording; if recording is still held on, the next init() starts it again.

A request reaches the device the next time the SDK checks its configuration: usually within minutes and at most an hour later while the SDK is initialized, otherwise at the next init(). Without a connection at init(), the SDK acts on the last configuration it received.

A call that a hold ignores reports no error, and the status stays as it was. Read isRecordingInProgress() instead of assuming that the call took effect. A remote start or stop is reported in the SDK status like any other.

Custom notification

Replace the SDK’s notification with your own, on the SDK’s channel FOREGROUND_SERVICE:

import android.app.Notification
import android.content.Context
import androidx.core.app.NotificationCompat
import io.truemetrics.truemetricssdk.config.ForegroundNotificationFactory
import io.truemetrics.truemetricssdk.config.SdkConfiguration

class CourierNotificationFactory : ForegroundNotificationFactory {
    override fun createNotification(context: Context): Notification =
        NotificationCompat.Builder(context, "FOREGROUND_SERVICE")
            .setContentTitle("Route tracking")
            .setContentText("Recording while you are logged in")
            .setSmallIcon(R.drawable.ic_notification)
            .setOngoing(true)
            .build()
}

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

Metadata

Log one event per delivery or pickup attempt, at the moment the driver finalizes it. The fields, the extra keys and the rules are on Metadata.

import io.truemetrics.truemetricssdk.TruemetricsSdk
import io.truemetrics.truemetricssdk.metadata.StandardMetadata

TruemetricsSdk.getInstance().logMetadata(
    StandardMetadata(
        eventTime = "2026-01-15T14:30:00+01:00",
        eventType = "delivery",
        deliveryId = "D-123",
        tourId = "T-456",
        waypointLatitude = "52.5200",
        waypointLongitude = "13.4050",
        referenceLatitude = "52.5201",
        referenceLongitude = "13.4051",
        address = "Pflanzstrasse 5, 10762 Berlin",
        extra = mapOf(
            "address_id" to "A-789",
            "delivery_state" to "success",
            "delivered_to_neighbor" to "false",
            "eta_first" to "2026-01-15T14:10:00+01:00",
            "eta_latest" to "2026-01-15T14:25:00+01:00",
            "depot_id" to "BER-1",
        ),
    )
)

The map-based logMetadata(Map<String, String>) is deprecated.

Device ID

The SDK generates the device ID. Take it from the first Initialized or RecordingInProgress status after each init() and store it in your logs or backend next to the driver or session: truemetrics support asks for it. If the first ready status is AskForPermissions, which carries no ID, call getDeviceId().

The ID changes after 30 days, at the next init() (unless truemetrics set another period for your account), and when the app’s data is cleared. getDeviceId() returns the current ID once the service is up, but it can still change while the SDK is Initializing.

Sensors

import androidx.lifecycle.lifecycleScope
import io.truemetrics.truemetricssdk.TruemetricsSdk
import kotlinx.coroutines.launch

lifecycleScope.launch {
    TruemetricsSdk.getInstance().sensorInfo.collect { sensors ->
        sensors.forEach { sensor ->
            log("${sensor.sensorName}: ${sensor.sensorStatus}, ${sensor.frequency} Hz")
            if (sensor.missingPermissions.isNotEmpty()) {
                log("missing permissions: ${sensor.missingPermissions}")
            }
        }
    }
}

setAllSensorsEnabled(true) records from all sensors the device has, setAllSensorsEnabled(false) from the set in your truemetrics configuration (the default); it does not switch sensors off. The change applies at once, also to a running recording. A call before the SDK’s service is up is ignored. The setting is not saved: after deinitialize() and init(), or when the app’s process restarts, the SDK records the configured set again, so call it again once the SDK is ready.

The list includes SensorName.DEVICE_HEALTH: once a minute while recording, the SDK notes the device’s condition, such as the app’s CPU and memory use, the thermal status and the battery current. It also notes when the screen turns on or off, a charger is connected or disconnected, battery saver is switched, or the thermal status changes. Once the SDK is ready after init(), it also notes basic device facts and, on Android 11 and newer, why the app’s earlier processes ended. truemetrics can change the rate, or switch off the regular and the change notes, in your configuration; the notes made after init() stay on. Keep an else branch in a when over SensorName.

Deinitialize

Call deinitialize() on logout. It returns quickly and is safe to call from the main thread. When it returns, recording has stopped, the SDK reports Uninitialized, and uploading has ended until the next init().

import io.truemetrics.truemetricssdk.TruemetricsSdk

fun onLogout() {
    TruemetricsSdk.getInstance().deinitialize()
}

The rest of the cleanup runs in the background, usually for a few seconds:

  • It saves the readings recorded up to the call. If your app ends its own process after logout, for example to restart, let it run for a few seconds first; otherwise they are lost.
  • The SDK’s notification can stay visible until the cleanup has finished.
  • An init() called meanwhile returns at once and waits for the cleanup by itself, for at most about 15 seconds.

A recording that deinitialize() stops reports RecordingStopped and Uninitialized at once. observeSdkStatus() delivers both; a collector of sdkStatus may receive only Uninitialized, so treat an Uninitialized that follows RecordingInProgress as the end of the recording too.

The recording does not resume at the next init(), even if the app is killed right after the call, unless truemetrics holds recording on remotely. For that, deinitialize() writes one small setting to disk before it returns, which StrictMode disk checks report. If the device cannot save it, for example because its storage is full, the next launch may still resume the recording.

SDK status

observeSdkStatus() delivers the current status to a new collector, then every later one in order, also when one status replaces another at once. A collector that falls behind receives the ones it missed afterwards, oldest first, up to the last 17, so check isRecordingInProgress() before acting on a status that may be out of date. A collection that is cancelled and started again (for example with repeatOnLifecycle), and a LiveData observer that is not active, receive only the current status. The sdkStatus StateFlow holds only the latest one, so its collectors can miss a status that is replaced at once. Both report:

StatusMeaningYour action
Uninitializedinit() not called, or after deinitialize()None. After RecordingInProgress, it also ends the recording.
InitializingStarting; fetching the configuration, retried every 30 sWait. Do not call init() again.
Initialized(deviceId)Ready, not recordingStore the device ID
RecordingInProgress(deviceId)RecordingNone
RecordingStoppedRecording stoppedNone
DelayedStart(deviceId, delayMs)An auto-start is pendingNone
TrafficLimitReachedThe account’s traffic limit is reached. Reported when the limit stops a recording, which also deletes the readings and metadata not yet uploaded, and when it refuses startRecording().Contact truemetrics. Recording does not restart by itself: once the limit is lifted, call startRecording() again.
ReadingsDatabaseFullStorage on the device is full, recording stoppedFree storage on the device, then call startRecording() again; recording does not restart by itself.
AskForPermissions(permissions)Permissions are missing; the SDK is ready. Also reported during a recording, which goes on.Request them (Permissions)
Error(errorCode, message)See the error codes below

Error codes

Reported by SDK 1.7.0:

Error codeCauseYour action
AUTHENTICATION_ERRORThe API key was rejected while the device had no saved configuration: at the first init() after install, after deinitialize(), after switching the API key, or after an earlier AUTHENTICATION_ERROR. Recording and uploading have stopped; the notification stays until deinitialize(). A device that has a saved configuration does not report a key revoked later: it records on that configuration, and its uploads fail until the key works again.Do not retry with the same key. Call deinitialize(), fix the key, then call init() again.
FOREGROUND_SERVICE_START_REFUSEDTemporary. init() ran in the background, where Android refuses to start a foreground service, or before the first unlock after a restart, where Android cannot bind the SDK’s service.None with a UI: the SDK retries when your UI comes to the foreground, and a startRecording() made meanwhile runs then. Without a UI, see the warning under Calls before the SDK is ready.
NOT_INITIALIZEDstartRecording() was called before init() or after deinitialize(). The request is dropped.Call init(), then startRecording() again.
CONFIG_ERRORstartRecording() found no loaded configuration.Call startRecording() again once the SDK is ready.
SENSORS_NOT_WORKINGAt recording start, some sensors are unavailable or miss a permission; the message names them. Reported while recording starts, between two RecordingInProgress statuses; recording goes on.Request the missing permissions. A sensor the device does not have needs nothing.

Reserved, not reported by SDK 1.7.0: UPLOAD_ERROR, STORAGE_FULL (a full storage arrives as ReadingsDatabaseFull), MISSING_NOTIFICATION_PERMISSION, TRAFFIC_USED_UP (arrives as TrafficLimitReached). Keep an else branch for them.

Statistics

import io.truemetrics.truemetricssdk.TruemetricsSdk
import io.truemetrics.truemetricssdk.engine.stats.SensorDataQuality

val sdk = TruemetricsSdk.getInstance()

sdk.getUploadStatistics()?.let {
    log("uploads: ${it.successfulUploadsCount}, last: ${it.lastSuccessfulUploadTimestamp}")
}

sdk.getSensorStatistics()
    ?.filter { it.quality == SensorDataQuality.BAD }
    ?.forEach { log("${it.sensorName}: ${it.actualFrequencyHz} of ${it.configuredFrequencyHz} Hz") }

Quality is the measured rate against the configured one: EXCELLENT 95 % or more, GOOD 80–95 %, POOR 50–80 %, BAD below 50 %, UNKNOWN without data or while not recording.

Updating from an earlier version

Check these points when you update to 1.7.0:

  • AskForPermissions can be the only ready status. An app that waits for Initialized before it starts recording or logs metadata has to accept AskForPermissions too, see When the SDK is ready.
  • deinitialize() can skip RecordingStopped for a collector of sdkStatus, which may receive only Uninitialized, see Deinitialize. observeSdkStatus() delivers both.
  • observeSdkStatus() is no longer the sdkStatus StateFlow. A cast to StateFlow fails, and a LiveData made with asLiveData() has no value until it is observed. Its collectors now also receive statuses that last only a moment, such as AskForPermissions before and after Initialized.
  • Recording can start or stop without a call from your app, when truemetrics starts or stops it remotely on your request, and startRecording() or stopRecording() can be ignored while a hold lasts, see Remote start and stop.
  • deinitialize() returns quickly. It no longer has to run off the main thread. Do not end the app’s process right after it.
  • SensorName.DEVICE_HEALTH is new. A Kotlin when over SensorName without an else branch no longer compiles.
  • Configuration cannot be created or copied. Its constructor and copy() are no longer public. Read the values from getActiveConfig() or getActiveConfigFlow().
  • logMetadata() right after init() is kept, see Calls before the SDK is ready.
  • A repeated init() keeps the running session. To switch configuration, call deinitialize() first.
  • Without a UI, recover a refused start with init() alone, not with deinitialize() and init().
  • Going back to an earlier version discards the readings that were recorded but not yet uploaded.

Rebuild every module that uses the SDK against 1.7.0: a module built against an earlier version can fail at runtime where it creates a Configuration or meets DEVICE_HEALTH.

API reference

TruemetricsSdk

MethodReturnsDescription
init(context, config)TruemetricsSdkInitialize (static)
getInstance()TruemetricsSdkThe singleton (static)
startRecording()UnitStart recording
stopRecording()UnitStop recording
isRecordingInProgress()BooleanRecording is running
isRecordingStopped()BooleanRecording was stopped
getRecordingStartTime()LongStart of the current or last recording, ms since epoch; 0 if none
getDeviceId()String?Current device ID; null until the service is up
logMetadata(standardMetadata)UnitLog an event, see Metadata
logMetadata(payload) (deprecated)UnitLog a metadata map
setAllSensorsEnabled(enabled)UnitRecord from all sensors (true) or the configured set (false)
getAllSensorsEnabled()BooleanWhether all sensors are recorded
getActiveConfig()Configuration?The configuration in use
getUploadStatistics()UploadStatistics?Upload statistics
getSensorStatistics()List<SensorStatistics>?Sensor statistics
deinitialize()UnitShut the SDK down

Flows

Property or methodTypeDescription
sdkStatusStateFlow<Status>Current SDK status, latest only (Java: getSdkStatus())
observeSdkStatus()Flow<Status>SDK status changes in order, see SDK status
sensorInfoStateFlow<Iterable<SensorInfo>>Sensors and their state
getActiveConfigFlow()Flow<Configuration>?Configuration changes

Data classes

ClassProperties
UploadStatisticssuccessfulUploadsCount: Int, lastSuccessfulUploadTimestamp: Long?
SensorStatisticssensorName, configuredFrequencyHz: Float, actualFrequencyHz: Float, quality: SensorDataQuality
SensorInfosensorName, sensorStatus (ON, OFF, NA), frequency: Float (Hz), missingPermissions: List<String>

On this page