Write exercise data to Samsung Health
write exercise data to samsung health objective create an exercise app that can write data to samsung health app using samsung health data sdk notethis code lab demonstrates how to utilize samsung health data sdk to write exercise data, such as running activities, to the samsung health app it provides a step-by-step guide on integrating your app with the sdk and offers hands-on experience in creating sample exercise data with the correct exercise type furthermore, it explores how to construct an insert request using the prepared data, ensuring smooth integration with samsung health's data store overview samsung health provides a comprehensive suite of features to monitor users' health and well-being data, including exercise activities samsung health data sdk empowers apps to access selected health data from the samsung health app and also allows writing data to samsung health's data storage this means apps using the sdk can both retrieve and contribute to the health data stored in the samsung health app for more detailed information, refer to samsung health data sdk documentation page 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 samsung health app installed on the device 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 developer mode in the samsung health app, follow these steps in the top-right corner of samsung health, tap the ⋮ button select settings > about samsung health tap the version number quickly 10 times or more to display the developer mode buttons select developer mode samsung health data sdk agree to the notice of usage of the developer mode turn on the developer mode for data read input client id and access code, then select add to turn on the developer mode for data write writingthe samsung health developer mode is intended solely for testing or debugging your application this code lab involves writing health data to samsung health to test data writing, an access code for developer mode is required this access code is provided to samsung health partners you can submit a partner request through the developer site start your project in android studio, click new project to create your project select the project type from the phone and tablet category then, click the next button configure your project set the name and package name, which you need to register during the partnership request choose the save location where you want to store the project locally select the minimum sdk level for your app samsung health runs on devices with android 10 api level 29 or higher click finish once done noteessential code snippets for this code lab are provided in the next sections implement them in your app, and design your preferred architecture exception handling is not included in this content set up the gradle and import samsung health data sdk before using samsung health data sdk library, you need to configure your project with the necessary dependencies and plugins add the gson library gson is a dependency required for json serialization and deserialization add gson as a dependency in the module-level build gradle file dependencies { implementation libs gson } define the correct version of gson in the libs versions toml file [versions] gson = "2 13 2" [libraries] gson = { module = "com google code gson gson", version ref = "gson" } apply the kotlin-parcelize plugin the kotlin parcelize plugin simplifies the process of making kotlin classes parcelable in the libs versions toml file, define the version for the parcelize plugin [versions] parcelize = "2 3 20" [plugins] parcelize = { id = "org jetbrains kotlin plugin parcelize", version ref = "parcelize" } go to the project-level build gradle file and create an alias for the plugin plugins { alias libs plugins parcelize apply false } then, go back to module-level build gradle file and add the parcelize plugin plugins { alias libs plugins parcelize } download and import samsung health data sdk to use samsung health data sdk, follow these steps download the latest version of samsung health data sdk library from the samsung developer page in the downloaded zip file, find the samsung-health-data-api- version aar file in the libs folder in your project, create a new libs folder inside the app module move the downloaded samsung-health-data-api- version aar library into the newly created app>libs folder add the library as a dependency in the module-level build gradle file dependencies { implementation files "libs/samsung-health-data-api- version aar" } access the api after setting up the project and importing the sdk, you can access the api by creating an instance of healthdatastore from healthdataservice use the getstore method, ensuring you provide the appropriate context healthdataservice getstore appcontext with this healthdatastore object, the app is ready to access and manage the data stored in samsung health request exercise data permissions to access health data stored in samsung health, you need to request the appropriate permissions from the app's user each health data type has specific permissions for reading and writing operations this code lab focuses on obtaining write permission for exercise data before displaying the permission request dialog in the app, verify if the user has already granted the necessary permissions using the getgrantedpermissions permissions set<permission> function from the healthdatastore api var grantedpermissions = healthdatastore getgrantedpermissions permissionset if any required permissions are missing, request them using the requestpermissions permissions set<permission>, activity activity function healthdatastore requestpermissions permissionset, activity prior to this, ensure that you create a set of required permission objects permission indicates the unit of permission to obtain the user's consent to share their data with the samsung health app's data store each permission is granted for a pair of datatype and specific accesstype permission companion object of datatype datatype, accesstype accesstype creates a permission instance with the given data type and access type to prepare the permission set for writing exercise data, modify the preparepermissions function as follows /****************************************************************************************** * [practice 1] prepare the permission set to write exercise data * * ---------------------------------------------------------------------------------------- * * - use the provided variable 'permissionset', which is currently defined as an empty set * - inside the 'permissionset' declaration, create a permission object using * the 'permission of datatype datatype, accesstype accesstype ' function * - use the data type 'datatypes exercise' and the access type 'accesstype write' ******************************************************************************************/ private fun preparepermissions set<permission> { val permissionset = setof<permission> permission of datatypes exercise, accesstype read , // todo create the permission object for write here return permissionset } fulfill the code by creating a permission object utilizing the permission of function with datatypes exercise and accesstype write as parameters next, implement the logic to request exercise permissions suspend fun requestexercisepermissions activity activity boolean { val permissionset = preparepermissions var grantedpermissions = healthdatastore getgrantedpermissions permissionset return if grantedpermissions containsall permissionset { true } else { runcatching { grantedpermissions = healthdatastore requestpermissions permissionset, activity } onfailure { if it is healthdataexception { throw it } else { it printstacktrace } } grantedpermissions containsall permissionset } } now, your app asks the user to grant write permission for the exercise data type prepare exercise session data this section demonstrates how to create an exercisesession specifically for running it involves organizing and structuring exercise session data, which includes details such as start time, end time, duration, exercise type, distance, calories, and an exercise log containing heart rate, cadence, power, and speed values the data required for this task is already prepared in this code lab, so there's no need to prepare it manually to begin, create a list that holds the collected running data heart rate, cadence, power, and speed for simplicity, use a local class named exerciselogdata to store these values private data class exerciselogdata val heartrate float, val cadence float, val power float, val speed float private fun preparedata = listof exerciselogdata heartrate = 96 0f, cadence = 158 0f, power = 173 0f, speed = 0 78f , exerciselogdata heartrate = 113 0f, cadence = 162 0f, power = 186 0f, speed = 1 32f , exerciselogdata heartrate = 114 0f, cadence = 160 0f, power = 171 0f, speed = 2 26f , exerciselogdata heartrate = 128 0f, cadence = 172 0f, power = 207 0f, speed = 2 32f , exerciselogdata heartrate = 134 0f, cadence = 170 0f, power = 194 0f, speed = 1 56f , exerciselogdata heartrate = 138 0f, cadence = 160 0f, power = 176 0f, speed = 2 0f , exerciselogdata heartrate = 139 0f, cadence = 164 0f, power = 179 0f, speed = 2 12f , exerciselogdata heartrate = 140 0f, cadence = 162 0f, power = 164 0f, speed = 1 82f , exerciselogdata heartrate = 141 0f, cadence = 160 0f, power = 171 0f, speed = 1 96f , exerciselogdata heartrate = 138 0f, cadence = 170 0f, power = 176 0f, speed = 1 48f , exerciselogdata heartrate = 142 0f, cadence = 160 0f, power = 190 0f, speed = 1 66f , exerciselogdata heartrate = 139 0f, cadence = 164 0f, power = 197 0f, speed = 2 32f , exerciselogdata heartrate = 137 0f, cadence = 164 0f, power = 187 0f, speed = 1 36f , exerciselogdata heartrate = 140 0f, cadence = 156 0f, power = 179 0f, speed = 1 64f , exerciselogdata heartrate = 138 0f, cadence = 156 0f, power = 180 0f, speed = 1 42f , exerciselogdata heartrate = 136 0f, cadence = 158 0f, power = 178 0f, speed = 1 72f , exerciselogdata heartrate = 136 0f, cadence = 162 0f, power = 170 0f, speed = 1 7f , exerciselogdata heartrate = 134 0f, cadence = 160 0f, power = 170 0f, speed = 1 86f , exerciselogdata heartrate = 133 0f, cadence = 156 0f, power = 171 0f, speed = 1 6f , exerciselogdata heartrate = 133 0f, cadence = 158 0f, power = 180 0f, speed = 1 74f , exerciselogdata heartrate = 133 0f, cadence = 158 0f, power = 170 0f, speed = 1 9f , exerciselogdata heartrate = 129 0f, cadence = 156 0f, power = 160 0f, speed = 1 54f , exerciselogdata heartrate = 132 0f, cadence = 154 0f, power = 161 0f, speed = 1 72f , exerciselogdata heartrate = 129 0f, cadence = 158 0f, power = 167 0f, speed = 1 58f , exerciselogdata heartrate = 132 0f, cadence = 154 0f, power = 182 0f, speed = 1 98f , exerciselogdata heartrate = 137 0f, cadence = 158 0f, power = 179 0f, speed = 1 96f , exerciselogdata heartrate = 132 0f, cadence = 156 0f, power = 178 0f, speed = 1 52f , exerciselogdata heartrate = 133 0f, cadence = 164 0f, power = 164 0f, speed = 2 1f , exerciselogdata heartrate = 135 0f, cadence = 158 0f, power = 164 0f, speed = 1 7f , exerciselogdata heartrate = 137 0f, cadence = 158 0f, power = 171 0f, speed = 2 1f , exerciselogdata heartrate = 138 0f, cadence = 160 0f, power = 169 0f, speed = 1 92f next, use the data generated by the preparedata function to create exerciselog entries these logs represent time-series data captured at different stages throughout the exercise to implement this process, create a list of exerciselog instances with timestamps calculated at 10-second intervals private fun preparerunningexerciselog starttime instant list<exerciselog> { var secondstoadd = 0l val secondsinterval = 10l val exerciselog = mutablelistof<exerciselog> val exercisedata = preparedata exercisedata foreach { data -> exerciselog add exerciselog of timestamp = starttime plusseconds secondstoadd , heartrate = data heartrate, cadence = data cadence, count = null, power = data power, speed = data speed secondstoadd += secondsinterval } return exerciselog } the exercisesession object adds the prepared list of exerciselog entries additionally, it calculates and includes mean and maximum values for various metrics this allows users to view comprehensive exercise statistics after inserting the data into samsung health private fun prepareexercisesession starttime instant, endtime instant exercisesession { val exerciselog = preparerunningexerciselog starttime val session = exercisesession builder setstarttime starttime setendtime endtime setexercisetype datatype exercisetype predefinedexercisetype running setduration duration between starttime, endtime setdistance 547f setcalories 55f setlog exerciselog setmeanheartrate 132 8f setmaxheartrate 142f setmeancadence 160 2f setmaxcadence 172f setmeanpower 176 3f setmaxpower 207f setmeanspeed 1 76f setmaxspeed 2 32f build return session } notethe exercisesession object is created using exercisesession builder and its build function to create a valid exercisesession, all mandatory fields must be set correctly if any mandatory fields are missing or if the end time is earlier than the start time, an invalidrequestexception will be thrown this ensures the integrity and accuracy of the exercise session data prepare healthdatapoint after preparing the session, create an instance of healthdatapoint a healthdatapoint is a fundamental data structure in samsung health data sdk that represents a single data entry it includes essential fields such as start time, end time, and data type, as well as additional fields like exercise type and exercise session it's crucial to ensure that all mandatory fields are properly set for exercisetype, specifying datatype exercisetype exercise_type and including sessions are mandatory notestart time, end time, and data type are always mandatory for healthdatapoint other mandatory fields may vary depending on the data type if the required fields are not set correctly, an invalidrequestexception will be thrown to initialize a healthdatapoint instance, use the builder method set the properties, such as start time and end time, by calling the setstarttime and setendtime functions, respectively for additional properties like exercise data type and session, use the addfielddata function healthdatapoint a healthdatapoint is an individual record of health data saved in the samsung health app's data store healthdatapointbuilder addfielddata field field<t>, value t? set a value of a specified field /****************************************************************************************** * [practice 2] add missing information to healthdatapoint * - data type of exercise, * - previously prepared exercise session * * ---------------------------------------------------------------------------------------- * * in todo 1 * - use the addfielddata field field<t>, value t? function to add the exercise data type * - use datatype exercisetype exercise_type as the field, and datatype exercisetype predefinedexercisetype running as the value * * in todo 2 * - use the addfielddata field field<t>, value t? function to add sessions data * - use datatype exercisetype sessions as the field, and the local variable 'sessions', * which contains a list with previously prepared session ******************************************************************************************/ private fun preparehealthdatapoint healthdatapoint { val fiveminutesasseconds = 300l val starttime = instant now minusseconds fiveminutesasseconds val endtime = instant now val sessions = listof prepareexercisesession starttime, endtime val data = healthdatapoint builder setstarttime starttime setendtime endtime // todo 1 add exercise of running here // todo 2 add session data here build return data } call addfielddata with datatype exercisetype exercise_type set to datatype exercisetype predefinedexercisetype running the parameters datatype exercisetype sessions and the local variable sessions, which contain the prepared exercise data create an insert request you can create an insert request to add the prepared healthdatapoint object to the healthdatastore every datatype, such as exercisetype, that supports write operations includes an insertdatarequestbuilder, which simplifies the process of building and configuring the request before submission to include the data in the request, use the adddata function once the request is fully configured, it is passed into the insertdata method this method is responsible for adding the prepared healthdatapoint data to the healthdatastore upon successful execution, the data is stored and available for viewing in the samsung health app now, use the insertdatarequest api to include the healthdatapoint in the request insertdatarequest insertdatarequest represents a request for inserting a healthdatapoint that an app creates into the samsung health app insertdatarequest basicbuilder adddata data t adds a data point created by the app to the request /****************************************************************************************** * [practice 3] add a healthdatapoint object to the write request * * ---------------------------------------------------------------------------------------- * * - use the adddata data t function to add the healthdatapoint object to the write request * - as a parameter, use the local variable 'healthdatapoint', which contains the previously prepared data ******************************************************************************************/ suspend fun writeexercise { val healthdatapoint = preparehealthdatapoint val writerequest = datatypes exercise insertdatarequestbuilder // todo add health data point here build healthdatastore insertdata writerequest } call the adddata function and pass the local variable healthdatapoint, which contains the previously prepared instance of healthdatapoint, as a parameter at this point, your app is fully capable of inserting running data into the samsung health data storage check exercise data once the data is successfully inserted, it becomes accessible to applications that read from the samsung health storage you can verify the inserted exercise data using two methods the dataviewer tool and the samsung health app dataviewer the dataviewer tool is a utility designed to help developers and users inspect and validate data stored in the samsung health app it provides a detailed view of the data, including exercise sessions and exercise logs, allowing you to confirm that the inserted data is correctly stored and structured to use the dataviewer tool locate its apk in the tool folder within the downloaded sdk package install and launch the app on your mobile device in the app, select the exercise item from the list of data types grant the necessary permissions when prompted click the inserted data point to see its details in sessions, click the link to view the details from the exercise sessions details, you can view the log containing a list of each individual entry verify that the information displayed matches the data you inserted, such as start time, end time, exercise type, and other details samsung health the inserted data can also be directly viewed in the samsung health app this app offers a comprehensive overview of the workout data, enabling users to verify that the exercise details—such as start time, end time, exercise type, distance, calories burned, and exercise log—are accurately stored and displayed to verify data in samsung health open the samsung health app on your phone navigate to the workout this week card find the inserted exercise in the all exercises list tap on the exercise to view its details you can view all statistics, including mean and max values for each workout parameter, presented on the chart verify that the displayed information matches the data you inserted, including start time, end time, exercise type, distance, calories burned, and the details from the exercise log you're done! congratulations! you have successfully completed the goal of this code lab now, you can create a mobile health app that can write exercise data to samsung health on your own! to learn more, explore samsung health data sdk