Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Filter
Develop Health
apioverviewpackageclasstreedeprecatedindex com samsung android sdk healthdata class healthconnectionerrorresult java lang object com samsung android sdk healthdata healthconnectionerrorresult public final class healthconnectionerrorresult extends object this class handles errors raised by connection failure to the health data store considerations for connection failure a partner app works with samsung health the partner app can meet the following error cases when it connects to samsung health connection error description platform_not_installed samsung health is not installed old_version_platform installed samsung health's version is old platform_disabled samsung health is disabled user_agreement_needed the user didn't agree to samsung health's terms & conditions and privacy policies user_password_needed samsung health is locked by the user password handling connection exceptions samsung health sdk for android helps you to handle all available error cases with healthconnectionerror when your application connects to the health data store healthconnectionerror is retrieved in healthdatastore connectionlistener's event handler and all samsung health's partner applications need to check the health data store's connection error mandatorily the following example shows how to handle the connection error public class mainactivity extends activity { private healthdatastore mstore; private healthconnectionerrorresult mconnerror; private static mainactivity minstance = null; @override public void oncreate bundle savedinstancestate { // mstore = new healthdatastore this, mconnectionlistener ; mstore connectservice ; } @override public void ondestroy { mstore disconnectservice ; // } private final healthdatastore connectionlistener mconnectionlistener = new healthdatastore connectionlistener { @override public void onconnected { // connected } @override public void onconnectionfailed healthconnectionerrorresult error { // connection fails showconnectionfailuredialog error ; } @override public void ondisconnected { // connection is disconnected } }; private void showconnectionfailuredialog healthconnectionerrorresult error { alertdialog builder alert = new alertdialog builder this ; mconnerror = error; if mconnerror hasresolution { switch error geterrorcode { case healthconnectionerrorresult platform_not_installed message = "please install samsung health"; break; case healthconnectionerrorresult old_version_platform message = "please upgrade samsung health"; break; case healthconnectionerrorresult platform_disabled message = "please enable samsung health"; break; case healthconnectionerrorresult user_agreement_needed message = "please agree to samsung health policy"; break; default message = "please make samsung health available"; break; } } else { // in case that the device doesn't support samsung health, // hasresolution returns false also alert setmessage r string msg_conn_not_available ; } alert setpositivebutton r string ok, dialog, id -> { if error hasresolution { error resolve mainactivity this ; } } ; if error hasresolution { alert setnegativebutton "cancel", null ; } alert show ; } } since 1 0 0 see also healthdatastore connectionlistener field summary fields modifier and type field and description static int connection_failure the connection is not established in the health data framework static int old_version_platform the version of the health data framework is outdated to cooperate with sdk static int old_version_sdk the sdk's data library version is outdated to cooperate with the samsung health's health data framework static int platform_disabled the health data framework is disabled static int platform_not_installed samsung health is not installed static int platform_signature_failure it fails to check the signature of the health data framework static int timeout the connection time exceeded the limit static int unknown unknown error static int user_agreement_needed the user did not agree to terms and conditions, and privacy policy of samsung health yet static int user_password_needed the user cancels the password input explicitly on the password pop-up window method summary all methods instance methods concrete methods modifier and type method and description int geterrorcode gets the error code of connection failure boolean hasresolution checks whether the given error has a resolution void resolve activity activity resolves an error with an activity which is able to get the user's feedback for possible error cases field detail unknown public static final int unknown unknown error its constant value is 0 since 1 0 0 see also constant field values connection_failure public static final int connection_failure the connection is not established in the health data framework its constant value is 1 since 1 0 0 see also constant field values platform_not_installed public static final int platform_not_installed samsung health is not installed to resolve it if your app runs on android 11, check your app manifest whether the "<queries>" element is added see the app manifest guide call resolve android app activity it leads the user to install samsung health on an app seller site its constant value is 2 since 1 0 0 see also resolve android app activity , constant field values old_version_sdk public static final int old_version_sdk the sdk's data library version is outdated to cooperate with the samsung health's health data framework to resolve it apply the latest data library to your app if your app uses the latest data library, create an activity to update to install your latest app its constant value is 3 since 1 0 0 see also constant field values old_version_platform public static final int old_version_platform the version of the health data framework is outdated to cooperate with sdk to resolve it, call resolve android app activity it leads the user to install the latest samsung health on an app seller site its constant value is 4 since 1 0 0 see also resolve android app activity , constant field values timeout public static final int timeout the connection time exceeded the limit its constant value is 5 since 1 0 0 see also constant field values platform_disabled public static final int platform_disabled the health data framework is disabled to resolve it, call resolve android app activity it leads the user to activate samsung health through the phone's settings its constant value is 6 since 1 0 0 see also resolve android app activity , constant field values user_password_needed public static final int user_password_needed the user cancels the password input explicitly on the password pop-up window some devices can request a password to protect the user's data the password for the health data access can be registered in samsung health by the user then the user can enter the password through the password pop-up window if the predetermined time passed without the valid password input, timeout occurs its constant value is 7 since 1 0 0 see also constant field values platform_signature_failure public static final int platform_signature_failure it fails to check the signature of the health data framework its constant value is 8 since 1 0 0 see also constant field values user_agreement_needed public static final int user_agreement_needed the user did not agree to terms and conditions, and privacy policy of samsung health yet the health data framework is not activated before agreement to resolve it, call reslove it leads the user to the samsung health's service agreement page its constant value is 9 since 1 0 0 see also resolve android app activity , constant field values method detail geterrorcode public int geterrorcode gets the error code of connection failure usually it is called in healthdatastore connectionlistener onconnectionfailed healthconnectionerrorresult it's required to resolve the error depending on its returned error code returns the error code since 1 0 0 hasresolution public boolean hasresolution checks whether the given error has a resolution whether the device supports samsung health the sdk supports marshmallow and above android devices including non-samsung devices and it works with samsung health there is no connection issue on most devices but it is not available occasionally depending on the device's specification this api lets you know whether the device supports samsung health the returned false involves that the device is not available for samsung health precondition check the network connection permission android permission internet returns true if the platform provides a resolution for the error call resolve activity false in the following cases if the device doesn't support samsung health if there is no resolution for the error since 1 0 0 resolve public void resolve activity activity resolves an error with an activity which is able to get the user's feedback for possible error cases it handles the following errors and operations show a proper message for each error case in your application before call this method error operation platform_not_installed linked to the application installation page old_version_platform linked to the application installation page platform_disabled linked to settings of the device to turn on samsung health user_agreement_needed linked to the starting screen of samsung health to get the user's agreement precondition check the network connection permission android permission internet parameters activity - an activity which resolves the error with the user's feedback usually it's the main activity of your application throws illegalargumentexception - if the specified input is null or invalid since 1 0 0
Develop Health
docrelease note release date july 31, 2025 release version v1 0 0 target device the samsung health data sdk supports android smartphones including non-samsung android smartphones sdk content content description /docs api reference programming guide /libs sdk’s library import it in your app project - samsung-health-data-api aar /sample-code app project including sample codes it’s project name is - healthdiary /tool dataviewer it displays saved health data in the samsung health app features samsung health data sdk enable an app to access samsung health’s selected data health data store an app can read or aggregate the following data with the sdk’s apis the user’s health data is kept secured in the health data store available data operators can be different for each data type active calories burned goal active time goal activity summary blood glucose blood oxygen blood pressure body composition body temperature energy score exercise with exercise location floors climbed heart rate nutrition nutrition goal skin temperature sleep sleep goal steps step goal water intake water intake goal user profile data permission the use’s data can be accessed after getting the user’s consent clearly data access android apps using the samsung health data sdk can read, insert, update, or delete data within the scope of user consent device manager saved health data in samsung health can be from various connected devices like a galaxy watch, galaxy ring and a weight scale devicemanager provides source device information of saved health data in the samsung health’s data store restrictions samsung health data sdk requires samsung health v6 30 2 or later version installation samsung health runs on devices with android 10 api level 29 or above it is available on all samsung smartphones and also non-samsung android smartphones the sdk doesn’t support an emulator measured data by samsung health data sdk is for fitness and wellness only, not for the diagnosis or treatment of any medical condition changes 1 0 0 - july 31, 2025 [new] data type the following data type has been added bodytemperaturetype operations for reading, inserting, updating and deleting data, as well as reading changes are supported property the following property has been added to the exercisesession class vo2max enum a new accessory type has been added to the accessorytype class thermometer the following predefined exercise types have been added to the exercisetype predefinedexercisetype class open_water_swimming zumba data operations bloodoxygentype inserting, updating, and deleting operations are supported exercisetype inserting, updating, and deleting operations are supported floorsclimbedtype reading, inserting, updating, and deleting, as well as reading changes operations are supported sleeptype inserting, updating, and deleting operations are supported only sleep_score is not writable [changed] nullable properties the following properties have been updated to be nullable swimmingintervals totaldistance totalduration predefined exercise types the following predefined exercise types of the exercisetype predefinedexercisetype class have been changed biking from bike ice_hokey from ice_hoking jump_rope from rope_skipping pool_swimming from swimming snorkeling from snorkelling soccer from football stationary_biking from exercise_bike stair_climbing from floor_climb stair_climbing_machine from stair_machine other from other_workout developer mode menu name from version 6 30 of the samsung health app, the name of the developer mode menu, which is a feature of the samsung health data sdk, has been changed to 'developer mode samsung health data sdk 1 0 0 beta2 - february 26, 2025 [new] data type the following data type has been added reading data and retrieving changed data is available energyscoretype inserting, updating, and deleting data inserting, updating, and deleting data has been supported for the following data types body composition blood glucose blood pressure heart rate nutrition water intake the following apis have been added in com samsung android sdk health data healthdatastore for inserting data insert type writeable<t>, builder suspend insertdatarequest basicbuilder<t> -> insertdatarequest basicbuilder<t> insertdata request insertdatarequest<t> insertdataasync request insertdatarequest<t> the following apis have been added in com samsung android sdk health data healthdatastore for updating data update type writeable<t>,builder suspend updatedatarequest basicbuilder<t> -> updatedatarequest basicbuilder<t> updatedata request updatedatarequest<t> updatedataasync request updatedatarequest<t> the following apis have been added in com samsung android sdk health data healthdatastore for deleting data delete type writeable<t>,builder suspend deletedatarequest basicbuilder -> deletedatarequest basicbuilder deletedata request deletedatarequest deletedataasync request deletedatarequest the com samsung android sdk health data data healthdatapoint builder class has been added to insert or update health data the following classs have been added in com samsung android sdk health data request insertdatarequest updatedatarequest deletedatarequest access code developer mode's access code to insert, update, or delete data when testing apps, the access code is required on the developer mode page the access code can be obtained by requesting partnership device manager the following apis have been added in com samsung android sdk health data devicemanager to register health devices and getting device information registerdevice request deviceregistrationrequest registerdeviceasync request deviceregistrationrequest getdevicebyseed getdevicebyseedasync getowndevices getowndevicesasync the com samsung android sdk health data request deviceregistrationrequest has been added to register a health device the following classes and apis have been added related to the accessory device com samsung android sdk health data device accessorytype device accessorybuilder device companion accessorybuilder device isof type accessorytype others the following apis have been added in com samsung android sdk health data request idfilter builder addclientdataid clientdataid string fromclientdataid clientdataid string the following error code has been added in com samsung android sdk health data error err_no_ownership_to_write the following property has been added in the bloodglucosetype medication_taken [changed] the bloodglucosetype meal_status property has been changed to be required 1 0 0 beta1 - october 21, 2024 the first sdk release [new] reading the following samsung health's data is available activity summary active calories burned goal active time goal blood glucose blood oxygen blood pressure body composition exercise exercise location floor climbed heart rate nutrition nutrition goal skin temperature sleep sleep goal steps step goal water intake water intake goal user profile data permission requesting data permissions is required to read health data device manager the device type like a galaxy watch, galaxy ring and a weight scale can be known with the device manager developer mode for development and debugging purposes, developers can activate the developer mode to interact with the samsung health data sdk within their android apps to distribute the app using the samsung health data sdk, request partnership you can find more information in the sdk process
Develop Health
docapp creation process creating an android app is available with the samsung health data sdk to develop and run an app using the sdk, the following process is required 1 sdk download download the samsung health data sdk and check the sdk content samsung health data sdk v1 0 0 1 81 mb 2 enabling the developer mode you can check the sdk operation by turning on the samsung health's developer mode notethe samsung health's developer mode is intended solely for app development purposes it should not be used for your app users if you want to run your app without utilizing the developer mode, please submit the partner request writing health data to samsung health to write health data to samsung health from an app, the access code is required you can request partnership and receive the access code after an approval 3 developing your app create an android app project with importing the sdk library if you encounter any issue using the sdk, please submit your query on the developer support 4 partnership request to distribute your app please submit partner request before your app distribution your app's information including the app package name and signature sha-256 will be registered in the samsung health's system after an approval otherwise, the app using the samsung health data sdk works only with the developer mode turned on our partnership is an exclusive service for the samsung health data sdk that allows users to discover engaging health and fitness apps partnership request
Develop Health
docmigrating exercise app to samsung health data sdk as of july 2025, samsung health sdk for android has been deprecated while existing functionality will continue to operate for now, developers are strongly encouraged to migrate to samsung health data sdk to ensure long-term compatibility and continued support both sdks provide access to health data, stored in samsung health app this data may originate directly from the app itself, as is the case for steps, or from connected wearable devices such as the ring, watch or dedicated medical equipment samsung health data sdk offers several advantages over its predecessor more user-friendly api support for more features such as suspend functions cleaner and more compact source code for more information and resources, refer to samsung health data sdk introduction the steps on this page help you easily understand the overall process of migrating your app that reads and inserts exercise data to use the samsung health data sdk prerequisites set up your environment before you begin the integration, make sure that you have the following installed and ready android studio java jdk 17 or higher android mobile device compatible with the latest version of samsung health set up your android device refer to the following resources to set up your android device turn on the phone’s developer options run apps on a hardware device download samsung health data sdk visit samsung health data sdk page to download samsung health data sdk enable samsung health data sdk’s developer mode previously, samsung health sdk for android required developers to submit a partner request to gain access, which needed to be applied for and approved before use now, with samsung health data sdk, you can download and use the sdk in developer mode without submitting a partner request to enhance convenience for developers, samsung health data sdk has improved its developer mode functionality if you only need to read data from samsung health app, you can activate developer mode and proceed with development and testing without requiring a partner request for more information on developer mode, please refer to developer mode if you want to test writing data to samsung health app using samsung health data sdk or distribute your app, you need to obtain a partnership for samsung health data sdk you can request it by following this process project setup import sdk library replace samsung health sdk for android aar file in your project navigate to app/libs in your project replace samsung-health-data-1 5 1 aar with samsung-health-data-api-1 0 0 aar from the downloaded sdk package app manifest when using samsung health data sdk, your app’s manifest should no longer include any entries related to health data permissions gradle settings sdk dependency update your module-level build gradle to include the correct dependency replace dependencies { implementation files "/libs/samsung-health-data-1 5 1 aar" } with entry samsung health data sdk version independent dependencies { implementation filetree mapof "dir" to "libs", "include" to listof "* aar" } other configuration add gson library to the dependencies of module-level build gradle dependencies { implementation "com google code gson gson 2 13 2" } apply the kotlin-parcelize plugin to the module-level build gradle plugins { id "kotlin-parcelize" } additionally, check the module-level build gradle file and include any other dependencies required by your implementation connect with samsung health after completing the initial setup, you are ready to connect your app to samsung health to access exercise data in the following paragraphs, we are going to show you how to migrate specific elements of logic from samsung health sdk for android to samsung health data sdk samsung health sdk for android with samsung health sdk for android, establishing a connection requires the following import healthdatastore import com samsung android sdk healthdata healthdatastore declare healthdatastore instance with lateinit var healthdatastore healthdatastore initialize the instance and start the connection with healthdatastore = healthdatastore context, listener also { it connectservice } these are the provided arguments listener – healthdatastore connectionlistener instance, used to observe the connection results and handle connection failures context – typically app or activity context samsung health data sdk with samsung health data sdk, establishing a connection is simpler, as there is no need to implement a connection listener import the following class import com samsung android sdk health data healthdatastore notethe class name healthdatastore class is the same as in samsung health sdk for android however, their import directories differ make sure that you are using the correct path we can now establish the connection and obtain a healthdatastore instance by calling healthdataservice getstore context here, context can be your app context request permissions upon successful connection to samsung health, your app must ensure that it has permissions to access the health data from samsung health since samsung sdks enforce data access control, defining and checking permissions must be done before any data operations are performed samsung health sdk for android in samsung health sdk for android, you must first create a permission set, specifying which data type your app intends to access and the access permission read or write for example, to request read and write permissions for exercise data val permissions = setof healthpermissionmanager permissionkey healthconstants exercise health_data_type, healthpermissionmanager permissiontype read , healthpermissionmanager permissionkey healthconstants exercise health_data_type, healthpermissionmanager permissiontype write then, to check existing permissions and request any that are missing, use the healthpermissionmanager class val permissionmanager = healthpermissionmanager healthdatastore runcatching { val grantedpermissions = permissionmanager ispermissionacquired permissions if grantedpermissions values all { it } { log i app_tag, "all required permissions granted" } else { log i app_tag, "not all required permissions granted" permissionmanager requestpermissions permissions, context setresultlistener permissionlistener } } onfailure { error -> error message? let { log i app_tag, it } } samsung health data sdk in samsung health data sdk, requesting data access permissions is simpler for example, to request read and write permissions for exercise data val permissions = setof permission of datatypes exercise, accesstype read , permission of datatypes exercise, accesstype write then, to check if all necessary permissions have been granted val grantedpermissions = healthdatastore getgrantedpermissions permissions val areallpermissionsgranted = grantedpermissions containsall permissions if there are any missing permissions, prompt the user to grant them try { val result = healthdatastore requestpermissions permissions, context // … } // catch any error read exercise data samsung health sdk for android in samsung health sdk for android, to read exercise data, you need to create a read request by defining the data type and time range set the data type using healthconstants exercise health_data_type and specify the local time range using setlocaltimerange, which accepts the start and end time in longs val readrequest = healthdataresolver readrequest builder setdatatype healthconstants exercise health_data_type setlocaltimerange healthconstants exercise start_time, healthconstants exercise time_offset, starttime, endtime build next, initialize a healthdataresolver object using the previously obtained healthdatastore instance and handler and launch the prepared readrequest to process the results for example, you can retrieve the device id associated with each recorded exercise this is useful when you want to determine which device the data originates from to achieve this, you can create an iterator to access healthdata that represents an exercise record val healthdataresolver = healthdataresolver healthdatastore, handler try { healthdataresolver read readrequest await run { try { val iterator = iterator while iterator hasnext { val healthdata = iterator next val deviceid = healthdata getstring healthconstants exercise device_uuid // process obtained deviceid or other data } } finally { close } } } catch exception exception { exception message? let { log i tag, it } } samsung health data sdk in samsung health data sdk, you can achieve the same result with simpler and more concise code as before, you need to create a read request first, create a localtimefilter to access data for the current day val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime then, apply it to the prepared request val readrequest = datatypes exercise readdatarequestbuilder setlocaltimefilter localtimefilter build to launch the request, simply call the readdata method of the healthdatastore instance, passing readrequest as an argument the result includes a datalist, which you can iterate through to access exercise data val exercisedatalist = healthdatastore readdata readrequest datalist exercisedatalist foreach { healthdatapoint -> val deviceid = healthdatapoint datasource? deviceid // process obtained deviceid or other data } read aggregated data for data types that represent summarized values, such as total, minimum, maximum or last values, you can use aggregate requests to compute these results samsung health sdk for android in samsung health sdk for android, to read aggregated data for a specific period, you need to create aggregaterequest with a defined time range and aggregation function for example, to read the total calories burned from exercise since the start of the day, you can call addfunction with aggregatefunction sum setlocaltimerange with starttime as the start of the day and endtime as the current time setdatatype with healthconstants exercise health_data_type below is an implementation of aggregaterequest that reads the total exercise calories since the start of the day note that you also need to define the key id to retrieve the aggregated data later val exercisetotalcaloriesid = "exercise_total_calories" val aggregaterequest = healthdataresolver aggregaterequest builder addfunction healthdataresolver aggregaterequest aggregatefunction sum, healthconstants exercise calorie, exercisetotalcaloriesid setlocaltimerange healthconstants exercise start_time, healthconstants exercise time_offset, starttime, endtime setdatatype healthconstants exercise health_data_type build next, launch the request synchronously and iterate through the results to get the total calories var totalcalories = 0 try { healthdataresolver aggregate aggregaterequest await run { try { val iterator = iterator if iterator hasnext { val healthdata = iterator next totalcalories = healthdata getint exercisetotalcaloriesid } } finally { close } } } catch exception exception { exception message? let { log i tag, it } } to get the total exercise duration, the logic remains the same the only difference is the property argument of the request’s addfunction , as well as the key to retrieve the aggregated data addfunction healthdataresolver aggregaterequest aggregatefunction sum, healthconstants exercise duration, "exercise_total_duration" samsung health data sdk in samsung health data sdk, it is simpler to get the aggregated data first, you need to create localtimefilter to define the time range val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime then, build an aggregaterequest instance by calling requestbuilder on the desired aggregate data type for exercise data, this could be either datatype exercisetype total_calories or datatype exercisetype total_duration the full request is shown below val aggregaterequest = datatype exercisetype total_calories requestbuilder setlocaltimefilter localtimefilter build to obtain the aggregated data, create an aggregate request and access the datalist since this type of request returns a single-element list containing the aggregated value, you can use kotlin’s mapnotnull function to extract it safely, ensuring it’s not null healthdatastore aggregatedata aggregaterequest datalist mapnotnull { it value } insert data let's explore how to insert prepared exercise data into samsung health samsung health sdk for android to insert data in samsung health sdk for android, you first need to create a healthdata instance that contains the exercise data to be inserted the health data includes the start time, end time, exercise type or duration, and live data time-series data across different exercise stages the livedata placeholder contains the user’s heart rate or speed across each exercise phase let's prepare a set of dummy data to insert in real-world scenarios, healthdata includes real-time measurements captured from wearable devices or other health and fitness equipment prepare data to be inserted first, create livedata - a list of objects of your custom data class exerciselivedata according to the documentation for samsung health sdk for android, it is recommended to provide start_time and at least one additional field for each instance of livedata for more details, please refer to livedata declare the start_time, heart_rate and speed data val livedatalist = listof exerciselivedata start_time = instant ofepochsecond 1766394000 toepochmilli , heart_rate = 144f, speed = 1 6f , exerciselivedata start_time = instant ofepochsecond 1766394030 toepochmilli , heart_rate = 146f, speed = 1 8f , // add more entries convert livedata list next, convert the livedata list to jsonblob bytearray format by using the sdk function getjsonblob this function takes a list of exerciselivedata as an argument and returns bytearray you can simply create a helper function for this task private fun createlivedata livedatalist list<exerciselivedata> bytearray { val zip = healthdatautil getjsonblob livedatalist return zip } create healthdata object create a healthdata object that holds all exercise data, including timestamps, calories, distance, duration and livedata the livedata is attached using the putblob function in addition to the standard fields start_time, end_time, and time_offset, it is necessary to specify the exercise type based on the predefined exercise type table, setting the value to 1002 represents a running exercise val calories = 73f val distance = 1000f val exercisetype = 1002 val starttime = instant ofepochsecond 1766394000 val endtime = instant ofepochsecond 1766394300 val duration = duration between starttime, endtime val timeoffset = timezone getdefault getoffset endtime toepochmilli tolong val healthdata = healthdata apply { sourcedevice = deviceid putlong healthconstants exercise start_time, starttime toepochmilli putlong healthconstants exercise end_time, endtime toepochmilli putlong healthconstants exercise time_offset, timeoffset putint healthconstants exercise exercise_type, exercisetype putlong healthconstants exercise duration, duration tomillis putfloat healthconstants exercise calorie, calories putfloat healthconstants exercise distance, distance putblob healthconstants exercise live_data, createlivedata livedatalist } insert the prepared data use a healthdataresolver class to build an insertrequest initialize a healthdataresolver instance and pass in the already connected healthdatastore utilize a builder function and set healthconstants exercise health_data_type as the data type retrieve the local device id using the healthdevicemanager instance, as you need to specify the source device that provides this data call the insert function with the prepared insertrequest and wait for the result below is an implementation example val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler try { val localdevice = healthdevicemanager healthdatastore localdevice uuid val data = exerciseinsertdata getexercisedata endtime, localdevice if data != null { val insertrequest = healthdataresolver insertrequest builder setdatatype healthconstants exercise health_data_type build insertrequest addhealthdata data val result = healthdataresolver insert insertrequest await if result status == healthresultholder baseresult status_successful { log i tag, "inserted running exercise count of data ${result count}" } else { log i tag, "inserting failed" } } } catch e exception { throw e } samsung health data sdk in samsung health data sdk, preparing livedata to be inserted into samsung health app is simplified by the help of the exerciselog class with predefined fields such as timestamp, heartrate, cadence and more, this class is ready to capture information for each phase of an exercise session this eliminates the need to manually encode it to jsonblob bytearray format instead, you can simply create a list of exerciselog objects, each representing a phase of the exercise val exerciselog = listof exerciselog of timestamp = instant ofepochsecond 1766394000 , heartrate = 144f, speed = 1 6f, cadence = null, count = null, power = null , exerciselog of timestamp = instant ofepochsecond 1766394030 , heartrate = 146f, speed = 1 8f, cadence = null, count = null, power = null // add more entries create a healthdatapoint instance another key difference in samsung health data sdk is that, instead of creating a healthdata instance, the sdk provides a healthdatapoint object that represents the entire exercise before creating a healthdatapoint instance, you need the following list of exerciselog objects predefined exercise type use addfielddata function to set the exercise type property with a predefined enum value and include list of datatype exercisetype sessions exercisesession object in the running exercise, there will always be a single-element list - an exercisesession element created based on a previously defined list of exerciselog objects to create an exercisesession object, use exercisesession builder and set the relevant data, such as start time, end time, exercise type, calories and duration once the relevant information is prepared, you can call the builder method to initialize a healthdatapoint instance and set the properties, such as start time, end time, and exercise type, by calling the addfielddata function the code is shown below val calories = 73f val distance = 1000f val starttime = instant ofepochsecond 1766394000 val endtime = instant ofepochsecond 1766394300 val duration = duration between starttime, endtime var healthdatapoint healthdatapoint? try { val session = exercisesession builder setstarttime starttime setendtime endtime setexercisetype datatype exercisetype predefinedexercisetype running setduration duration setcalories calories setdistance distance setcomment "routine running" setlog exerciselog build healthdatapoint = healthdatapoint builder setstarttime starttime setendtime endtime addfielddata datatype exercisetype exercise_type, datatype exercisetype predefinedexercisetype running addfielddata datatype exercisetype sessions, listof session build } catch e exception { throw e } insert the prepared data to insert the prepared data, simply build insertrequest by calling the insertdatarequestbuilder method on datatypes exercise attach the created data healthdatapoint instance by calling the adddata function finalize the request with the build method next, call the insertdata method of the healthdatastore instance and pass the created insertrequest as an argument val insertrequest = datatypes exercise insertdatarequestbuilder adddata data build healthdatastore insertdata insertrequest exception handling robust health apps can recover when things go wrong let's examine the differences between both sdks when handling such scenarios samsung health sdk for android in the case of samsung health sdk for android, the methods for handling errors depend on the exception types for example, connection exceptions with samsung health are handled by the healthdatastore connectionlistener's event handler you can use the healthconnectionerror class to check whether the error has a resolution based on the error type, you can implement different handling strategies for exceptions related to requests such as reading or writing data, refer to the healthresultholder baseresult class and its getstatus method however, since there are no dedicated exception class, developers must handle the exceptions that are part of the standard java language, such as illegalargumentexception, securityexception or illegalstateexception samsung health data sdk when working with samsung health data sdk, key functions such as aggregatedata , requestpermissions , or getgrantedpermissions may throw exceptions under certain conditions to prevent unexpected crashes or blank screens, it’s best to funnel these exceptions into a central error handler you can do so by wrapping every api invocation with try { // sdk function invocation } catch e healthdataexception { handlehealthdataexception e } about healthdataexception healthdataexception is the main exception class for samsung health data sdk the handlehealthdataexception function • shows an error log • tries to “resolve” the exception some healthdataexception instances include a resolution intent you can check if the exception has a resolution by checking the hasresolution property of the exception object and trying to fix it by invoking resolve examples of such exceptions • err_old_version_platform indicates samsung health app is outdated • err_platform_not_installed signals that samsung health app is not installed in both cases, the resolution involves opening the device’s app marketplace to prompt the user to install or update samsung health app once the issue is fixed, control returns to the app so it can continue functioning this approach not only keeps your ui clean, but allows for a consistent, guided error experience when something goes wrong, users can see a clear message of what happened and how to fix it summary we have covered how to migrate an app that uses samsung health sdk for android to samsung health data sdk when migrating your app to samsung health data sdk, you can follow the described process and code examples to complete the migration for more details, please refer to samsung health data sdk introduction partner request before distributing your app the developer mode of samsung health data sdk is a feature provided solely for development purposes to ensure that an app using samsung health data sdk functions properly without enabling developer mode, you need to submit a partner request through the developer site before distributing your app on app marketplaces after the partner app is approved, the app's detailed information will be registered in samsung's system having a trouble? we are operating a developer support channel on the samsung developer site if you encounter any issue or any question, please visit developer support and submit your query after logging in your samsung account
FAQ health
docfaq common | what are the benefits of samsung health sdk for android? samsung health app is a most popular health app and has more than 50 million of monthly active users it works not only on samsung smartphones but also non-samsung phones if the device supports android marshmallow or above it consists a big ecosystem including various health apps and connected accessory devices samsung health sdk for android enables your app to manage the user’s health data with the unified interface by connecting to samsung health app you can have more enhanced chances with a partnership of samsung health common | i know the sdk needs samsung health installation can samsung health be installed to all phones? if not, how can i know the samsung health’s availability on the device? even though samsung health is installed in android smartphones with marshmallow or above including samsung and non-samsung smartphones, some phones cannot support samsung health its check code needs to be added to prevent a relevant situation the sdk’s health data provides a solution to check it through healthconnectionerrorresult hasresolution if the app meets the following cases, it means that the device is not available for samsung health healthdatastore connectservice gives a failure event healthconnectionerrorresult hasresolution returns false see an example for failure exception handling health data | i would like to know data’s common properties all data type interfaces extend the healthconstants common interface basically some data types extend healthconstants discretemeasurement and others extend healthconstants sessionmeasurement depending on whether the end measured time exists for example, healthconstants sleep extends healthconstants common healthconstants sessionmeasurement you can set healthconstants sleep's following properties including its own ones healthconstants common device_uuid healthconstants sessionmeasurement start_time healthconstants sessionmeasurement end_time see the "properties" description of each data type interface in api reference for more information sleep data can be set as the example shown below public class healthdataexample { // the state of connection private healthdatastore mstore; private void insertsleepdata long start, long end, long offset { healthdevice mydevice = new healthdevicemanager mstore getlocaldevice ; healthdata data = new healthdata ; data setsourcedevice mydevice getuuid ; // fills all mandatory properties out data putlong healthconstants sleep start_time, start ; data putfloat healthconstants sleep end_time, end ; data putlong healthconstants sleep time_offset, offset ; healthdataresolver resolver = new healthdataresolver mstore, null ; healthdataresolver insertrequest insrequest = new healthdataresolver insertrequest builder setdatatype healthconstants sleep health_data_type build ; // do something } } health data | there are two data types for steps which data type is better? handling all use cases for the phone and linked multi-accessory devices is not easy with it because the phone and accessory device like galaxy watch can provide step count data at the same time or not depending on how many devices are carried by the user samsung health sdk provides the following data types for steps healthconstants stepdailytrend healthconstants stepcount healthconstants stepdailytrend is used to generally to read the user’s daily steps especially, its source_type_all provides the day’s total steps simply excluding duplicated steps when the user carries one more devices at the same time healthconstants stepcount is useful for getting each source device’s step count getting real-time step count of the phone that samsung health is installed health data | the inserted health data’s measured time looks different how can i solve it? if new data is inserted to the health data store, created_time, updated_time of healthconstants common are assigned by the system automatically so you don’t need to set them separately data’s start_time or end_time indicates its utc measurement time in milliseconds be careful not to set start_time or end_time as the device’s current local time time_offset is indicated by the time zone and daylight saving time in milliseconds and it helps in showing the health data’s measured time properly in the device the following example shows getting the current device’s time_offset import java util timezone; public class heathdataexample { long gettimeoffset long intaketime { return timezone getdefault getoffset intaketime ; } }
Develop Health
apioverviewpackageclasstreedeprecatedindex com samsung android sdk healthdata class healthdataobserver java lang object com samsung android sdk healthdata healthdataobserver public abstract class healthdataobserver extends object this class defines a health data observer for health data change adding an observer you can add an observer for the specific health data type and get notification in onchange string if the designated health data is changed in case that you add an observer for the data type that updates too frequently in short time like step count, it can send too many events to your application and it can bring degradation of your application's performance check that your application needs to update data with real-time from samsung health again before adding an observer a health data observer can be defined as below public class healthdataobserverexample { // the state of connection private healthdatastore mstore; public static final string app_tag = "myapp"; private final healthdataobserver mobserver = new healthdataobserver null { // checks notification for changed health data @override public void onchange string datatypename { log d app_tag, "health data is changed " ; readchangeddata datatypename ; } }; when you add an observer for the specific health data type, specify the data type name as below only data type is allowed to be observed public void start { // adds an observer for change of the weight healthdataobserver addobserver mstore, healthconstants weight health_data_type, mobserver ; } the change notification is received in onchange string and you can check updated health data as below private void readchangeddata string datatypename { healthdataresolver resolver = new healthdataresolver mstore, null ; healthdataresolver readrequest rdrequest = new healthdataresolver readrequest builder setdatatype datatypename build ; try { // make an asynchronous request to read health data resolver read rdrequest setresultlistener mrdlistener ; } catch exception e { log d app_tag, "healthdataresolver read fails " ; } } private final healthresultholder resultlistener<healthdataresolver readresult> mrdlistener = new healthresultholder resultlistener<healthdataresolver readresult> { @override public void onresult healthdataresolver readresult result { try { iterator<healthdata> iterator = result iterator ; if iterator hasnext { healthdata data = iterator next ; // check the result } } finally { result close ; } } }; } since 1 0 0 constructor summary constructors constructor and description healthdataobserver handler handler creates a healthdataobserver instance method summary all methods static methods instance methods abstract methods concrete methods modifier and type method and description static void addobserver healthdatastore store, string datatypename, healthdataobserver observer adds an observer that wants to follow data change for the given health data type abstract void onchange string datatypename called if health data registered as an observer is changed static void removeobserver healthdatastore store, healthdataobserver observer removes a registered observer constructor detail healthdataobserver public healthdataobserver handler handler creates a healthdataobserver instance parameters handler - the handler to run onchange string if it's null, onchange string event is run on binder thread which is invoked by samsung health since 1 0 0 method detail onchange public abstract void onchange string datatypename called if health data registered as an observer is changed parameters datatypename - the data type name that health data is changed since 1 0 0 addobserver public static void addobserver healthdatastore store, string datatypename, healthdataobserver observer adds an observer that wants to follow data change for the given health data type parameters store - the health data store for connection datatypename - the health data type name to follow change observer - an observer to receive notification if health data is changed throws illegalargumentexception - if the data type or observer is invalid illegalstateexception - if the instance of health data store is invalid or a remote-invocation error occurs in the connection since 1 0 0 removeobserver public static void removeobserver healthdatastore store, healthdataobserver observer removes a registered observer parameters store - health data store for connection observer - the added observer throws illegalargumentexception - if the observer is invalid illegalstateexception - if the instance of health data store is invalid or a remote-invocation error occurs in the connection since 1 0 0
Develop Health
docmigration guide from samsung health sdk for android to samsung health data sdk following the release of samsung health data sdk, samsung health sdk for android has been deprecated after this transition, partner apps that currently use samsung health sdk for android need to transition to samsung health data sdk benefits of migrating to samsung health data sdk samsung health data sdk enables apps to access health data in the samsung health app on android smartphones not only does it offer the functionality as samsung health sdk for android, but it also provides various additional advantages compared to samsung health sdk for android, samsung health data sdk applies the service logic displayed in the samsung health app's trackers and provides more specialized data from the app this allows health service providers to gain a better understanding of users' health indicators for example, to retrieve the same step count data displayed in the samsung health app when using samsung health sdk for android, you need to set the data type as stepdailytrend set filters for both the time period source_type_all this ensures that you receive the same step count data that`s displayed in the samsung health app samsung health sdk for android code val healthdataresolver = healthdataresolver healthdatastore, null val date = localdate now atstartofday toinstant zoneoffset utc toepochmilli val filter = filter and filter eq stepdailytrend day_time, date , filter eq stepdailytrend source_type, stepdailytrend source_type_all val stepsrequest = healthdataresolver readrequest builder setdatatype stepdailytrend health_data_type setfilter filter build with samsung health data sdk, you can simplify a data request by utilizing the total aggregator and only applying a time filter this data request allows you to retrieve the daily total step count displayed in the samsung health app without considering the potential oversight of setting the source type to `all' samsung health data sdk code val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime val stepsrequest = datatype stepstype total requestbuilder setlocaltimefilter localtimefilter build samsung health data sdk provides various goal data types, such as step goal, sleep goals, and active calories burned goal goal data types help to provide appropriate guidance to users samsung health data sdk can read, write, update, and delete health data in the samsung health app it can also retrieve associated data related to specific data for example, the samsung health app continuously measures blood oxygen and skin temperature during sleep samsung health data sdk allows you to easily retrieve blood oxygen and skin temperature data related to this specific sleep data samsung health sdk for android will remain operational for at least 2 years after its deprecation after a certain period, this sdk will be removed, so we recommend updating your app to use samsung health data sdk instead developer mode previously, samsung health sdk for android required developers to submit a partner request to gain access, which needed to be applied for and approved before use now, with samsung health data sdk, you can download and use the sdk in developer mode without submitting a partner request to enhance convenience for developers, samsung health data sdk has improved its developer mode functionality if you only need to read data from samsung health app, you can activate developer mode and proceed with development and testing without requiring a partner request for more information on developer mode, please refer to developer mode if you want to test writing data to samsung health app using samsung health data sdk or distribute your app, you need to obtain a partnership for samsung health data sdk you can request it by following this process checking supported data types of samsung health data sdk before you start using samsung health data sdk, please, compare it with samsung health sdk for android and its existing data types to determine whether the data types you want to use in your app are supported and what additional data can be utilized category data type of samsung health sdk for android sdk corresponding data type in samsung health data sdk activity healthconstants exercise exercisetype healthconstants floorsclimbed floorsclimbedtype healthconstants stepdailytrend read-only stepstype read-only healthconstants stepcount read-only not provided not provided stepgoaltype read-only not provided activitysummarytype read-only not provided activecaloriesburnedgoaltype read-only not provided activetimegoaltype read-only food intake healthconstants nutrition nutritiontype not provided nutritiongoaltype read-only healthconstants waterintake waterintaketype not provided waterintakegoaltype read-only rest healthconstants sleep sleeptype healthconstants sleepstage not provided not provided sleepgoaltype read-only healthcare healthconstants bloodglucose bloodglucosetype healthconstants bloodpressure bloodpressuretype healthconstants bodytemperature bodytemperature healthconstants heartrate heartratetype healthconstants oxygensaturationtype bloodoxygentype healthconstants weight bodycompositiontype not provided skintemperature score not provided energyscoretype read-only user profile healthuserprofile read-only userprofiledatatype read-only checking the user experience to access health data from samsung health data sdk, you need to receive data permissions and obtain user consent in order to do that, please, follow the same process as samsung health sdk for android you can request data permissions at requesting data permissions notewhen using both sdks together, the data permissions of each sdk are displayed to the user, which can result in an inconvenient ui for the user hence, we recommend to use samsung health data sdk data permission of samsung health sdk for android data permission of samsung health data sdk getting started 1 download samsung health data sdk visit samsung health data sdk page to download samsung health data sdk 2 enabling samsung health data sdk’s developer mode if you only need to read data from samsung health app, you can enable the developer mode feature without submitting an additional partner request refer to the developer mode documentation for instructions on how to enable it if you want to write data to samsung health app, you need to submit a partner request 3 importing samsung health data sdk's library remove the library of samsung health sdk for android from your app project samsung-health-data-a b c aar and add samsung health data sdk's library to the app/libs folder samsung-health-data-api-a b c aar note that 'a b c' is the sdk's version 4 update app manifest if your app's manifest has the element for the samsung health app, please remove it remove the element remove the element for samsung health sdk for android from your app manifest <manifest > <queries> <package android name="com sec android app shealth" /> </queries> </manifest> if the app manifest has the element lines related to health data permissions of samsung health sdk for android, please remove it remove the data permission declarations remove the data permission declarations for samsung health sdk for android from your app manifest <manifest > <application > <meta-data android name="com samsung android health permission read" android value="com samsung health exercise;com samsung shealth step_daily_trend"/> <meta-data android name="com samsung android health permission write" </application> </manifest> include migration completion information please add the following information to your app manifest <manifest > <application > <meta-data android name="com samsung android sdk health data migration_completed" android value="true"/> </application> </manifest> 5 gradle settings in the app/builde gradle, remove the dependency for samsung health sdk for android app/build gradle - remove the dependency for samsung health sdk for android dependencies { implementation files 'src/main/libs/samsung-health-data-1 5 1 aar' } add the dependency for samsung health data sdk instead app/build gradle - add the dependency for samsung health data sdk dependencies { implementation filetree mapof "dir" to "libs", "include" to listof "* aar" } add the gson library in the dependency app/build gradle - add the dependency for samsung health data sdk dependencies { implementation "com google code gson gson 2 9 0" } and apply the kotlin-parcelize plugin to the app/build gradle app/build gradle - add the plugin for samsung health data sdk plugins { id "kotlin-parcelize" } 6 connecting with samsung health to access health data in the samsung health app, you need to connect the sdk with the samsung health app if the samsung health app is not installed or you have an earlier version of the samsung health app than the supported version, an exception occurs after the connection request if it is a resolvable exception, call the resolve api is to resolve the exception below is an example code snippet when using samsung health sdk for android connecting with samsung health with samsung health sdk for android lateinit var healthdatastore healthdatastore fun connect activity activity { healthdatastore = healthdatastore context, object healthdatastore connectionlistener { override fun onconnected { log i app_tag, "health data service is connected" } override fun onconnectionfailed error healthconnectionerrorresult { if error hasresolution { error resolve activity } else { log i app_tag, "health data service is not available" } } override fun ondisconnected { log i app_tag, "health data service is disconnected" } } runcatching { healthdatastore connectservice } onfailure { error -> error message? let { log i app_tag, it } } } to connect to the samsung health app using samsung health data sdk, you can do so as shown in the code below connecting with samsung health with samsung health data sdk lateinit var healthdatastore healthdatastore fun connect activity activity { runcatching { healthdatastore = healthdataservice getstore context } onsuccess { log i app_tag, "health data service is connected" } onfailure { error -> if error is resolvableplatformexception && error hasresolution { error resolve activity } // handle other types of healthdataexception error message? let { log i app_tag, it } } } 7 requesting data permissions after you have successfully connected to the samsung health app, you need to request data permissions for the health data you want to access from the user upon obtaining an explicit consent from the user, you will be able to access the health data before requesting data permission, check if the user has already granted the data permission if the required data permission has not been obtained, proceed to request the necessary data permission the following code is an example of requesting data permissions to read daily step count, nutrition, and user profile data when using samsung health sdk for android requesting data permission with samsung health sdk for android private val permissionlistener healthresultholder resultlistener<permissionresult> = healthresultholder resultlistener<permissionresult> { result -> if result resultmap values contains false { log i app_tag, "not all required permissions granted" } else { log i app_tag, "all required permissions granted" } } fun requestpermissions activity activity, healthdatastore healthdatastore { val permissionset = setof permissionkey stepdailytrend health_data_type, healthpermissionmanager permissiontype read , permissionkey nutrition health_data_type, healthpermissionmanager permissiontype read , permissionkey healthconstants user_profile_data_type, healthpermissionmanager permissiontype read val permissionmanager = healthpermissionmanager healthdatastore runcatching { val grantedpermissions = permissionmanager ispermissionacquired permissionset if grantedpermissions values all { it } { log i app_tag, "all required permissions granted" } else { log i app_tag, "not all required permissions granted" permissionmanager requestpermissions permissionset, activity setresultlistener permissionlistener } } onfailure { error -> error message? let { log i app_tag, it } } } when the above code is executed, the following screenshot shows the data permission popup displayed to the user when using samsung health data sdk, you can do the following requesting data permission with samsung health data sdk suspend fun requestpermissions healthdatastore healthdatastore, activity activity { val permissionset = setof permission of datatypes steps, accesstype read , permission of datatypes nutrition, accesstype read , permission of datatypes user_profile, accesstype read val grantedpermissions = healthdatastore getgrantedpermissions permissionset if grantedpermissions containsall permissionset { log i app_tag, "all required permissions granted" } else { healthdatastore requestpermissions permissionset, activity } } when requesting data permissions with samsung health data sdk, the following screenshot will be displayed to the user 8 data request asynchronous request asynchronous operations allow the application to continue processing other tasks without waiting for the current task to complete it prevents the main thread from being blocked it enhances user experience by keeping the application interactive during long-running tasks and supports efficient handling of concurrent operations below you can see a code example of when using samsung health sdk for android to make an asynchronous request asynchronous request when with samsung health sdk for android fun readstepsasync healthdatastore healthdatastore { val healthdataresolver = healthdataresolver healthdatastore, null val date = localdate now atstartofday toinstant zoneoffset utc toepochmilli val filter = filter and filter eq stepdailytrend day_time, date , filter eq stepdailytrend source_type, stepdailytrend source_type_all val stepsrequest = healthdataresolver readrequest builder setdatatype stepdailytrend health_data_type setfilter filter build try { healthdataresolver read stepsrequest setresultlistener { result -> try { val iterator = result iterator if iterator hasnext { val healthdata = iterator next val stepcount = healthdata getint stepdailytrend count log i mainactivity app_tag, "step count $stepcount" } } finally { result close } } } catch exception exception { exception message? let { log i mainactivity app_tag, it } } } when using samsung health data sdk, you can perform the same operation as follows use an api that includes async asynchronous request with samsung health data sdk fun readstepsasync healthdatastore healthdatastore, activity activity { val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime val stepsrequest = datatype stepstype total requestbuilder setlocaltimefilter localtimefilter build healthdatastore aggregatedataasync stepsrequest setcallback looper getmainlooper , { result -> val stepcount = result datalist first value log i mainactivity app_tag, "step count $stepcount" } { error -> if error is resolvableplatformexception && error hasresolution { error resolve activity } } } synchronous request synchronous operations execute tasks sequentially, requiring the application to wait for the current task to complete before proceeding to the next while this approach is simple to implement and ensures a predictable execution flow, it can block the main thread this makes synchronous operations more suitable for straightforward, short tasks rather than complex or concurrent processes to perform synchronous operations when using samsung health sdk for android, you can use the await api synchronous request with samsung health sdk for android fun readstepssync healthdatastore healthdatastore { val healthdataresolver = healthdataresolver healthdatastore, null val date = localdate now atstartofday toinstant zoneoffset utc toepochmilli val filter = filter and filter eq stepdailytrend day_time, date , filter eq stepdailytrend source_type, stepdailytrend source_type_all val stepsrequest = healthdataresolver readrequest builder setdatatype stepdailytrend health_data_type setfilter filter build try { healthdataresolver read stepsrequest await run { try { val iterator = iterator if iterator hasnext { val healthdata = iterator next val stepcount = healthdata getint stepdailytrend count log i mainactivity app_tag, "step count $stepcount" } } finally { close } } } catch exception exception { exception message? let { log i mainactivity app_tag, it } } } for synchronous operations involving samsung health data sdk, please, use the following approach synchronous request with samsung health data sdk suspend fun readstepssync healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val stepsrequest = datatype stepstype total requestbuilder setlocaltimefilterwithgroup localtimefilter companion of starttime, endtime , localtimegroup of localtimegroupunit hourly, 1 build try { val readresult = healthdatastore aggregatedata stepsrequest val stepcount = readresult datalist first value log i mainactivity app_tag, "step count $stepcount" } catch e exception { e printstacktrace } } 9 implementing and testing app accessing the health data is required by the app to test to ensure the functionality works properly for detailed information on accessing health data, refer to accessing health data 10 partner request before distributing your app the developer mode of samsung health data sdk is a feature provided solely for development purposes to ensure that an app using samsung health data sdk functions properly without enabling developer mode, you need to submit a partner request through the developer site before distributing your app on app marketplaces after the partner app is approved, the app's detailed information will be registered in samsung's system accessing health data steps samsung health measures step data from smartphones with samsung health installed and from connected galaxy wearable devices, such as the galaxy watch, galaxy fit, or galaxy ring it aggregates and eliminates duplicate data to provide daily step counts step count data is read-only the corresponding steps data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants stepdailytrend read-only healthconstants stepcount read-only stepstype read-only here is an example of code that reads today's total step count when using samsung health sdk for android reading today's total steps with samsung health sdk for android fun readtodaystepcountdata healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val filter = filter and filter eq stepdailytrend day_time, starttime , filter eq stepdailytrend source_type, stepdailytrend source_type_all val healthdataresolver = healthdataresolver healthdatastore, null val request = healthdataresolver readrequest builder setdatatype stepdailytrend health_data_type setfilter filter build try { healthdataresolver read request setresultlistener { result -> try { val iterator = result iterator if iterator hasnext { val healthdata = iterator next val totalcount = healthdata getint stepdailytrend count log i mainactivity app_tag, "today steps count $totalcount" } else { log i mainactivity app_tag, "no step data available" the code to retrieve today's total step count when using samsung health data sdk is as follows reading today's total steps with samsung health data sdk suspend fun readtodaystepcountdata healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val readrequest = datatype stepstype total requestbuilder setlocaltimefilter localtimefilter of starttime, endtime build try { val readresult = healthdatastore aggregatedata readrequest val data = readresult datalist first val totalcount = data value log i mainactivity app_tag, "today steps count $totalcount" } catch e exception { e printstacktrace } } exercise the samsung health app records the user's exercise data when the user wears a galaxy watch, galaxy fit, or galaxy ring and records exercise data, the app records their heart rate, exercise speed, and distance the corresponding exercise data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants exercise exercisetype example code for reading today's exercise data when using samsung health sdk for android is as follows reading exercise data with samsung health sdk for android fun readtodayexercise healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdate now plusdays 1 atstartofday toinstant zoneoffset utc toepochmilli val healthdataresolver = healthdataresolver healthdatastore, null val readrequest = healthdataresolver readrequest builder setdatatype exercise health_data_type setlocaltimerange floorsclimbed start_time, floorsclimbed time_offset, starttime, endtime build try { healthdataresolver read readrequest setresultlistener { result -> try { val iterator = result iterator iterator foreach { healthdata -> val exercisetype = healthdata getint exercise exercise_type val duration = healthdata getlong exercise duration val calories = healthdata getfloat exercise calorie log i mainactivity app_tag, "exercise type $exercisetype, duration $duration, calories $calories" } } finally { result close } } } catch exception exception { exception message? let { log i mainactivity app_tag, it } } } example code for reading today's exercise data when using samsung health data sdk is as follows reading exercise data with samsung health data sdk suspend fun readtodayexercise healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val readrequest = datatypes exercise readdatarequestbuilder setlocaltimefilter localtimefilter of starttime, endtime build try { val readresult = healthdatastore readdata readrequest val datapoints = readresult datalist if datapoints isempty { log i mainactivity app_tag, "no exercises today" return } datapoints foreach { datapoint -> val exercisetype = datapoint getvalue datatype exercisetype exercise_type val sessions = datapoint getvalue datatype exercisetype sessions sessions? foreach { session -> val exercisesessiontype = session exercisetype val exercisesessionduration = session duration val exercisesessioncalories = session calories log i mainactivity app_tag, "exercise type $exercisetype, session type $exercisesessiontype, duration $exercisesessionduration, calories $exercisesessioncalories" } } } catch e exception { e printstacktrace } } example code for writing exercise data when using samsung health sdk for android is as follows writing running exercise data with samsung health sdk for android fun insertrunningexercise healthdatastore healthdatastore { val fiveminutesasseconds = 300l val exercisetype = 1002 val calories = 73f val distance = 1000f val deviceid = healthdevicemanager healthdatastore localdevice uuid val starttime = instant now minusseconds fiveminutesasseconds val endtime = instant now val timeoffset = timezone getdefault getoffset endtime toepochmilli tolong val duration = duration between starttime, endtime val healthdataresolver = healthdataresolver healthdatastore, null val livedata = createlivedata listof exerciselivedata start_time = starttime toepochmilli , heart_rate = 144f, speed = 1 6f , exerciselivedata start_time = starttime plusseconds 30 toepochmilli , heart_rate = 146f, speed = 1 8f , exerciselivedata start_time = starttime plusseconds 60 toepochmilli , heart_rate = 146f, speed = 1 9f , exerciselivedata start_time = starttime plusseconds 90 toepochmilli , heart_rate = 152f, speed = 2f , exerciselivedata start_time = starttime plusseconds 120 toepochmilli , heart_rate = 154f, speed = 2 1f , exerciselivedata start_time = starttime plusseconds 150 toepochmilli , heart_rate = 161f, speed = 2 2f , exerciselivedata start_time = starttime plusseconds 180 toepochmilli , heart_rate = 159f, speed = 2 1f , exerciselivedata start_time = starttime plusseconds 210 toepochmilli , heart_rate = 160f, speed = 2 2f , exerciselivedata start_time = starttime plusseconds 240 toepochmilli , heart_rate = 159f, speed = 2 1f , exerciselivedata start_time = starttime plusseconds 270 toepochmilli , heart_rate = 161f, speed = 2 2f , exerciselivedata start_time = starttime plusseconds 300 toepochmilli , heart_rate = 160f, speed = 2f val healthdata = healthdata apply { sourcedevice = deviceid putlong exercise start_time, starttime toepochmilli putlong exercise end_time, endtime toepochmilli putlong exercise time_offset, timeoffset putint exercise exercise_type, exercisetype putlong exercise duration, duration tomillis putfloat exercise calorie, calories putfloat exercise distance, distance putblob exercise live_data, livedata } val insertrequest = healthdataresolver insertrequest builder setdatatype exercise health_data_type build insertrequest addhealthdata healthdata try { val result = healthdataresolver insert insertrequest await if result status == status_successful { log i mainactivity app_tag, "inserted running exercise count of data ${result count}" } else { log i mainactivity app_tag, "inserting failed" } } catch e exception { e printstacktrace } } private fun createlivedata livedatalist list<exerciselivedata> bytearray { val zip = healthdatautil getjsonblob livedatalist return zip } data class exerciselivedata val start_time long, val heart_rate float, val speed float example code for writing exercise data when using samsung health data sdk is as follows one exercise session of exercise data is writable writing running exercise data with samsung health data sdk suspend fun insertrunningexercise healthdatastore healthdatastore { val fiveminutesasseconds = 300l val calories = 73f val distance = 1000f val starttime = instant now minusseconds fiveminutesasseconds val endtime = instant now val duration = duration between starttime, endtime val exerciselog = listof exerciselog of timestamp = starttime, heartrate = 144f, speed = 1 6f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 30 , heartrate = 146f, speed = 1 8f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 60 , heartrate = 146f, speed = 1 9f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 90 , heartrate = 152f, speed = 2f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 120 , heartrate = 154f, speed = 2 1f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 150 , heartrate = 161f, speed = 2 2f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 180 , heartrate = 159f, speed = 2 1f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 210 , heartrate = 160f, speed = 2 2f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 240 , heartrate = 159f, speed = 2 1f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 270 , heartrate = 161f, speed = 2 2f, cadence = null, count = null, power = null , exerciselog of timestamp = starttime plusseconds 300 , heartrate = 160f, speed = 2f, cadence = null, count = null, power = null try { val session = exercisesession builder setstarttime starttime setendtime endtime setexercisetype datatype exercisetype predefinedexercisetype running setduration duration setcalories calories setdistance distance setlog exerciselog build val healthdatapoint = healthdatapoint builder setstarttime starttime setendtime endtime addfielddata datatype exercisetype exercise_type, datatype exercisetype predefinedexercisetype running addfielddata datatype exercisetype sessions, listof session build val insertrequest = datatypes exercise insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest log i mainactivity app_tag, "inserted running exercise" } catch e exception { e printstacktrace } } floors climbed floors climbed data is one of the activity health data types it is displayed in the activity tracker in the samsung health app the corresponding floors climbed data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants floorsclimbed floorsclimbedtype to read today's floors climbed data when using samsung health sdk for android, the following example code can be used reading floors climbed data with samsung health sdk for android fun readtodayfloorsclimbed healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdate now plusdays 1 atstartofday toinstant zoneoffset utc toepochmilli val healthdataresolver = healthdataresolver healthdatastore, null val readrequest = healthdataresolver readrequest builder setdatatype floorsclimbed health_data_type setlocaltimerange floorsclimbed start_time, floorsclimbed time_offset, starttime, endtime build try { healthdataresolver read readrequest setresultlistener { result -> try { val iterator = result iterator if iterator hasnext { val healthdata = iterator next val totalcount = healthdata getfloat floorsclimbed floor log i mainactivity app_tag, "today floors climbed $totalcount" } else { log i mainactivity app_tag, "today floors climbed 0" } } finally { result close } } } catch exception exception { exception message? let { log i mainactivity app_tag, it } } } when using samsung health data sdk to read today's floors climbed data is as follows reading floors climbed data with samsung health data sdk suspend fun readtodayfloorsclimbed healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val readrequest = datatype floorsclimbedtype total requestbuilder setlocaltimefilter localtimefilter of starttime, endtime build try { val readresult = healthdatastore aggregatedata readrequest val data = readresult datalist val totalcount = if data isnotempty data first value else 0 log i mainactivity app_tag, "today floors climbed $totalcount" } catch e exception { e printstacktrace } } to write floors climbed data when using samsung health sdk for android, the following example code can be used writing floors climbed data with samsung health sdk for android fun inserttodayfloorsclimbed healthdatastore healthdatastore { val oneminuteasseconds = 60l val floor = 2f val deviceid = healthdevicemanager healthdatastore localdevice uuid val starttime = instant now minusseconds oneminuteasseconds toepochmilli val endtime = instant now toepochmilli val timeoffset = timezone getdefault getoffset endtime tolong val healthdataresolver = healthdataresolver healthdatastore, null val healthdata = healthdata apply { sourcedevice = deviceid putlong floorsclimbed start_time, starttime putlong floorsclimbed end_time, endtime putlong floorsclimbed time_offset, timeoffset putfloat floorsclimbed floor, floor } val insertrequest = healthdataresolver insertrequest builder setdatatype floorsclimbed health_data_type build insertrequest addhealthdata healthdata try { val result = healthdataresolver insert insertrequest await if result status == status_successful { log i mainactivity app_tag, "inserted floor climbed count of data ${result count}" } else { log i mainactivity app_tag, "inserting failed" } } catch e exception { e printstacktrace } } when using samsung health data sdk to write today's floors climbed data is as follows writing floors climbed data with samsung health data sdk suspend fun inserttodayfloorclimbed healthdatastore healthdatastore { val oneminuteasseconds = 60l val floor = 2f val starttime = instant now minusseconds oneminuteasseconds val endtime = instant now try { val healthdatapoint = healthdatapoint builder setstarttime starttime setendtime endtime addfielddata datatype floorsclimbedtype floor, floor build val insertrequest = datatypes floors_climbed insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest log i mainactivity app_tag, "inserted floor climbed" } catch e exception { e printstacktrace } } nutrition the samsung health app provides a food tracker that allows users to record and manage their eating data for each meal type, such as breakfast, lunch, and dinner the corresponding nutrition data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants nutrition nutritiontype here is an example code to read today's nutrition data when using samsung health sdk for android reading nutrition data with samsung health sdk for android fun readtodaynutrition healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdate now plusdays 1 atstartofday toinstant zoneoffset utc toepochmilli val healthdataresolver = healthdataresolver healthdatastore, null val nutritionrequest = healthdataresolver readrequest builder setdatatype nutrition health_data_type setlocaltimerange nutrition start_time, nutrition time_offset, starttime, endtime build try { healthdataresolver read nutritionrequest setresultlistener { result -> try { val iterator = result iterator iterator foreach { healthdata -> val title = healthdata getstring nutrition title val mealtype = healthdata getint nutrition meal_type val calories = healthdata getfloat nutrition calorie log i mainactivity app_tag, "today nutrition $title, $mealtype, $calories" } } finally { result close } } } catch exception exception { exception message? let { log i mainactivity app_tag, it } } } when using samsung health data sdk to read today's nutrition data is as follows reading nutrition data with samsung health data sdk suspend fun readtodaynutrition healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val readrequest = datatypes nutrition readdatarequestbuilder setlocaltimefilter localtimefilter of starttime, endtime build try { val readresult = healthdatastore readdata readrequest if readresult datalist isempty { log i mainactivity app_tag, "no nutrition today" return } readresult datalist foreach { healthdata -> val title = healthdata getvalue datatype nutritiontype title val mealtype = healthdata getvalue datatype nutritiontype meal_type val calories = healthdata getvalue datatype nutritiontype calories log i mainactivity app_tag, "today nutrition $title, $mealtype, $calories" } } catch e exception { e printstacktrace } } here is an example code to write nutrition data when using samsung health sdk for android writing nutrition data with samsung health sdk for android fun insertnutrition healthdatastore healthdatastore { val mydevice = healthdevicemanager healthdatastore val mealtitle = "toast and coffee" val calories = 66f val totalfat = 0 8f val saturatedfat = 0 1f val protein = 2 1f val carbohydrate = 11 9f val totalsugars = 1f val dietaryfiber = 0 6f val sodium = 135f val calcium = 40 3f val iron = 0 78f val potassium = 140f val referenceindexforironinmilligrams = 8 1f val referenceindexforcalciuminmilligrams = 1000f val starttime = instant now toepochmilli val timeoffset = timezone getdefault getoffset starttime tolong val data = healthdata apply { sourcedevice = mydevice localdevice uuid putlong healthconstants nutrition start_time, starttime ; putlong healthconstants nutrition time_offset, timeoffset ; putint healthconstants nutrition meal_type, meal_type_breakfast putstring healthconstants nutrition title, mealtitle putfloat healthconstants nutrition calorie, calories putfloat healthconstants nutrition total_fat, totalfat putfloat healthconstants nutrition saturated_fat, saturatedfat putfloat healthconstants nutrition protein, protein putfloat healthconstants nutrition carbohydrate, carbohydrate putfloat healthconstants nutrition sugar, totalsugars putfloat healthconstants nutrition dietary_fiber, dietaryfiber putfloat healthconstants nutrition sodium, sodium putfloat healthconstants nutrition potassium, potassium val calciumaspercentofreferenceintake = calcium / referenceindexforcalciuminmilligrams * 100 val ironinpercentofreferenceintake= iron / referenceindexforironinmilligrams * 100 putfloat healthconstants nutrition calcium, calciumaspercentofreferenceintake putfloat healthconstants nutrition iron, ironinpercentofreferenceintake } val insertrequest = healthdataresolver insertrequest builder setdatatype healthconstants nutrition health_data_type build val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler try { insertrequest addhealthdata data val insertresult = healthdataresolver insert insertrequest await log i tag, "insertnutrition status ${insertresult status}" } catch e exception { e printstacktrace } } when using samsung health data sdk to write nutrition data is as follows writing nutrition data with samsung health data sdk suspend fun insertnutrition healthdatastore healthdatastore { val starttime = localdatetime now val mealtitle = "toast and coffee" val calories = 66f val totalfat = 0 8f val saturatedfat = 0 1f val protein = 2 1f val carbohydrate = 11 9f val sugar = 1f val dietaryfiber = 0 6f val sodium = 135f val calcium = 40 3f val iron = 0 78f val potassium = 140f try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime addfielddata datatype nutritiontype meal_type, mealtype breakfast addfielddata datatype nutritiontype title, mealtitle addfielddata datatype nutritiontype calories, calories addfielddata datatype nutritiontype total_fat, totalfat addfielddata datatype nutritiontype saturated_fat, saturatedfat addfielddata datatype nutritiontype protein, protein addfielddata datatype nutritiontype carbohydrate, carbohydrate addfielddata datatype nutritiontype sugar, sugar addfielddata datatype nutritiontype dietary_fiber, dietaryfiber addfielddata datatype nutritiontype sodium, sodium addfielddata datatype nutritiontype calcium, calcium addfielddata datatype nutritiontype iron, iron addfielddata datatype nutritiontype potassium, potassium build val insertdatarequest = datatypes nutrition insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertdatarequest } catch e exception { e printstacktrace } } water intake the data types of samsung health sdk for android and samsung health data sdk are as follows samsung health sdk for android samsung health data sdk healthconstants waterintake waterintaketype example code for reading today's water intake data when using samsung health sdk for android is as follows reading water intake data with samsung health sdk for android fun readtodaytotalwaterintake healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdatetime now toinstant zoneoffset utc toepochmilli val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val waterintakeid = "water_intake_sum" val aggregaterequest = healthdataresolver aggregaterequest builder addfunction healthdataresolver aggregaterequest aggregatefunction sum, healthconstants waterintake amount, waterintakeid setlocaltimerange healthconstants waterintake start_time, healthconstants waterintake time_offset, starttime, endtime setdatatype healthconstants waterintake health_data_type build try { healthdataresolver aggregate aggregaterequest setresultlistener { result -> try { result? foreach { healthdata -> val waterintakesum = healthdata getfloat waterintakeid } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read today's water intake data is as follows reading water intake data with samsung health data sdk suspend fun readtodaytotalwaterintake healthdatastore com samsung android sdk health data healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime val readrequest = datatype waterintaketype total requestbuilder setlocaltimefilter localtimefilter build try { val result = healthdatastore aggregatedata readrequest result datalist lastornull ? let { datapoint -> val waterintake = datapoint value } } catch e exception { e printstacktrace } } example code for writing water intake data when using samsung health sdk for android is as follows writing water intake data with samsung health sdk for android fun insertwaterintake healthdatastore healthdatastore { val mydevice = healthdevicemanager healthdatastore val wateramountinmilliliters = 250f val unitamount = 250f val starttime = instant now toepochmilli val timeoffset = timezone getdefault getoffset starttime tolong val data = healthdata apply { sourcedevice = mydevice localdevice uuid putlong healthconstants waterintake start_time, starttime ; putlong healthconstants waterintake time_offset, timeoffset ; putfloat healthconstants waterintake amount, wateramountinmilliliters putfloat healthconstants waterintake unit_amount, unitamount } val insertrequest = healthdataresolver insertrequest builder setdatatype healthconstants waterintake health_data_type build val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler try { insertrequest addhealthdata data val insertresult = healthdataresolver insert insertrequest await log i tag, "insertwaterintake status ${insertresult status}" } catch e exception { e printstacktrace } } when using samsung health data sdk to write water intake data is as follows writing water intake data with samsung health data sdk suspend fun insertwaterintake healthdatastore healthdatastore { val starttime = localdatetime now val wateramountinmilliliters = 250f try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime addfielddata datatype waterintaketype amount, wateramountinmilliliters build val insertdatarequest = datatypes water_intake insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertdatarequest } catch e exception { e printstacktrace } } sleep and sleep stage the data types of samsung health sdk for android and samsung health data sdk are as follows samsung health sdk for android samsung health data sdk healthconstants sleep healthconstants sleepstage sleeptype code for reading the last night's sleep data when using samsung health sdk for android is as follows reading the last night's sleep data with samsung health sdk for android fun readlastsleep healthdatastore healthdatastore { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val resultcount = 1 val resultoffset = 0 val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants sleep health_data_type setsort healthconstants sleep start_time, sortorder desc setresultcount resultoffset, resultcount build try { healthdataresolver read request setresultlistener { result -> try { result lastornull ? let { healthdata -> val sleepid = healthdata getstring healthconstants sleep uuid val sleepstarttime = instant ofepochmilli healthdata getlong healthconstants sleep start_time val sleependtime = instant ofepochmilli healthdata getlong healthconstants sleep end_time readsleepstagesforsleepid healthdatastore, sleepid } } finally { result close } } } catch e exception { e printstacktrace } } fun readsleepstagesforsleepid healthdatastore healthdatastore, sleepid string { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants sleepstage health_data_type setfilter filter eq healthconstants sleepstage sleep_id, sleepid build try { healthdataresolver read request setresultlistener { result -> try { result? foreach { sleepstagedata -> val sleepstagename = sleepstagenamebyid sleepstagedata getint healthconstants sleepstage stage val sleepstagestarttime = instant ofepochmilli sleepstagedata getlong healthconstants sleepstage start_time val sleepstageendtime = instant ofepochmilli sleepstagedata getlong healthconstants sleepstage end_time } } finally { result close } } } catch e exception { e printstacktrace } } fun sleepstagenamebyid id int string { return when id { healthconstants sleepstage stage_awake -> "awake" healthconstants sleepstage stage_deep -> "deep" healthconstants sleepstage stage_light -> "light" healthconstants sleepstage stage_rem -> "rem" else -> "" } } when using samsung health data sdk to read the last night's sleep data is as follows reading the last night's sleep data with samsung health data sdk suspend fun readsleeptotalduration healthdatastore healthdatastore { val daysbackoffset = 400l val starttime = localdate now minusdays daysbackoffset val endtime = localdate now val localdatefilter = localdatefilter of starttime, endtime val request = datatype sleeptype total_duration requestbuilder setlocaldatefilter localdatefilter build try { val result = healthdatastore aggregatedata request result datalist foreach { aggregateddata -> val starttime = aggregateddata starttime val endtime = aggregateddata endtime val totalduration = aggregateddata value } } catch e exception { e printstacktrace } } suspend fun readlastsleep healthdatastore healthdatastore { val resultcount = 1 val readrequest = datatypes sleep readdatarequestbuilder setordering ordering desc setlimit resultcount build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { sleepdata -> val sleepid = sleepdata uid val sleepstarttime = sleepdata starttime val sleependtime = sleepdata endtime val sleepsessions = sleepdata getvalue datatype sleeptype sessions sleepsessions? foreach { sleepsession -> val sessionduration = sleepsession duration val sessionstarttime = sleepsession starttime val sessionendtime = sleepsession endtime val sleepstages = sleepsession stages sleepstages? foreach { sleepstage -> val sleepstagename = sleepstage stage name val sleepstagestarttime = sleepstage starttime val sleepstageendtime = sleepstage endtime } } } } catch e exception { e printstacktrace } } code for writing sleep data when using samsung health sdk for android is as follows writing the last night's sleep data with samsung health sdk for android fun insertsleepdata healthdatastore healthdatastore { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val healthdevicemanager = healthdevicemanager healthdatastore val zoneoffset = zoneoffset systemdefault rules getoffset instant now val starttime = localdate now minusdays 1 attime 23, 10 toinstant zoneoffset val endtime = localdate now attime 6, 30 toinstant zoneoffset val timeoffset = timezone getdefault getoffset instant now toepochmilli val sleepdata = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleep start_time, starttime toepochmilli putlong healthconstants sleep end_time, endtime toepochmilli putlong healthconstants sleep time_offset, timeoffset tolong } val insertrequest = insertrequest builder setdatatype healthconstants sleep health_data_type build insertrequest addhealthdata sleepdata try { val insertresult = healthdataresolver insert insertrequest await if insertresult status != baseresult status_successful { log i mainactivity app_tag, "error inserting sleep data error code ${insertresult status}" } } catch e exception { e printstacktrace } val resultcount = 1 val resultoffset = 0 val readrequest = healthdataresolver readrequest builder setdatatype healthconstants sleep health_data_type setsort healthconstants sleep update_time, sortorder desc setresultcount resultoffset, resultcount build try { val readresult = healthdataresolver read readrequest await val sleepid = readresult last getstring healthconstants sleep uuid writesleepstages healthdatastore, sleepid } catch e exception { e printstacktrace } } private fun writesleepstages healthdatastore healthdatastore, sleepid string { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val healthdevicemanager = healthdevicemanager healthdatastore val startdate = localdate now minusdays 1 val enddate = localdate now val zoneoffset = zoneoffset systemdefault rules getoffset instant now val timeoffset = timezone getdefault getoffset instant now toepochmilli val sleepstages = mutablelistof<healthdata> var sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, startdate attime 23, 10 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, startdate attime 23, 35 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_light } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, startdate attime 23, 35 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 1, 50 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_deep } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 1, 50 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 2, 20 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_rem } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 2, 20 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 2, 55 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_light } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 2, 55 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 3, 10 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_awake } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 3, 10 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 4, 30 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_deep } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 4, 30 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 5, 10 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_rem } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 5, 10 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 6, 20 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_light } sleepstages add sleepstage sleepstage = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants sleepstage time_offset, timeoffset tolong putstring healthconstants sleepstage sleep_id, sleepid putlong healthconstants sleepstage start_time, enddate attime 6, 20 toinstant zoneoffset toepochmilli putlong healthconstants sleepstage end_time, enddate attime 6, 30 toinstant zoneoffset toepochmilli putint healthconstants sleepstage stage, healthconstants sleepstage stage_awake } sleepstages add sleepstage val insertrequest = insertrequest builder setdatatype healthconstants sleepstage health_data_type build insertrequest addhealthdata sleepstages try { val insertresult = healthdataresolver insert insertrequest await if insertresult status != baseresult status_successful { log i mainactivity app_tag, "error inserting stages data error code ${insertresult status}" } } catch e exception { e printstacktrace } } when using samsung health data sdk to write sleep data is as follows writing the last night's sleep data with samsung health data sdk suspend fun insertsleepdata healthdatastore healthdatastore { val startdate = localdate now minusdays 1 val enddate = localdate now val starttime = startdate attime 23, 10 val endtime = enddate attime 6, 30 val zoneoffset = zoneoffset systemdefault rules getoffset instant now val duration = duration between starttime, endtime val sleepstagelist = listof sleepsession sleepstage of startdate attime 23, 10 toinstant zoneoffset , startdate attime 23, 35 toinstant zoneoffset , datatype sleeptype stagetype light , sleepsession sleepstage of startdate attime 23, 35 toinstant zoneoffset , enddate attime 1, 50 toinstant zoneoffset , datatype sleeptype stagetype deep , sleepsession sleepstage of enddate attime 1, 50 toinstant zoneoffset , enddate attime 2, 20 toinstant zoneoffset , datatype sleeptype stagetype rem , sleepsession sleepstage of enddate attime 2, 20 toinstant zoneoffset , enddate attime 2, 55 toinstant zoneoffset , datatype sleeptype stagetype light , sleepsession sleepstage of enddate attime 2, 55 toinstant zoneoffset , enddate attime 3, 10 toinstant zoneoffset , datatype sleeptype stagetype awake , sleepsession sleepstage of enddate attime 3, 10 toinstant zoneoffset , enddate attime 4, 30 toinstant zoneoffset , datatype sleeptype stagetype deep , sleepsession sleepstage of enddate attime 4, 30 toinstant zoneoffset , enddate attime 5, 10 toinstant zoneoffset , datatype sleeptype stagetype rem , sleepsession sleepstage of enddate attime 5, 10 toinstant zoneoffset , enddate attime 6, 20 toinstant zoneoffset , datatype sleeptype stagetype light , sleepsession sleepstage of enddate attime 6, 20 toinstant zoneoffset , enddate attime 6, 30 toinstant zoneoffset , datatype sleeptype stagetype awake val sleepsession = sleepsession of starttime toinstant zoneoffset , endtime toinstant zoneoffset , duration, sleepstagelist try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime setlocalendtime endtime addfielddata datatype sleeptype duration, duration addfielddata datatype sleeptype sessions, listof sleepsession build val insertdatarequest = datatypes sleep insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertdatarequest } catch e exception { e printstacktrace } } weight the corresponding weight data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants weight bodycompositiontype to read the latest weight data when using samsung health sdk for android, the following example code can be used reading the last weight data with samsung health sdk for android fun readlatestweight healthdatastore healthdatastore { val resultcount = 1 val resultoffset = 0 val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants weight health_data_type setsort healthconstants oxygensaturation start_time, sortorder desc setresultcount resultoffset, resultcount build try { healthdataresolver read request setresultlistener { result -> try { result lastornull ? let { healthdata -> val measurementstarttime = instant ofepochmilli healthdata getlong healthconstants weight start_time val weight = healthdata getfloat healthconstants weight weight val bodyfat = healthdata getfloat healthconstants weight body_fat } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read the latest weight data is as follows reading the last weight data with samsung health data sdk suspend fun readlatestweight healthdatastore healthdatastore { val resultcount = 1 val readrequest = datatypes body_composition readdatarequestbuilder setordering ordering desc setlimit resultcount build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { datapoint -> val weight = datapoint getvalue datatype bodycompositiontype weight val bodyfat = datapoint getvalue datatype bodycompositiontype body_fat val measurementstarttime = datapoint starttime } } catch e exception { e printstacktrace } } here is an example code to write weight data when using samsung health sdk for android writing weight data with samsung health sdk for android fun insertweightdata healthdatastore healthdatastore { val weight = 75f val zoneid = zoneoffset systemdefault val starttime = localdate now attime 9, 0 atzone zoneid toinstant toepochmilli val timeoffset = timezone getdefault getoffset starttime tolong val mhealthdataresolver = healthdataresolver healthdatastore, handler looper getmainlooper val healthdevicemanager = healthdevicemanager healthdatastore val data = healthdata apply { putlong healthconstants weight start_time, starttime putlong healthconstants weight time_offset, timeoffset putfloat healthconstants weight weight, weight // register local device as the source of data sourcedevice = healthdevicemanager localdevice uuid } try { val insertrequest = insertrequest builder setdatatype healthconstants weight health_data_type build insertrequest addhealthdata data val result = mhealthdataresolver insert insertrequest await log i mainactivity app_tag, "insert result status ${result status}" } catch e exception { e printstacktrace } } writing weight data with samsung health data sdk suspend fun insertweightdata healthdatastore healthdatastore { val weight = 75f val localdatetime = localdate now attime 9, 0 val zoneid = zoneoffset systemdefault val zoneoffset = zoneid rules getoffset localdatetime try { val healthdatapoint = healthdatapoint builder addfielddata datatype bodycompositiontype weight, weight setlocalstarttime localdatetime, zoneoffset build val insertrequest = datatypes body_composition insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest } catch e exception { e printstacktrace } } heart rate the corresponding heart rate data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants heartrate heartratetype example code for reading today's heart rate data when using samsung health sdk for android is as follows reading today's heart rate data with samsung health sdk for android class readheartrate { fun readtodayheartrate healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdatetime now toinstant zoneoffset utc toepochmilli val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants heartrate health_data_type setlocaltimerange healthconstants heartrate start_time, healthconstants heartrate time_offset, starttime, endtime build try { healthdataresolver read request setresultlistener { result -> try { result? foreach { healthdata -> val heartrate = healthdata getfloat healthconstants heartrate heart_rate val measurementstarttime = instant ofepochmilli healthdata getlong healthconstants heartrate start_time val measurementendtime = instant ofepochmilli healthdata getlong healthconstants heartrate end_time val binningdata = healthdata getblob healthconstants heartrate binning_data val livedatalist = healthdatautil getstructureddatalist binningdata, heartratelivedata class java livedatalist foreach { livedatapoint -> val heartrate = livedatapoint heart_rate val starttime = instant ofepochmilli livedatapoint start_time } } } finally { result close } } } catch e exception { e printstacktrace } } } data class heartratelivedata val heart_rate float, val heart_rate_min float, val heart_rate_max float, val start_time long, val end_time long when using samsung health data sdk to read today's heart rate data is as follows reading today's heart rate data with samsung health data sdk suspend fun readtodayheartrate healthdatastore healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime val readrequest = datatypes heart_rate readdatarequestbuilder setlocaltimefilter localtimefilter build try { val result = healthdatastore readdata readrequest result datalist foreach { datapoint -> val starttime = datapoint starttime val endtime = datapoint endtime val heartrate = datapoint getvalue datatype heartratetype heart_rate val heartrateseriesdata = datapoint getvalue datatype heartratetype series_data heartrateseriesdata? foreach { seriesdata -> val starttime = seriesdata starttime val heartrate = seriesdata heartrate } } } catch e exception { e printstacktrace } } to write heart rate data when using samsung health sdk for android, the following example code can be used writing heart rate data with samsung health sdk for android fun inserttodayheartrate healthdatastore healthdatastore { val tenminutesasseconds = 600l val heartrate = 76f val heartbeatcount = 1 val deviceid = healthdevicemanager healthdatastore localdevice uuid val starttime = instant now minusseconds tenminutesasseconds toepochmilli val endtime = instant now toepochmilli val timeoffset = timezone getdefault getoffset endtime tolong val healthdataresolver = healthdataresolver healthdatastore, null val healthdata = healthdata apply { sourcedevice = deviceid putlong heartrate start_time, starttime putlong heartrate end_time, endtime putlong heartrate time_offset, timeoffset putfloat heartrate heart_rate, heartrate putint heartrate heart_beat_count, heartbeatcount } val insertrequest = healthdataresolver insertrequest builder setdatatype heartrate health_data_type build insertrequest addhealthdata healthdata try { val result = healthdataresolver insert insertrequest await if result status == status_successful { log i mainactivity app_tag, "inserted heart rate count of data ${result count}" } else { log i mainactivity app_tag, "inserting failed" } } catch e exception { e printstacktrace } } when using samsung health data sdk to write heart rate data is as follows writing heart rate data with samsung health data sdk suspend fun inserttodayheartrate healthdatastore healthdatastore { val tenminutesasseconds = 600l val heartrate = 76f val starttime = localdatetime now minusseconds tenminutesasseconds val endtime = localdatetime now try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime setlocalendtime endtime addfielddata datatype heartratetype heart_rate, heartrate build val insertrequest = datatypes heart_rate insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest log i mainactivity app_tag, "inserted heart rate" } catch e exception { e printstacktrace } } blood glucose the corresponding blood glucose data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants bloodglucose bloodglucosetype here is an example code to read today's blood glucose data when using samsung health sdk for android reading today's blood glucose data with samsung health sdk for android fun readtodaybloodglucose healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdatetime now toinstant zoneoffset utc toepochmilli val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants bloodglucose health_data_type setlocaltimerange healthconstants oxygensaturation start_time, healthconstants oxygensaturation time_offset, starttime, endtime build try { healthdataresolver read request setresultlistener { result -> try { result foreach { healthdata -> val measurementstarttime = instant ofepochmilli healthdata getlong healthconstants bloodglucose start_time val bloodglucose = healthdata getfloat healthconstants bloodglucose glucose //refer to the documentation for meal_type, measurement_type, sample_source_type mapping val mealtype = healthdata getint healthconstants bloodglucose meal_type val measurementtype = healthdata getint healthconstants bloodglucose measurement_type val samplesourcetype = healthdata getint healthconstants bloodglucose sample_source_type } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read today's blood glucose data is as follows reading today's blood glucose data with samsung health data sdk fun readtodaybloodglucose healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdatetime now toinstant zoneoffset utc toepochmilli val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants bloodglucose health_data_type setlocaltimerange healthconstants oxygensaturation start_time, healthconstants oxygensaturation time_offset, starttime, endtime build try { healthdataresolver read request setresultlistener { result -> try { result foreach { healthdata -> val measurementstarttime = instant ofepochmilli healthdata getlong healthconstants bloodglucose start_time val bloodglucose = healthdata getfloat healthconstants bloodglucose glucose //refer to the documentation for meal_type, measurement_type, sample_source_type mapping val mealtype = healthdata getint healthconstants bloodglucose meal_type val measurementtype = healthdata getint healthconstants bloodglucose measurement_type val samplesourcetype = healthdata getint healthconstants bloodglucose sample_source_type } } finally { result close } } } catch e exception { e printstacktrace } } code for writing sleep data when using samsung health sdk for android is as follows writing blood glucose data with samsung health sdk for android fun insertbloodglucosedata healthdatastore healthdatastore { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val healthdevicemanager = healthdevicemanager healthdatastore val tenminutesasseconds = 600l val starttime = instant now minusseconds tenminutesasseconds val timeoffset = timezone getdefault getoffset starttime toepochmilli val glucose = 4 8f val bloodglucosedata = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants bloodpressure start_time, starttime toepochmilli putlong healthconstants bloodglucose time_offset, timeoffset tolong putfloat healthconstants bloodglucose glucose, glucose putint healthconstants bloodglucose measurement_type, healthconstants bloodglucose measurement_type_whole_blood putint healthconstants bloodglucose meal_type, healthconstants bloodglucose meal_type_fasting } val insertrequest = insertrequest builder setdatatype healthconstants bloodglucose health_data_type build insertrequest addhealthdata bloodglucosedata try { val insertresult = healthdataresolver insert insertrequest await if insertresult status != baseresult status_successful { log i mainactivity app_tag, "error inserting blood glucose data error code ${insertresult status}" } } catch e exception { e printstacktrace } } example code for writing blood glucose data when using samsung health data sdk is as follows writing blood glucose data with samsung health data sdk suspend fun insertbloodglucosedata healthdatastore healthdatastore { val starttime = localdatetime now minusminutes 10 val glucose = 4 8f try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime setlocalendtime starttime addfielddata datatype bloodglucosetype glucose_level, glucose addfielddata datatype bloodglucosetype measurement_type, datatype bloodglucosetype measurementtype whole_blood addfielddata datatype bloodglucosetype meal_status, datatype bloodglucosetype mealstatus fasting build val insertdatarequest = datatypes blood_glucose insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertdatarequest } catch e exception { e printstacktrace } } blood oxygen the corresponding blood oxygen data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants oxygensaturationtype bloodoxygentype example code for reading the latest blood oxygen data when using samsung health sdk for android is as follows reading the latest blood oxygen data with samsung health sdk for android fun readlatestbloodoxygen healthdatastore healthdatastore { val resultoffset = 0; val resultcount = 1 val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants oxygensaturation health_data_type setsort healthconstants oxygensaturation start_time, sortorder desc setresultcount resultoffset, resultcount build try { healthdataresolver read request setresultlistener { result -> try { result lastornull ? let { healthdata -> val bloodoxygen = healthdata getfloat healthconstants oxygensaturation spo2 val measurementstarttime = instant ofepochmilli healthdata getlong healthconstants oxygensaturation start_time } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read the latest blood oxygen data is as follows reading the latest blood oxygen data with samsung health data sdk suspend fun readlatestbloodoxygen healthdatastore healthdatastore { val resultcount = 1 val readrequest = datatypes blood_oxygen readdatarequestbuilder setordering ordering desc setlimit resultcount build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { datapoint -> val bloodoxygen = datapoint getvalue datatype bloodoxygentype oxygen_saturation val measurementstarttime = datapoint starttime } } catch e exception { e printstacktrace } } here is an example code to write blood oxygen data when using samsung health sdk for android writing blood oxygen data with samsung health sdk for android fun insertbloodoxygendata healthdatastore healthdatastore { val bloodoxygen = 98f val tenminutesasseconds = 10l * 60l val zoneid = zoneoffset systemdefault val time = localdatetime now minusseconds tenminutesasseconds atzone zoneid toinstant toepochmilli val timeoffset = timezone getdefault getoffset time tolong val mhealthdataresolver = healthdataresolver healthdatastore, handler looper getmainlooper val healthdevicemanager = healthdevicemanager healthdatastore val data = healthdata apply { putlong healthconstants oxygensaturation start_time, time putlong healthconstants oxygensaturation end_time, time putlong healthconstants oxygensaturation time_offset, timeoffset putfloat healthconstants oxygensaturation spo2, bloodoxygen // register local device as the source of data sourcedevice = healthdevicemanager localdevice uuid } try { val insertrequest = insertrequest builder setdatatype healthconstants oxygensaturation health_data_type build insertrequest addhealthdata data val result = mhealthdataresolver insert insertrequest await log i mainactivity app_tag, "insert result status ${result status}" } catch e exception { e printstacktrace } } example code for writing blood oxygen data when using samsung health data sdk is as follows writing blood oxygen data with samsung health data sdk suspend fun insertbloodoxygendata healthdatastore healthdatastore { val bloodoxygen = 98f val tenminutesasseconds = 10l * 60l val time = localdatetime now minusseconds tenminutesasseconds val zoneid = zoneoffset systemdefault val zoneoffset = zoneid rules getoffset time try { val healthdatapoint = healthdatapoint builder addfielddata datatype bloodoxygentype oxygen_saturation, bloodoxygen setlocalstarttime time, zoneoffset setlocalendtime time, zoneoffset build val insertrequest = datatypes blood_oxygen insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest } catch e exception { e printstacktrace } } blood pressure the corresponding blood pressure data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants bloodpressure bloodpressuretype code for reading the latest blood pressure data when using samsung health sdk for android is as follows reading the latest blood pressure data with samsung health sdk for android fun readlatestbloodpressure healthdatastore healthdatastore { val resultoffset = 0; val resultcount = 1 val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants bloodpressure health_data_type setsort healthconstants bloodpressure start_time, sortorder desc setresultcount resultoffset, resultcount build try { healthdataresolver read request setresultlistener { result -> try { result? lastornull ? let { healthdata -> val starttime = instant ofepochmilli healthdata getlong healthconstants bloodpressure start_time val systolicpressure = healthdata getfloat healthconstants bloodpressure systolic val diastolicpressure = healthdata getfloat healthconstants bloodpressure diastolic val mean = healthdata getfloat healthconstants bloodpressure mean val pulse = healthdata getint healthconstants bloodpressure pulse val sourcepackagename = healthdata getstring healthconstants common package_name val sourcedeviceid = healthdata getstring healthconstants common device_uuid } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read the latest blood pressure data is as follows reading the latest blood pressure data with samsung health data sdk suspend fun readlatestbloodpressure healthdatastore healthdatastore { val resultcount = 1 val readrequest = datatypes blood_pressure readdatarequestbuilder setordering ordering desc setlimit resultcount build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { datapoint -> val starttime = datapoint starttime val systolicpressure = datapoint getvalue datatype bloodpressuretype systolic val diastolicpressure = datapoint getvalue datatype bloodpressuretype diastolic val mean = datapoint getvalue datatype bloodpressuretype mean val pulse = datapoint getvalue datatype bloodpressuretype pulse_rate val sourcepackagename = datapoint datasource? appid val sourcedeviceid = datapoint datasource? deviceid } } catch e exception { e printstacktrace } } code for writing blood pressure data when using samsung health sdk for android is as follows writing blood pressure data with samsung health sdk for android fun insertbloodpressuredata healthdatastore healthdatastore { val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val healthdevicemanager = healthdevicemanager healthdatastore val tenminutesasseconds = 600l val starttime = instant now minusseconds tenminutesasseconds val timeoffset = timezone getdefault getoffset starttime toepochmilli val systolic = 119f val diastolic = 87f val mean = 0f val bloodpressuredata = healthdata apply { sourcedevice = healthdevicemanager localdevice uuid putlong healthconstants bloodpressure start_time, starttime toepochmilli putlong healthconstants bloodpressure time_offset, timeoffset tolong putfloat healthconstants bloodpressure systolic, systolic putfloat healthconstants bloodpressure diastolic, diastolic putfloat healthconstants bloodpressure mean, mean } val insertrequest = insertrequest builder setdatatype healthconstants bloodpressure health_data_type build insertrequest addhealthdata bloodpressuredata try { val insertresult = healthdataresolver insert insertrequest await if insertresult status != baseresult status_successful { log i mainactivity app_tag, "error inserting blood pressure data error code ${insertresult status}" } } catch e exception { e printstacktrace } } example code for writing blood pressure data when using samsung health data sdk is as follows writing blood pressure data with samsung health data sdk suspend fun insertbloodpressuredata healthdatastore healthdatastore { val starttime = localdatetime now minusminutes 10 val systolic = 119f val diastolic = 87f val mean = 0f try { val healthdatapoint = healthdatapoint builder setlocalstarttime starttime addfielddata datatype bloodpressuretype systolic, systolic addfielddata datatype bloodpressuretype diastolic, diastolic addfielddata datatype bloodpressuretype mean, mean build val insertdatarequest = datatypes blood_pressure insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertdatarequest } catch e exception { e printstacktrace } } body temperature the corresponding body temperature data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthconstants bodytemperature bodytemperaturetype here is an example of code that reads today's body temperature data when using samsung health sdk for android reading today's body temperature data with samsung health sdk for android fun readtodaybodytemperature healthdatastore healthdatastore { val starttime = localdate now atstartofday toinstant zoneoffset utc toepochmilli val endtime = localdatetime now toinstant zoneoffset utc toepochmilli val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val readrequest healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants bodytemperature health_data_type setlocaltimerange healthconstants bodytemperature start_time, healthconstants bodytemperature time_offset, starttime, endtime build try { healthdataresolver read readrequest setresultlistener { result -> try { result lastornull ? let { healthdata -> val measurementstarttime = date healthdata getlong healthconstants bodytemperature start_time val bodytemperature = healthdata getfloat healthconstants bodytemperature temperature } } finally { result close } } } catch e exception { e printstacktrace } } when using samsung health data sdk to read today's body temperature data is as follows reading today's body temperature samsung health data sdk suspend fun readtodaybodytemperature healthdatastore com samsung android sdk health data healthdatastore { val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime val readrequest = datatypes body_temperature readdatarequestbuilder setlocaltimefilter localtimefilter build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { datapoint -> val measurementstarttime = datapoint starttime val bodytemperature = datapoint getvalue datatype bodytemperaturetype body_temperature } } catch e exception { e printstacktrace } } example code for writing body temperature data when using samsung health sdk for android is as follows writing body temperature data with samsung health sdk for android fun insertbodytemperaturedata healthdatastore healthdatastore { val bodytemperature = 37f val tenminutesasseconds = 10l * 60l val zoneid = zoneoffset systemdefault val starttime = localdatetime now minusseconds tenminutesasseconds atzone zoneid toinstant toepochmilli val timeoffset = timezone getdefault getoffset starttime tolong val mhealthdataresolver = healthdataresolver healthdatastore, handler looper getmainlooper val healthdevicemanager = healthdevicemanager healthdatastore val data = healthdata apply { putlong healthconstants bodytemperature start_time, starttime putlong healthconstants bodytemperature time_offset, timeoffset putfloat healthconstants bodytemperature temperature, bodytemperature // register local device as the source of data sourcedevice = healthdevicemanager localdevice uuid } try { val insertrequest = insertrequest builder setdatatype healthconstants bodytemperature health_data_type build insertrequest addhealthdata data val result = mhealthdataresolver insert insertrequest await log i mainactivity app_tag, "insert result status ${result status}" } catch e exception { e printstacktrace } } when using samsung health data sdk to write body temperature data is as follows writing body temperature data with samsung health data sdk suspend fun insertbodytemperaturedata healthdatastore healthdatastore { val bodytemperature = 37f val tenminutesasseconds = 10l * 60l val time = localdatetime now minusseconds tenminutesasseconds val zoneid = zoneoffset systemdefault val zoneoffset = zoneid rules getoffset time try { val healthdatapoint = healthdatapoint builder addfielddata datatype bodytemperaturetype body_temperature, bodytemperature setlocalstarttime time, zoneoffset setlocalendtime time, zoneoffset build val insertrequest = datatypes body_temperature insertdatarequestbuilder adddata healthdatapoint build healthdatastore insertdata insertrequest } catch e exception { e printstacktrace } } user profile the corresponding user profile data types in samsung health sdk for android and samsung health data sdk are as following samsung health sdk for android samsung health data sdk healthuserprofile userprofiledatatype example code for getting user profile data when using samsung health sdk for android is as follows getting user profile data with samsung health sdk for android fun readuserprofile healthdatastore healthdatastore { val userprofile = healthuserprofile getprofile healthdatastore val gender = gendernamebyid userprofile gender val height = userprofile height val weight = userprofile weight } fun gendernamebyid id int string { return when id { healthuserprofile gender_male -> "male" healthuserprofile gender_female -> "female" else -> "unknown" } } example code for getting user profile data when using samsung health data sdk is as follows getting user profile data with samsung health data sdk suspend fun readuserprofile healthdatastore healthdatastore { val readrequest = datatypes user_profile readdatarequestbuilder build try { val result = healthdatastore readdata readrequest result datalist lastornull ? let { datapoint -> val gender = datapoint getvalue datatype userprofiledatatype gender val height = datapoint getvalue datatype userprofiledatatype height val weight = datapoint getvalue datatype userprofiledatatype weight } } catch e exception { e printstacktrace } } getting data's source device code for getting source device information that provided sleep data when using samsung health sdk for android is as follows getting data's source device information with samsung health sdk for android fun getsourcedeviceinfoofsleepdata healthdatastore healthdatastore { val resultcount = 1 val resultoffset = 0 val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler val request healthdataresolver readrequest = healthdataresolver readrequest builder setdatatype healthconstants sleep health_data_type setsort healthconstants sleep start_time, sortorder desc setresultcount resultoffset, resultcount build try { healthdataresolver read request setresultlistener { result -> try { result? foreach { healthdata -> val deviceid = healthdata getstring healthconstants sleep device_uuid val healthdevice = healthdevicemanager healthdatastore getdevicebyuuid deviceid val devicename = healthdevice customname val devicetype = devicegroupnamebyid healthdevice group } } finally { result close } } } catch e exception { e printstacktrace } } fun devicegroupnamebyid id int string { return when id { healthdevice group_mobile -> "mobile" healthdevice group_external -> "external" healthdevice group_companion -> "companion or watch" else -> "unknown" } } to get source device information that provided sleep data when using samsung health data sdk, the following example code can be used getting data's source device information with samsung health data sdk suspend fun getsourcedeviceinfoofsleepdata healthdatastore healthdatastore { val resultcount = 1 val readrequest = datatypes sleep readdatarequestbuilder setordering ordering desc setlimit resultcount build try { val result = healthdatastore readdata readrequest result datalist foreach { sleepdata -> val devicemanager = healthdatastore getdevicemanager sleepdata datasource? let { datasource -> val device = devicemanager getdevice datasource deviceid val deviceid = device? id val devicename = device? name val devicetype = device? devicetype } } } catch e exception { e printstacktrace } } partnership migration to samsung health data sdk once you have completed the migration implementation from samsung health sdk for android to samsung health data sdk and successfully finished testing using developer mode, you can request partnership migration to use samsung health data sdk during the partnership migration process, the partnership information previously approved for using samsung health sdk for android is leveraged, allowing you to complete the approval process for samsung health data sdk more efficiently here, you can find the instructions for partnership migration if you have already applied for partnership approval for samsung health data sdk using the application package name of your current app to write data to samsung health and use developer mode, you do not need to proceed with the partnership migration process having a trouble? we are operating a developer support channel on the samsung developer site if you encounter any issue or any question, please visit developer support and submit your query after logging in your samsung account
Develop Health
docprivacy privacy is a key for handling health data samsung health sdk for android enables your application to access health data based on the user's consent permission manager the sdk's supported data types except health document need to gain permission through permissionmanager an application needs to declare proper permissions for handling required health data types and to consider secureexception when the application didn't gain a user consent the user can withdraw consent at any time see permissionmanager for permission declaration and request samsung health add the partner app's permission info under samsung health > settings > data permissions > [partner app] after a success of healthpermissionmanager requestpermission in the partner app on the other hand, the partner app needs to make a permission setting menu separately in the menu, the app calls healthpermissionmanager requestpermission with required permissions the samsung health's health data framework pops up the permission ui a permission result event is retreived after the user's agreement or denial on the permission popup the app should provide an interface that the user may change data permission at any time the user consent is limited to the device even if multiple devices use the same samsung account, the application has to acquire the user consent on each device independently instant permission a very sensitive data type like a health document requires gaining instant permission instant permission is created for one-time data access an app that handles a health document has to call the instant permission api whenever it needs to access data related apis are healthdataresolver insertwithpermission healthdataresolver readwithpermission healthdataresolver deletewithpermission
Develop Health
apisamsung health data sdk/com samsung android sdk health data package-level declarations types types devicemanager link copied to clipboard interface devicemanagerit retrieves information about the devices that provide the health data stored in the samsung health app healthdataservice link copied to clipboard object healthdataservicethe entry point for connecting to the samsung health data store healthdatastore link copied to clipboard interface healthdatastorehealthdatastore is a proxy that provides a way to access the data stored in the samsung health app
Develop Health
apisamsung health data sdk/com samsung android sdk health data data/datasource datasource class datasource parcelablespecifies the app and device that provided the health data the appid for the data created by the samsung health app is "com sec android app shealth" if the deviceid of the health data is the same as that returned by com samsung android sdk health data devicemanager getlocaldevice, the data has been created by the local device on which the samsung health app is installed since1 0 0see alsohealthdatapoint datasource members properties appid link copied to clipboard val appid stringthe unique identifier of the source app deviceid link copied to clipboard val deviceid stringthe unique identifier of the source device
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
You have successfully updated your cookie preferences.