Datablit Kotlin SDK
A lightweight analytics library for Android applications to track user events and behavior. The SDK provides comprehensive functionality for event tracking, user identification, rule evaluation, and experiment variant retrieval.
Installation
Add the dependency to your build.gradle.kts
:
dependencies {
implementation("com.datablit:kotlin:1.0.0")
}
Quick Start
Here's how to get started with the Datablit Kotlin SDK:
import com.datablit.Datablit
// Initialize the SDK
val datablit = Datablit("your-api-key", context)
// Track an event
datablit.track("Button Click")
// Track an event with properties
datablit.track("Purchase", mapOf(
"productId" to "123",
"price" to 29.99,
"currency" to "USD"
))
// Identify a user
datablit.identify("user123", mapOf(
"name" to "John Doe",
"email" to "john@example.com",
"plan" to "premium"
))
API Reference
Datablit(apiKey, context, config)
Initializes the Datablit SDK. You should initialize this library once before using any other functions.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
apiKey | String | Yes | Your Datablit API key. Get this from the Datablit project source Create new project/source if its not created yet |
context | Context | Yes | Android application context |
config.endpoint | String | No | API endpoint for sending events. Default: https://event.datablit.com/v1/batch |
config.flushAt | Int | No | Number of events to batch before sending. Default: 20 |
config.flushInterval | Long | No | Interval in milliseconds to flush events. Default: 30000 |
config.trackApplicationLifecycleEvents | Boolean | No | Automatically track app lifecycle events. Default: false |
config.enableDebugLogs | Boolean | No | Enable debug logging. Default: false |
Analytics API
datablit.track(eventName, properties)
Tracks an event with associated properties.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
eventName | String | Yes | Name of the event. |
properties | Map<String, Any> | No | Key-value pairs of event properties. |
Example:
datablit.track("Button Click")
// Track with properties
datablit.track("Purchase", mapOf(
"productId" to "123",
"price" to 29.99,
"currency" to "USD"
))
datablit.identify(userId, traits)
Identify a user with a unique ID and optional traits.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
userId | String | Yes | Unique user ID. |
traits | Map<String, Any> | No | Additional user attributes. |
Example:
datablit.identify("user123", mapOf(
"name" to "John Doe",
"email" to "john@example.com",
"plan" to "premium"
))
datablit.flush()
Manually flush queued events to the server.
Example:
datablit.flush()
Rules API
datablit.rule.evalRule(request, callback)
Evaluates a rule for a given user and context. This allows you to make dynamic decisions based on user attributes and rule logic.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
key | String | Yes | The rule key identifier. |
userId | String | Yes | Unique user ID. |
params | Map<String, Any> | No | Additional parameters for rule evaluation. |
callback | Function | Yes | Callback function to handle the result. |
Example:
datablit.rule.evalRule(
key = "feature_flag",
userId = "user123",
params = mapOf(
"os_name" to "android",
"app_version" to "1.0.0"
)
) { result ->
result.onSuccess { ruleResult ->
if (ruleResult.result) {
println("Rule evaluated to true")
} else {
println("Rule evaluated to false")
}
}.onFailure { error ->
println("Rule evaluation failed: ${error.message}")
}
}
Experiments API
datablit.experiment.getVariant(request, callback)
Retrieves the experiment variant for a user. This is useful for A/B testing and feature experimentation.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
expId | String | Yes | The experiment ID. |
entityId | String | Yes | Unique entity/user ID. |
callback | Function | Yes | Callback function to handle the result. |
Example:
datablit.experiment.getVariant(
expId = "01K2JKVXR0J0ZWPX40XY8CAWBS",
entityId = "user123"
) { result ->
result.onSuccess { response ->
println("User is in variant: ${response.variant}") // "control", "variant_a", etc.
// Use the variant to show different UI
when (response.variant) {
"variant_a" -> {
// Show new feature
}
else -> {
// Show control version
}
}
}.onFailure { error ->
println("Failed to get variant: ${error.message}")
}
}
Auto-Tracked Events
Application Lifecycle Events
If trackApplicationLifecycleEvents
is set to true
, the SDK will automatically track the following events:
Application Opened
Application Backgrounded
Application Foregrounded
These events include contextual information such as device details, OS version, screen dimensions, locale, timezone, and more.
Error Handling
The SDK provides comprehensive error handling mechanisms through Result objects:
// Rule evaluation with error handling
datablit.rule.evalRule(
key = "feature_flag",
userId = "user123"
) { result ->
result.onSuccess { ruleResult ->
// Handle successful rule evaluation
println("Rule result: ${ruleResult.result}")
}.onFailure { error ->
// Handle error
println("Rule evaluation failed: ${error.message}")
}
}
// Experiment variant with error handling
datablit.experiment.getVariant(
expId = "01K2JKVXR0J0ZWPX40XY8CAWBS",
entityId = "user123"
) { result ->
result.onSuccess { response ->
// Handle successful variant retrieval
println("Variant: ${response.variant}")
}.onFailure { error ->
// Handle error
println("Failed to get variant: ${error.message}")
}
}
Features
- Event Tracking: Track custom events with properties
- User Identification: Identify users with traits
- Automatic Batching: Events are automatically batched and sent to the server
- Offline Support: Events are queued locally and sent when network is available
- Lifecycle Tracking: Optional automatic tracking of application lifecycle events
- Rule Evaluation: Evaluate feature flags and rules for users with context parameters
- Experiment Variants: Get experiment variants for users
- Configurable: Customize flush intervals, batch sizes, and endpoints
Permissions
Ensure that the following permissions are declared in your AndroidManifest.xml
:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Note: Always adhere to Android's permission guidelines and request runtime permissions when necessary.
For more information, examples, and contributions, visit the Datablit Kotlin SDK GitHub repository.