Skip to main content

Sleep Cycle SDK - Android Documentation

Overview

The Sleep Cycle SDK for Android enables developers to integrate advanced sleep analysis capabilities into their applications. The SDK provides real-time sleep tracking using audio and motion sensors, delivering detailed sleep insights and events throughout the night.

System Requirements

Minimum Android API Level:
  • Min SDK: API level 28 (Android 9.0 Pie)
  • Compile SDK: API level 36
Kotlin:
  • Kotlin Version: 1.9+ (JVM target 11)
  • The SDK is written in Kotlin and provides a Kotlin-first API

Installation

Find the latest version on Maven Central.

Groovy DSL

Add the Sleep Cycle SDK dependency to your build.gradle:
dependencies {
    implementation "com.sleepcycle.sdk:sdk-android:<latest-version>"
}

Kotlin DSL

Add the Sleep Cycle SDK dependency to your build.gradle.kts:
dependencies {
    implementation("com.sleepcycle.sdk:sdk-android:<latest-version>")
}

Prerequisites

Permissions

The SDK requires microphone access for audio-based sleep analysis:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
The SDK automatically includes the WAKE_LOCK permission in its manifest to keep the device awake during analysis:
<uses-permission android:name="android.permission.WAKE_LOCK" />

Keeping the analysis active using a foreground service

To ensure continuous sleep analysis throughout the night, you must implement a foreground service. This prevents Android from terminating the analysis process during extended periods. It is up to the host app to start the foreground service correctly. The service must declare appropriate foreground service types in its manifest to specify what system resources it needs access to. For sleep analysis, you’ll typically need the health or microphone service types, which grant access to health sensors and microphone respectively.

General

It’s typical to call initialize() during application startup, often in your Application subclass’s onCreate() method. This ensures the SDK is ready when your activities need it. The SDK maintains its state across configuration changes. The SDK is thread safe and can be called from any thread.

Initialize the SDK

The SDK requires authentication before use. The initialization process validates your credentials and determines available features.
import com.sleepcycle.sdk.SleepCycleSdk

try {
    val features = SleepCycleSdk.initialize(
        context = applicationContext,
        apiKey = "your-api-key-here"
    )
    Log.d("SDK", "Authorized with features: $features")
} catch (e: Exception) {
    Log.e("SDK", "Authorization failed: ${e.message}")
}

Start a sleep analysis session

Once initialized, you can start a sleep analysis session:
import com.sleepcycle.sdk.SleepAnalysisConfig

SleepCycleSdk.startAnalysis(
    config = SleepAnalysisConfig(
        useAudio = true,
        useAccelerometer = true
    )
)
Parameters:
  • dataSource: Optional custom data source. When null, the SDK uses live device sensors (microphone and accelerometer)
  • config: Configuration object specifying which sensors to use

Stop a session

To stop an active analysis session and retrieve the results:
val result: AnalysisResult? = SleepCycleSdk.stopAnalysis()

result?.let { analysisResult ->
    val statistics = analysisResult.statistics
    val events = analysisResult.eventsByType

    Log.d("SDK", "Sleep duration: ${statistics.totalSleepDurationSeconds}")

    events?.get(EventType.SNORING)?.forEach { event ->
        Log.d("SDK", "Snoring detected from ${event.startTime} to ${event.endTime}")
    }
}

Real-time events

The SDK provides real-time event updates during analysis through a Flow API:
import com.sleepcycle.sdk.Event
import com.sleepcycle.sdk.EventType

lifecycleScope.launch {
    SleepCycleSdk.eventFlow.collect { events: List<Event> ->
        events.forEach { event ->
            when (event.type) {
                EventType.MOVEMENT -> handleMovement(event)
                EventType.SNORING -> handleSnoring(event)
                EventType.TALKING -> handleTalking(event)
                EventType.COUGHING -> handleCoughing(event)
            }
        }
    }
}

Audio clips

The SDK can capture short audio recordings when specific sleep events are detected, such as snoring, sleep talking, or coughing. To use audio clips, create an audio clips producer and pass it to startAnalysis:
import com.sleepcycle.sdk.*

// Configure which events trigger audio clips
val audioClipsConfig = AudioClipsConfig(
    activeTypes = hashMapOf(
        EventType.SNORING to EventTypeConfig(minDuration = 0.5),
        EventType.TALKING to EventTypeConfig(minDuration = 0.5)
    ),
    clipLength = 10.0  // Clip duration in seconds
)

// Implement receiver to handle captured clips
val audioClipsReceiver = object : AudioClipsReceiver {
    override fun onAudioClipReceived(audioClip: AudioClip) {
        // Process or store the audio clip
    }
}

// Create audio clips producer
val audioClipsProducer = SleepCycleSdk.createAudioClipsProducer(
    config = audioClipsConfig,
    receiver = audioClipsReceiver
)

// Pass to startAnalysis
SleepCycleSdk.startAnalysis(
    config = SleepAnalysisConfig(useAudio = true),
    audioEventListeners = listOf(audioClipsProducer)
)
Each AudioClip contains the audio samples as a FloatArray, the event type, start time, and sample rate.

Get the SDK state

Monitor SDK state changes using the StateFlow:
import com.sleepcycle.sdk.SdkState

val sdkStateFlow: StateFlow<SdkState> = SleepCycleSdk.sdkStateFlow
Get the current state:
val currentState: SdkState = SleepCycleSdk.getState()