Get Started

🚧

Follow the guideline for testing the sleep tracking

To accurately test Asleep Track 's sleep tracking/analysis, 
please follow the test environment guide. Please note that sleep analysis results obtained 
in environments not adhering to this guide may not accurately reflect actual sleep patterns.

  • Sleep measurement begins analysis when at least 20 minutes of audio is uploaded, after which it is analyzed every 5 minutes or 20 minutes depending on the plan (contract terms).
    πŸ”— Check Test Environment Guideline
  • We provide sample code that allows you to check the sleep measurement/analysis function of Asleep Track.
    πŸ”— Check Sample App
  • When using a sleep monitoring app with the Android SDK, it does not function properly if other recording apps are running at the same time.
    • On OS versions 9 and below, only one app can provide audio recording functionality, and only the first app to run can monopolize it. An error occurs when trying to run audio recording in other apps.
    • In OS versions 10 and above, when two or more audio recording apps are running, the most recently run audio-related app records normally, while the previously run apps are silenced. This results in an inability to obtain accurate results when analyzing sleep monitoring.
      Android Developer Site

πŸ“˜

In-app updates

Depending on the app user settings, the app could be updated automatically. If the app is updated automatically after starting the sleep tracking, unintentional app termination may cause abnormal termination of the sleep tracking.
You can prevent such unintended situations by using a feature called In-App Update, which allows you to receive updates in advance.

πŸ”— In-app updates guide

1. Requirements

1.1 Minimum requirements on Asleep SDK for Android

🚧

  • Android 8.0 (API level 26) or higher
  • Java 1.8 or higher
  • Android Gradle plugin 8.0 or higher

1.2 API Key

  • The API key is required to use the Asleep Track SDK.
  • For how to issue an API key, see this link [Generate API key]

2. Getting Ready

2.1 Install Asleep SDK and Settings

  1. Create a project using Android Studio.
  2. Add AsleepSDK.aar file in the [root]/app/libs folder of the generated project folder.
  3. Open the AndroidManifest.xml file to add permissions.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE"/>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
		...
    

πŸ“˜

The FOREGROUND_SERVICE permission is required when developing the app .

If you want the app to track sleep during entire night, you must use SDK with FOREGROUND_SERVICE.

https://developer.android.com/guide/components/foreground-services

When applying the Asleep SDK in your app, it is necessary to separate the process of the foreground service to prevent the app from being forcefully terminated due to updates in Google libraries (gms, chrome) during sleep measurement.

Please refer to the code of the sample app with separated FGS process for more details.

πŸ“˜

The REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission is required.

It can be helpful if you have the appropriate permissions to prevent you from falling into Doze mode.

https://developer.android.com/training/monitoring-device-state/doze-standby

  1. To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module's build.gradle file.
plugins {
  ...
}

android {
	...
}

dependencies {
		...
    implementation 'com.squareup.okhttp3:okhttp:4.11.0'
    implementation 'com.google.code.gson:gson:2.10'
    implementation fileTree(dir: 'libs', include: ['*.aar', '*.jar'], exclude: [])
}
  1. Write the source code to request permissions for using the microphone recording function.
ActivityCompat.requestPermissions(requireActivity(), 
                                  arrayOf(android.Manifest.permission.RECORD_AUDIO, 
                                          android.Manifest.permission.POST_NOTIFICATIONS), 
                                  0)

3. Sleep Tracking with Asleep SDK

3.1 Step 1: Initialize the Asleep SDK

  • Enter the 'apiKey' issued in section 1.2.
  • If 'userId' is null, a new userId will be generated.
  • Enter the URL of the proxy server in 'baseUrl'. If null, the default base URL will be used.
  • Enter the URL of the server where you want to receive the analysis results directly in 'callbackUrl'. If null, there will be no callback.
  • If your app has a nickname, enter it in the 'service'.
import ai.asleep.asleepsdk.Asleep
import ai.asleep.asleepsdk.data.AsleepConfig
import ai.asleep.asleepsdk.AsleepErrorCode

...

Asleep.initAsleepConfig(  
    context = applicationContext,  
    apiKey = "[input your apiKey]",  
    userId = "",  
    baseUrl = null,  
    callbackUrl = "",  
    service = "[input your AppName]",  
    object : Asleep.AsleepConfigListener {  
        override fun onSuccess(userId: String?, asleepConfig: AsleepConfig?) {  
            ...
            /* save userId and asleepConfig */
        }
    override fun onFail(errorCode: Int, detail: String) {
        ...
    }
})

3.2 Step 2: Create SleepTrackingManager

  • From initAsleepConfig, Enter AsleepConfig as a parameter.
import ai.asleep.asleepsdk.tracking.SleepTrackingManager

...

var sleepTrackingManager = Asleep.createSleepTrackingManager(asleepConfig, object : SleepTrackingManager.TrackingListener {                           
    override fun onCreate() {
    }

    override fun onUpload(sequence: Int) {
    }
    
    override fun onClose(sessionId: String) {
        ...
        /* save sessionId */
    }
    
    override fun onFail(errorCode: Int, detail: String) {
    }
})

3.3 Step 3: Start Tracking

  1. Start Recording
  • When you start, the sequence number is called back every 30 seconds from the onUpload function of the listener that was registered when the SleepTrackingManager was created.
sleepTrackingManager?.startSleepTracking()
  1. Analyze during Recording
sleepTrackingManager?.requestAnalysis(object : SleepTrackingManager.AnalysisListener {  
    override fun onSuccess(session: Session) {  
        Log.d("", "${session.toString()}")  
    }
}

3.4 Step 4: Stop Tracking

  • When you stop, the sessionId is called back from the onClose function of the listener registered at the time of the SleepTrackingManager creation.
sleepTrackingManager?.stopSleepTracking()

3.5 Step 5: Create Reports

  • From initAsleepConfig, enter AsleepConfig as a parameter.
val reports = Asleep.createReports(asleepConfig)

3.6 Step 6: Get Report

  1. Receive one SessionID result
  • Enter sessionID when sleepTracking is stopped as a parameter.
reports?.getReport(sessionId, object : Reports.ReportListener {
    override fun onSuccess(report: Report?) {
    }

    override fun onFail(errorCode: Int, detail: String) {
    }
})
  1. Get results by date
val today = LocalDate.now()
reports?.getReports(today.minusDays(7).toString(), today.toString(), "DESC", 0, 20, object : Reports.ReportsListener {
    override fun onSuccess(reports: List<SleepSession>?) {
    }

    override fun onFail(errorCode: Int, detail: String) {
    }
})

3.7 Step 7: Remove Session

  1. Deleting recording history
  • Enter SessionID to delete the corresponding recording history.
reports?.deleteReport(sessionId, object : Reports.DeleteReportListener {
    override fun onSuccess(sessionId: String?) {
    }

    override fun onFail(errorCode: Int, detail: String) {
    }
})
  1. Deleting all my information
  • Deletes the userId and all measured records. The deleted userId is no longer available.
Asleep.deleteUser(object : Asleep.DeleteUserIdListener {
    override fun onSuccess(userId: String?) {
    }

    override fun onFail(errorCode: Int, detail: String) {
    }
})

3.8 Step 8: Continue Session

  • Available from v2.3.0

In the Android OS, the Google Play Services package sometimes updates, which can lead to the system forcibly terminating and restarting an app's foreground service. To address this, functionality is provided to continue the operation of the sleepTrackingManager.

Firstly, when the foreground service is restarted by the system, the LifecycleService()'s onStartCommand function is called.

At this time, if there is an unfinished session as determined by the Asleep.hasUnfinishedSession function, the AsleepConfig stored inside the AsleepSDK can be retrieved. A new sleepTrackingManager is then created, and startSleepTracking is called to continue tracking.

private var asleepConfig: AsleepConfig? = null
private var sleepTrackingManager: SleepTrackingManager? = null
...
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 
  super.onStartCommand(intent, flags, startId)

	if(Asleep.hasUnfinishedSession(applicationContext)) {
    asleepConfig = Asleep.getSavedAsleepConfig(applicationContext, BuildConfig.ASLEEP_API_KEY)
    sleepTrackingManager = Asleep.createSleepTrackingManager(asleepConfig, object : SleepTrackingManager.TrackingListener {
			override fun onCreate() {
        ...
      }
      override fun onUpload(sequence: Int) {
      	...
      }
      override fun onClose(sessionId: String) {
      	...
      }
      override fun onFail(errorCode: Int, detail: String) {
      	...
      }
    }
    ...
    sleepTrackingManager?.startSleepTracking()
  }
  ...
}