Access rich sleep data from Samsung Health measured by Galaxy wearables
access rich sleep data from samsung health measured by galaxy wearables objective create a health app for android devices, utilizing the samsung health data sdk to obtain samsung health's rich sleep data overview samsung health offers various features to monitor user health data, including automatic sleep recording the samsung health data sdk grants access to the collected data, allowing developers to filter it based on factors such as the device used or a specific timeframe this sdk obtains comprehensive sleep information, including sleep scores, sleep sessions, sleep stages, and associated data such as skin temperature and blood oxygen levels you can retrieve rich sleep data from samsung health using the samsung health data sdk and apply device and local time filters to refine your queries effectively set up your environment you will need the following android studio latest version recommended java se development kit jdk 17 or later android mobile device compatible with the latest samsung health version sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! health data sleep sample code 666 8 kb set up your android device click on the following links to set up your android device enable developer options run apps on a hardware device activate samsung health's developer mode to enable the developer mode in the samsung health app, follow these steps in the top-right, tap the ⋮ button of samsung health select settings > about samsung health tap the version number quickly 10 times or more if you are successful, the developer mode samsung health data sdk button is displayed select developer mode samsung health data sdk agree with notice of usage of the developer mode for reading data from samsung health with samsung health data sdk, turn on the developer mode for data read now, you can test your app with samsung health notethe samsung health developer mode is only intended for testing or debugging your application it is not for application users start your project in android studio, click open to open an existing project locate the downloaded android project sleepdiary from the directory and click ok check gradle settings before using the samsung health data sdk library, certain configurations are necessary these steps are already applied in the sample code provided the samsung-health-data-api-1 0 0 aar library is added to the app\libs folder, and included as a dependency in the module-level build gradle file in the same file, the gson library is also added as a dependency dependencies { implementation files "libs/samsung-health-data-api-1 0 0 aar" implementation libs gson } next, the kotlin-parcelize plugin is applied plugins { id "kotlin-parcelize" } lastly, the following entries are also added in the gradle > libs version toml file [versions] gson = "2 11 0" [libraries] gson = { module = "com google code gson gson", version ref = "gson" } request sleep data permissions the application requires the appropriate permissions and the user's agreement to share their health data for the app to read their sleep data from samsung health while this code lab focuses solely on datatypes sleep, it is important to recognize that other data types such as skin temperature and blood oxygen levels are also available during sleep these additional data types can be accessed using datatypes skin_temperature and datatypes blood_oxygen respectively go to app > kotlin+java > com samsung health sleepdiary > repository in the healthdatastorerepository kt file, navigate to the preparepermissionset function create a permission object consisting of sleep data type and read access type, and assign it to the sleeppermission variable permission indicates the unit of permission to obtain user consent to share data with the samsung health's data store it's a pair of datatype and accesstype permission companion object of datatype datatype, accesstype accesstype creates a permission /****************************************************************************************** * [practice 1] prepare permission set to receive sleep data * * ---------------------------------------------------------------------------------------- * * use the provided variable 'sleeppermission' which is currently null * create a permission object by calling 'permission of datatype datatype, accesstype accesstype ' function * use data type 'datatypes sleep' and access type 'accesstype read' * assign the permission object to 'sleeppermission' variable ******************************************************************************************/ fun preparepermissionset mutableset<permission> { val permissionset mutableset<permission> = mutablesetof var sleeppermission permission? = null // todo assign the ‘sleeppermission’ variable here using permission class apis sleeppermission? let { permissionset add sleeppermission } return permissionset } prepare a read request for sleep data in order to retrieve sleep data from samsung health, the client app should prepare a readdatarequest object and send it to the healthdatastore this read request includes filters such as localtimefilter or readsourcefilter to ensure that only the desired data is received moreover, if the user wears both a galaxy watch and a galaxy ring while sleeping, samsung health combines the data from both devices to create an integrated sleep session, providing the most accurate sleep data not setting the device filter allows access to the combined data in the healthdatastorerepository kt file, navigate to the preparereadsleeprequest function prepare a read request that retrieves data from a specific day within the past week and includes the option to specify a device filter for either a ring or a watch using the provided localtimefilter object, update the readrequestbuilder object you can take your time to familiarize yourself with the readdatarequest builder creation datatypes sleep readdatarequestbuilder function creates a builder for sleep data type setlocaltimefilter function, called on a builder object, adds a time filter to the request setsourcefilter function, called on a builder object, adds a read source filter to the request with an application filter and a device filter build function, called on a builder object, builds readdatarequest from the configuration of this builder readdatarequest it represents a request for read query over a period of time to get a list of original healthdatapoints readdatarequest dualtimebuilder<t> setlocaltimefilter localtimefilter localtimefilter sets the local time filter of the request readdatarequest dualtimebuilder<t> setsourcefilter sourcefilter readsourcefilter sets the source filter of the request readdatarequest build builds readdatarequest from the configuration of this builder /****************************************************************************************** * [practice 2] prepare a read request for sleep data * * ---------------------------------------------------------------------------------------- * * use the provided variable 'localtimefilter' * set a time filter by calling ' setlocaltimefilter localtimefilter ' on a 'readrequest' builder ******************************************************************************************/ fun preparereadsleeprequest localtimefilter localtimefilter, readsourcefilter readsourcefilter readdatarequest<healthdatapoint> { val readrequest = datatypes sleep readdatarequestbuilder // todo use the 'localtimefilter' variable here to set the time filter setsourcefilter readsourcefilter build return readrequest } learn how to receive a response from samsung health receiving sleep data from samsung health is done by sending a readdatarequest query to the healthdatastore notethis is a blocking call and should not be called from the main thread healthdatastore it is a proxy which provides a way to access samsung health data an application can access the data through operations healthdatastore provides, such as inserting, updating, deleting, reading, and aggregating data a healthdatastore instance can be obtained by healthdataservice getstore method dataresponse<t> abstract suspend fun <t datapoint> readdata request readdatarequest<t> reads a set of data from samsung health according to the given request this method returns the original data point which is not processed or aggregated the code below, which is already included in the project file, shows how to receive a response from samsung health val healthdatalist = healthdatastore readdata readrequest datalist understand how the collected sleep data is processed a sleep healthdatapoint is a specific type of healthdatapoint that contains samsung health sleep data it includes various fields that can be accessed by calling getvalue function on the data point some of the fields include duration - returns a duration object that indicates how long the sleep lasted sleep score - returns the calculated quality of the sleep sessions - returns a list of sessions during the sleep period if the user wakes up during sleep for an extended period, multiple sleep sessions may be generated within a single sleep data point additionally, each session can consist of various sleep stages including light, rem rapid eye movement , deep, or awake the code below, which is already included in the project file, shows how the collected sleep data is processed private fun preparesleepresult healthdata healthdatapoint sleepdata { healthdata let { val score int score = preparesleepscore it ? 0 val duration = it getvalue datatype sleeptype duration ? duration zero val sleepsessionlist = it getvalue datatype sleeptype sessions ? emptylist return sleepdata score, sleepsessionlist size, duration tohours toint , duration minushours duration tohours tominutes toint , it starttime, it endtime, extractsessions sleepsessionlist } } notesamsung health can also measure the user's blood oxygen level and skin temperature during sleep, if supported by the wearable device these values are associated to the sleep data in the samsung health data sdk an application can use the healthdatapoint’s unique id uid to create an associatedreadrequest and retrieve the blood oxygen level and skin temperature data associated with the sleep data point extract sleep score from a health data point most of the data accessible through the samsung health data sdk is stored as fields within data points these fields can be extracted by specifying the appropriate keys in the getvalue function in the healthdatastorerepository kt file, navigate to the preparesleepscore function read the sleep score field from the healthdatapointby by calling the getvalue function with the key datatype sleeptype sleep_score healthdatapoint it indicates each health data record saved in the samsung health's data store <t> t? getvalue field field<t> returns the value of the given field /****************************************************************************************** * [practice 3] extract a sleep score from the sleep data * * ---------------------------------------------------------------------------------------- * * use the provided variable 'sleepscore' * extract a sleep score from a health data point by calling 'healthdatapoint getvalue ' function * use field 'datatype sleeptype sleep_score' as an argument * assign the obtained sleep score to 'sleepscore' variable ******************************************************************************************/ fun preparesleepscore healthdatapoint healthdatapoint int? { var sleepscore int? = null // todo assign the 'sleepscore' variable here by extracting sleep score from 'healthdatapoint' return sleepscore } run unit tests for your convenience, an additional unit tests package is provided this package lets you verify your code changes even without using a physical phone right-click on com samsung health sleepdiary test > run 'tests in 'com samsung health sleepdiary' if you completed all the tasks correctly, you can see that all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to read your sleep data once the app starts, allow all permissions to read sleep data from samsung health and tap done afterwards, the app's main screen appears, displaying today's sleep data from all connected devices you can use the calendar or device filter to show sleep data from a different day or a specific device you can tap on any sleep data to see the list of sessions you can tap on any session to see details such as sleep stages you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a mobile health app that reads samsung health rich sleep data by yourself! if you are having trouble, you may download this file health data sleep complete code 666 4 kb to learn more about samsung health, visit developer samsung com/health