Skip to main content
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

Add the truemetrics SDK to your app’s build.gradle file:
dependencies {
    implementation 'io.truemetrics:truemetrics-sdk:VERSION'
}

Quick Start

1. Initialize the SDK in your Application class

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Basic configuration
        val config = SdkConfiguration.Builder("YOUR_API_KEY")
            .build()
            
        truemetricsSdk.init(this, config)
    }
}

2. Start and stop recordings

// Get SDK instance
val sdk = truemetricsSdk.getInstance()

// Start recording sensor data
sdk.startRecording()

// Stop recording
sdk.stopRecording()

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

Configuration

The SDK is configured using the SdkConfiguration.Builder class. Here are all available options:

Basic Configuration

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

Custom Foreground Notification

Customize the notification shown when the SDK is running as a foreground service:
class CustomNotificationFactory : ForegroundNotificationFactory {
    override fun createNotification(context: Context): Notification {
        return NotificationCompat.Builder(context, "sdk_channel")
            .setContentTitle("truemetrics SDK Running")
            .setContentText("Collecting sensor data...")
            .setSmallIcon(R.drawable.ic_sensors)
            .setOngoing(true)
            .build()
    }
}

val config = SdkConfiguration.Builder(apiKey)
    .foregroundNotificationFactory(CustomNotificationFactory())
    .build()

Core Features

Recording Management

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

Metadata Logging

Attach custom metadata to your recordings for better analysis:
// Log user information
sdk.logMetadata(mapOf(
    "userId" to "user123",
    "sessionId" to "session_abc",
    "appVersion" to "1.2.3"
))

// Log event-specific data
sdk.logMetadata(mapOf(
    "eventType" to "navigation",
    "destination" to "profile_screen",
    "timestamp" to System.currentTimeMillis().toString()
))

Lifecycle Integration

The SDK automatically handles Android application lifecycle events, but you can also integrate with your own lifecycle observers:
class MyActivity : AppCompatActivity() {
    private val sdk = truemetricsSdk.getInstance()
    
    override fun onResume() {
        super.onResume()
        // SDK automatically handles app resume
    }
    
    override fun onPause() {
        super.onPause()
        // SDK continues running in background service
    }
}

Complete Cleanup

When you need to completely shut down the SDK:
sdk.deinitialize()
⚠️ Warning: After calling deinitialize(), the SDK instance becomes unusable. You must call init() again to use the SDK.

Best Practices

1. Initialization

  • Always initialize in your Application class
  • Use the application context, not activity context
  • Initialize once and reuse the singleton instance
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        
        val config = SdkConfiguration.Builder(BuildConfig.TRUEMETRICS_API_KEY)
            .delayAutoStartRecording(SdkConfiguration.DELAY_30_SECONDS)
            .build()
            
        truemetricsSdk.init(this, config)
    }
}

2. Recording Management

  • Check recording status before starting/stopping
  • Use metadata to provide context for your recordings
  • Consider auto-start delays for better user experience
fun startDataCollection() {
    val sdk = truemetricsSdk.getInstance()
    
    if (!sdk.isRecordingInProgress()) {
        // Log session context
        sdk.logMetadata(mapOf(
            "sessionType" to "user_initiated",
            "feature" to "data_analysis"
        ))
        
        sdk.startRecording()
    }
}

3. Data Observation

  • Use lifecycle-aware components when observing flows
  • Only observe flows when you need the data
  • Handle null values appropriately
class MyViewModel : ViewModel() {
    private val sdk = truemetricsSdk.getInstance()
    
    val sensorStats = sdk.observerSensorStats()
        .flowOn(Dispatchers.IO)
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = emptyList()
        )
}

4. Error Handling

// Monitor SDK status for errors
sdk.observeSdkStatus().collect { status ->
    when (status) {
        Status.Error -> {
            // Handle SDK errors
            // Consider reinitializing or notifying user
        }
        Status.Running -> {
            // SDK is healthy
        }
        else -> {
            // Handle other states
        }
    }
}

5. Resource Management

  • Only call deinitialize() when you’re completely done with the SDK
  • Use appropriate lifecycle scopes for flow collection
  • Monitor storage usage in production apps

Debugging

Monitor SDK status for diagnostic information:
sdk.observeSdkStatus().collect { status ->
    Log.d("SDK_DEBUG", "Current status: $status")
}

API Reference

truemetricsSdk

MethodReturn TypeDescription
init(context, config)truemetricsSdkInitialize SDK (static)
getInstance()truemetricsSdkGet singleton instance (static)
startRecording()UnitStart sensor recording
stopRecording()UnitStop sensor recording
isRecordingInProgress()BooleanCheck if recording active
isRecordingStopped()BooleanCheck if recording stopped
logMetadata(payload)UnitLog custom metadata
setAllSensorsEnabled(enabled)UnitEnable/disable all sensors
getAllSensorsEnabled()BooleanGet sensor enable status
getRecordingStartTime()LongGet recording start timestamp
getDatabaseSize()StringGet current database size
getActiveConfig()SdkConfiguration?Get active configuration
deinitialize()UnitShutdown SDK completely

Observable Flows

FlowTypeDescription
deviceIdFlowStateFlow<String?>Unique device identifier
sensorStatsStateFlow<List<SensorStats>>Sensor statistics
trafficInfoStateFlow<TrafficInfo>Network usage data
recordingsCountStateFlow<Long>Number of recordings
databaseSizeStateFlow<String>Database size string
sensorInfoStateFlow<Iterable<SensorInfo>>Available sensors info
sdkStatusStateFlow<Status>SDK operational status

Observer Methods

MethodReturn TypeDescription
observeSdkStatus()Flow<Status>Observe SDK status changes
observerSensorStats()Flow<List<SensorStats>>Observe sensor statistics
observerTrafficInfo()Flow<TrafficInfo>Observe network traffic
observerRecordingCount()Flow<Long>Observe recording count
observeDatabaseSize()Flow<String>Observe database size
getStorageInfo()Flow<String>Observe storage information
getActiveConfigFlow()Flow<SdkConfiguration?>?Observe config changes
I