Sleep is a crucial think about our on a regular basis life. Good sleeping habits play a significant function in bodily well being and general well-being. With Galaxy Watch and Samsung Well being, customers can observe their sleep, consider its high quality, and get teaching to develop wholesome habits. When the consumer wakes up, the sleep knowledge is analyzed and the consumer can overview key sleep statistics and the way a lot time they spent in every sleep stage. Sleep teaching performance compares knowledge to earlier days, so the consumer can observe how their day by day routine enhancements affect their sleep high quality.

Galaxy Watch gadgets can even measure blood oxygen throughout sleep, and customers with a Galaxy Watch5 or increased can even observe their pores and skin temperature. When a telephone is used along with the look ahead to sleep monitoring, loud night breathing detection can be doable.

Sleep monitoring

You possibly can leverage Samsung Well being superior sleep monitoring and Well being Join API to create functions that may learn customers’ actual sleep knowledge and create customized sleep session data that may be synchronized to Samsung Well being.

This weblog demonstrates the way to use the Well being Join API to learn knowledge from Well being Join, work with session knowledge, and insert knowledge to Well being Join, utilizing sleep knowledge for instance. To observe together with the steps on this weblog, obtain the pattern software:

Sleep Recorder model 1.0

(128,0KB) Jan 15, 2024

For more information about Samsung Health and Health Connect, see Accessing Samsung Health Data through Health Connect..

Sleep knowledge synchronization with Well being Join

The Well being Join platform collects health-related knowledge and synchronizes it with Samsung Well being, enabling you to make use of it in your functions.

Sleep knowledge is created on a smartwatch when the consumer wakes up. The info should be transferred to a paired cellular system for processing. Knowledge switch is initiated when the cellular system is linked. The processed knowledge creates a sleep report, which Samsung Well being synchronizes to Well being Join. Switch and synchronization duties might be delayed, relying on processor availability.

Conditions

Implementing performance that makes use of well being knowledge in an software requires Well being Join library, HealthConnectionClient, and permissions.

Add Well being Join API library dependencies

To make use of the Well being Join API options in your software:

dependencies {
    // Add Well being Join library
    implementation "androidx.well being.join:connect-client:1.1.0-alpha06"
}

Configure the “AndroidManifest.xml” file

  • Declare the required permissions:
<uses-permission android:title="android.permission.well being.WRITE_SLEEP"/>
<uses-permission android:title="android.permission.well being.READ_SLEEP" />
  • Add <intent-filter> within the <exercise> part:
<intent-filter>
	<motion android:title="androidx.well being.ACTION_SHOW_PERMISSIONS_RATIONALE" />
</intent-filter>
  • Add the <activity-alias> factor required in Android 14:
<activity-alias
	android:title="ViewPermissionUsageActivity"
    android:exported="true"
    android:targetActivity=".MainMenuActivity"
    android:permission="android.permission.START_VIEW_PERMISSION_USAGE">
    <intent-filter>
    	<motion android:title="android.intent.motion.VIEW_PERMISSION_USAGE" />
        <class android:title="android.intent.class.HEALTH_PERMISSIONS" />
    </intent-filter>
</activity-alias>
  • Add <uses-permission> parts:
<uses-permission android:title="android.permission.well being.WRITE_SLEEP"/>
<uses-permission android:title="android.permission.well being.READ_SLEEP" />
  • Add the <queries> factor:
<queries>
	<package deal android:title="com.google.android.apps.healthdata" />
</queries>

Word that on this software we additionally use:

  <package deal android:title="com.sec.android.app.shealth" />

Including this factor is critical, since we’re going to open the Samsung Well being app. Nevertheless, in case you are considering utilizing solely the Well being Join API – the above half is just not required.

Get a HealthConnect shopper

The HealthConnectClient class is an entry level to the Well being Join API. It robotically manages the connection to the underlying storage layer and handles all IPC and serialization of the outgoing requests and the incoming responses.

It’s a good apply to make sure that the system working your software truly helps the Well being Join API library. The library is offered solely when the Well being Join software is put in on the system.

WordAndroid 14 Well being Join is a part of the system and is put in by default. Nevertheless in earlier variations, it is necessary to verify if Well being Join is current on the system.

Examine for Well being Join availability. Whether it is lacking, show an error and redirect the consumer to the app retailer if set up of the app is feasible:

when (HealthConnectClient.getSdkStatus(this)) {
  HealthConnectClient.SDK_UNAVAILABLE -> {
  // Error message
  }
  HealthConnectClient.SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED -> {
  // Error message
  strive {
  	startActivity(
      	Intent(
          	Intent.ACTION_VIEW,
          	Uri.parse("market://particulars?id=com.google.android.apps.healthdata"),
      	),
  	)
  } catch (e: ActivityNotFoundException) {
  	startActivity(
      	Intent(
          	Intent.ACTION_VIEW,
          	Uri.parse("https://play.google.com/retailer/apps/particulars?id=com.google.android.apps.healthdata"),
      	),
  	)
  }
}

If Well being Join is offered, get a HealthConnectClient class occasion:

non-public val healthConnectClient by lazy { HealthConnectClient.getOrCreate(context) }

Request consumer permissions

Your software should request permission from the consumer to make use of their well being knowledge.

  • Create a set of permissions for the required knowledge sorts. The permissions should match these you outlined within the AndroidManifest.xml file.
  val permissions = setOf(
    HealthPermission.getWritePermission(SleepSessionRecord::class),
    HealthPermission.getReadPermission(SleepSessionRecord::class),
)
  • Examine whether or not the consumer has granted the required permissions:
droop enjoyable hasAllPermissions(): Boolean {
	if (HealthConnectClient.sdkStatus(context) != HealthConnectClient.SDK_AVAILABLE) {
    	return false
    }
    return healthConnectClient.permissionController.getGrantedPermissions()
		.containsAll(permissions)
}
  • If not, launch the permission request:
if (!healthConnectManager.hasAllPermissions()) {
	requestPermissions.launch(healthConnectManager.permissions)
}
  • Create the permissions immediate:
non-public enjoyable createRequestPermissionsObject() {
	requestPermissions =
		registerForActivityResult(healthConnectManager.requestPermissionActivityContract) { granted ->
  			lifecycleScope.launch {
  				if (granted.isNotEmpty() && healthConnectManager.hasAllPermissions()) {
  					runOnUiThread {
						Toast.makeText(
                        	this@MainMenuActivity,
                         	R.string.permission_granted,
                            Toast.LENGTH_SHORT,
                          ) .present()
					}
				} else {
                	runOnUiThread {
                    	AlertDialog.Builder(this@MainMenuActivity)
                    	.setMessage(R.string.permissions_not_granted)
                  		.setPositiveButton(R.string.okay, null)
                		.present()
           		}
  			}
    	}
	}
}

Retrieve sleep knowledge from Well being Join

Within the pattern software, to show sleep knowledge, choose a date and faucet READ DATA. A listing of sleep classes for that day is displayed. When you choose a session, the appliance retrieves and shows its sleep stage data from Well being Join.

To retrieve and show sleep session knowledge:

  • Outline the specified time vary and ship it to Well being Join Supervisor. Since a sleep session can begin on the day earlier than the chosen date, make sure the appliance additionally retrieves sleep classes from the day gone by and later ignores the classes that don’t match the specified time vary.
val startTime = chosenDay.minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()
val endTime = startTime.plus(2, ChronoUnit.DAYS).minus(1, ChronoUnit.MILLIS)
val sleepSessions = healthConnectManager.readSleepSessionRecords(
	startTime,
    endTime,
)
  • Retrieve the record of sleep session information in Well being Join Supervisor. Create a ReadRecordsRequest object and ship it to Well being Join:
val request = ReadRecordsRequest(
	recordType = SleepSessionRecord::class,
    timeRangeFilter = TimeRangeFilter.between(begin, finish),
)
val response = healthConnectClient.readRecords(request)
return response.information
  • Show the information in a ListView on the appliance display:
for (session in sleepSessions) {
	sleepSessionRanges.add(TimeRange.between(session.startTime, session.endTime))
    val sessionStart = session.startTime.atZone(ZoneId.systemDefault()).format(
    	DateTimeFormatter.ISO_LOCAL_TIME,
  	)
    val sessionEnd = session.endTime.atZone(ZoneId.systemDefault()).format(
    	DateTimeFormatter.ISO_LOCAL_TIME,
    )
    sleepStagesLists.add(session.phases)
    sleepSessionsAdapter.add("Begin: $sessionStartttEnd: $sessionEnd GMT ${session.startZoneOffset}")
}
  • When a session is chosen, show its sleep stage particulars:
for (stage in sleepStagesLists[sleepSessionIndex]) {
	val stageStart = stage.startTime.atZone(ZoneId.systemDefault()).format(
    	DateTimeFormatter.ISO_LOCAL_TIME,
    )
    val stageEnd = stage.endTime.atZone(ZoneId.systemDefault()).format(
    	DateTimeFormatter.ISO_LOCAL_TIME,
    )
    val stageName = HealthConnectManager.enumToStageMap.getValue(stage.stage)
    sleepStagesAdapter.add("$stageStartt-t$stageEndtt$stageName")
}

WordThough knowledge is inserted to and saved in Well being Join in UTC time with time zone offset, knowledge retrieved from Well being Join is displayed in native time.

You possibly can extract Well being Join sleep knowledge from any supply, together with knowledge from Galaxy Watch. The next determine reveals a sleep session in Samsung Well being and the identical knowledge offered within the pattern software.

Sleep knowledge in Samsung Well being and pattern software

Create and insert sleep session knowledge

Well being Join not solely means that you can learn sleep knowledge that’s collected by way of Samsung Well being, it additionally allows you to manually insert sleep knowledge that may be synchronized to Samsung Well being.

To manually insert sleep knowledge to Well being Join, you could put together each a sleep session and sleep stage knowledge.
A session is a time interval throughout which a consumer performs an exercise, similar to sleeping. To organize a session, you could know its begin and finish time. Within the pattern software, an non-obligatory time zone offset can be applied, since knowledge in Well being Join database is saved in UTC.

If the session begin hour and minute is later than the top hour and minute, the session is interpreted as beginning on the day gone by. Within the following determine, the session is interpreted to have began at 22:00 on 2023-12-10 and ended at 06:00 on 2023-12-11.

Sleep session period

Within the following a part of the appliance, sleep phases might be added throughout the sleep session. So as to add a sleep stage, outline its begin time, finish time, and title. For compatibility with Samsung Well being, use the sleep stage names Awake, Gentle, REM, and Deep. Every outlined sleep stage is seen within the record. Ideally, sleep phases cowl your complete sleep session, however this isn’t a requirement for synchronizing with Samsung Well being.

Sleep stage creation

To create and add a sleep session to Well being Join:

  • Examine that the consumer has granted the required permissions:
if (!healthConnectManager.hasAllPermissions()) {
	showDialogInfo(R.string.permissions_not_granted_api_call)
    return@launch
}
  • Outline the sleep session begin and finish time:
val startTime = sleepSessionTimeRange.startDateTimeMillis
val endTime = sleepSessionTimeRange.endDateTimeMillis
val timezoneOffset = dateOfSleepEnd.offset
  • So as to add sleep stage knowledge to the session, create a SleepStage report for every stage
var sleepStagesList: ArrayList<SleepSessionRecord.Stage>

val sleepStage = SleepSessionRecord.Stage(
startTime = sleepStageStart,
                endTime = sleepStageEnd,
                stage = HealthConnectManager.stageToEnumMap.getValue(
                    activitySleepStagesBinding.spinStage.selectedItem.toString(),
                ),
)
sleepStagesList.add(sleepStage)
  • In Well being Join supervisor, create a sleep session report and embody the sleep stage record:
droop enjoyable insertSleepSessionRecord(
	sleepStartTime: Immediate,
    sleepEndTime: Immediate,
    timezoneOffset: ZoneOffset,
    phases: ArrayList<SleepSessionRecord.Stage>,
): Boolean {
	var wasInsertSuccessful = false
    strive {
    	val sleepSessionRecord = SleepSessionRecord(
        	sleepStartTime,
            timezoneOffset,
            sleepEndTime,
            timezoneOffset,
            "Sleep Report pattern",
            "This can be a sleep report pattern recorded by SleepRecorder app",
            phases,
        )
  • Insert the sleep session report into Well being Join:
var wasInsertSuccessful = false
strive {
    wasInsertSuccessful =
        healthConnectClient.insertRecords(listOf(sleepSessionRecord)).recordIdsList.isNotEmpty()
} catch (e: Exception) {
    Log.i(APP_TAG, "Error inserting report: " + e.message)
}

The sleep session is now in Well being Join and visual in Samsung Well being after knowledge synchronization. In Samsung Well being, go to the “Sleep” display. The inserted sleep session might be reviewed there with visualizations and evaluation similar to every other sleep session, similar to these tracked on a Galaxy Watch. Under is a sleep session from the pattern software:

Sleep session

Conclusion

This weblog has demonstrated how one can develop an software that retrieves knowledge from and inserts knowledge into Well being Join, making it seen within the Samsung Well being software after knowledge synchronization.