Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
tutorials health, galaxy watch, mobile
blogthe samsung health sensor sdk enables your application to collect vital signs and other health parameters tracked on galaxy watch running wear os powered by samsung. the tracked data can be displayed immediately or retained for later analysis. some kinds of tracked data, such as batching data, are impractical to display on a watch screen in real-time, so it is common to store the data in a database or server solution or show them on the larger screen of a mobile device. this blog demonstrates how to develop two connected sample applications. a watch application uses the samsung health sensor sdk to collect heart rate tracker data, then uses the wearable data layer api to transmit it to a companion application on the user’s android mobile device, which displays the data as a simple list on its screen. you can follow along with the demonstration by downloading the sample application project. to test the applications, you need a galaxy watch4 (or higher model) and a connected android mobile device. creating the application project the application project consists of a wearable module for the watch, and a mobile module for android mobile devices: in android studio, select open file > new > new project. select wear os > empty wear app and click next. new wear app define the project details. project details to create a companion mobile application for the watch application, check the pair with empty phone app box. notemake sure that the application id is identical for both modules in their “build.gradle” files. for more information about creating multi-module projects, see from wrist to hand: develop a companion app for your wearable application. implementing the watch application the watch application ui has two buttons. the start/stop button controls heart data tracking, and the send button transfers the collected data to the connected mobile device. the screen consists of a heart rate field and 4 ibi value fields, since there can be up to 4 ibi values in a single tracking result. watch application ui track and extract heart rate data when the user taps the start button on the wearable application ui, the starttracking() function from the mainviewmodel class is invoked. the application must check that the galaxy watch supports the heart rate tracking capability that we want to implement, as the supported capabilities depend on the device model and software version. retrieve the list of supported health trackers with the trackingcapability.supporthealthtrackertypes of the healthtrackingservice class: override fun hascapabilities(): boolean { log.i(tag, "hascapabilities()") healthtrackingservice = healthtrackingserviceconnection.gethealthtrackingservice() val trackers: list<healthtrackertype> = healthtrackingservice!!.trackingcapability.supporthealthtrackertypes return trackers.contains(trackingtype) } to track the heart rate values on the watch, read the flow of values received in the ondatareceived() listener: @experimentalcoroutinesapi override suspend fun track(): flow<trackermessage> = callbackflow { val updatelistener = object : healthtracker.trackereventlistener { override fun ondatareceived(datapoints: mutablelist<datapoint>) { for (datapoint in datapoints) { var trackeddata: trackeddata? = null val hrvalue = datapoint.getvalue(valuekey.heartrateset.heart_rate) val hrstatus = datapoint.getvalue(valuekey.heartrateset.heart_rate_status) if (ishrvalid(hrstatus)) { trackeddata = trackeddata() trackeddata.hr = hrvalue log.i(tag, "valid hr: $hrvalue") } else { coroutinescope.runcatching { trysendblocking(trackermessage.trackerwarningmessage(geterror(hrstatus.tostring()))) } } val validibilist = getvalidibilist(datapoint) if (validibilist.size > 0) { if (trackeddata == null) trackeddata = trackeddata() trackeddata.ibi.addall(validibilist) } if ((ishrvalid(hrstatus) || validibilist.size > 0) && trackeddata != null) { coroutinescope.runcatching { trysendblocking(trackermessage.datamessage(trackeddata)) } } if (trackeddata != null) { validhrdata.add(trackeddata) } } trimdatalist() } fun geterror(errorkeyfromtracker: string): string { val str = errors.getvalue(errorkeyfromtracker) return context.resources.getstring(str) } override fun onflushcompleted() { log.i(tag, "onflushcompleted()") coroutinescope.runcatching { trysendblocking(trackermessage.flushcompletedmessage) } } override fun onerror(trackererror: healthtracker.trackererror?) { log.i(tag, "onerror()") coroutinescope.runcatching { trysendblocking(trackermessage.trackererrormessage(geterror(trackererror.tostring()))) } } } heartratetracker = healthtrackingservice!!.gethealthtracker(healthtrackertype.heart_rate_continuous) setlistener(updatelistener) awaitclose { log.i(tag, "tracking flow awaitclose()") stoptracking() } } each tracking result is within a list in the datapoints argument of the ondatareceived() update listener. the sample application implements continuous heart rate tracking. to extract a heart rate from data point: val hrvalue = datapoint.getvalue(valuekey.heartrateset.heart_rate) val hrstatus = datapoint.getvalue(valuekey.heartrateset.heart_rate_status) a status parameter is returned in addition to the heart rate data. if the heart rate reading was successful, its value is 1. each inter-beat interval data point consists of a list of values and the corresponding status for each value. there can be up to 4 ibi values in a single data point, depending on the heart rate. if the ibi reading is valid, the value of the status parameter is 0. to extract only ibi data that is valid and whose value is not 0: private fun isibivalid(ibistatus: int, ibivalue: int): boolean { return ibistatus == 0 && ibivalue != 0 } fun getvalidibilist(datapoint: datapoint): arraylist<int> { val ibivalues = datapoint.getvalue(valuekey.heartrateset.ibi_list) val ibistatuses = datapoint.getvalue(valuekey.heartrateset.ibi_status_list) val validibilist = arraylist<int>() for ((i, ibistatus) in ibistatuses.withindex()) { if (isibivalid(ibistatus, ibivalues[i])) { validibilist.add(ibivalues[i]) } } send data to the mobile application the application uses the messageclient class of the wearable data layer api to send messages to the connected mobile device. messages are useful for remote procedure calls (rpc), one-way requests, or in request-or-response communication models. when a message is sent, if the sending and receiving devices are connected, the system queues the message for delivery and returns a successful result code. the successful result code does not necessarily mean that the message was delivered successfully, as the devices can be disconnected before the message is received. to advertise and discover devices on the same network with features that the watch can interact with, use the capabilityclient class of the wearable data layer api. each device on the network is represented as a node that supports various capabilities (features) that an application defines at build time or configures dynamically at runtime. your watch application can search for nodes with a specific capability and interact with it, such as sending messages. this can also work in the opposite direction, with the wearable application advertising the capabilities it supports. when the user taps the send button on the wearable application ui, the sendmessage() function from the mainviewmodel class is invoked, which triggers code in the sendmessageusecase class: override suspend fun sendmessage(message: string, node: node, messagepath: string): boolean { val nodeid = node.id var result = false nodeid.also { id -> messageclient .sendmessage( id, messagepath, message.tobytearray(charset = charset.defaultcharset()) ).apply { addonsuccesslistener { log.i(tag, "sendmessage onsuccesslistener") result = true } addonfailurelistener { log.i(tag, "sendmessage onfailurelistener") result = false } }.await() log.i(tag, "result: $result") return result } } to find a destination node for the message, retrieve all the available capabilities on the network: override suspend fun getcapabilitiesforreachablenodes(): map<node, set<string>> { log.i(tag, "getcapabilities()") val allcapabilities = capabilityclient.getallcapabilities(capabilityclient.filter_reachable).await() return allcapabilities.flatmap { (capability, capabilityinfo) -> capabilityinfo.nodes.map { it to capability } } .groupby( keyselector = { it.first }, valuetransform = { it.second } ) .mapvalues { it.value.toset() } } since the mobile module of the sample application advertises having the “wear” capability, to find an appropriate destination node, retrieve the list of connected nodes that support it: override suspend fun getnodesforcapability( capability: string, allcapabilities: map<node, set<string>> ): set<node> { return allcapabilities.filtervalues { capability in it }.keys } select the first node from the list, encode the message as a json string, and send the message to the node: suspend operator fun invoke(): boolean { val nodes = getcapablenodes() return if (nodes.isnotempty()) { val node = nodes.first() val message = encodemessage(trackingrepository.getvalidhrdata()) messagerepository.sendmessage(message, node, message_path) true } else { log.i(tag, "no compatible nodes found") false } } implementing the mobile application the mobile application ui consists of a list of the heart rate and inter-beat interval values received from the watch. the list is scrollable. mobile application ui receive and display data from the watch application to enable the mobile application to listen for data from the watch and launch when it receives data, define the datalistenerservice service in the mobile application’s androidmanifest.xml file, within the <application> element: <service android:name="com.samsung.health.mobile.data.datalistenerservice" android:exported="true"> <intent-filter> <action android:name="com.google.android.gms.wearable.data_changed" /> <action android:name="com.google.android.gms.wearable.message_received" /> <action android:name="com.google.android.gms.wearable.request_received" /> <action android:name="com.google.android.gms.wearable.capability_changed" /> <action android:name="com.google.android.gms.wearable.channel_event" /> <data android:host="*" android:pathprefix="/msg" android:scheme="wear" /> </intent-filter> </service> implement the datalistenerservice class in the application code to listen for and receive message data. the received json string data is passed as a parameter: private const val tag = "datalistenerservice" private const val message_path = "/msg" class datalistenerservice : wearablelistenerservice() { override fun onmessagereceived(messageevent: messageevent) { super.onmessagereceived(messageevent) val value = messageevent.data.decodetostring() log.i(tag, "onmessagereceived(): $value") when (messageevent.path) { message_path -> { log.i(tag, "service: message (/msg) received: $value") if (value != "") { startactivity( intent(this, mainactivity::class.java) .addflags(intent.flag_activity_new_task).putextra("message", value) ) } else { log.i(tag, "value is an empty string") } } } to decode the message data: fun decodemessage(message: string): list<trackeddata> { return json.decodefromstring(message) } to display the received data on the application screen: @composable fun mainscreen( results: list<trackeddata> ) { column( modifier = modifier .fillmaxsize() .background(color.black), verticalarrangement = arrangement.top, horizontalalignment = alignment.centerhorizontally ) { spacer( modifier .height(70.dp) .fillmaxwidth() .background(color.black) ) listview(results) } } running the applications to run the wearable and mobile applications: connect your galaxy watch and android mobile device (both devices must be paired with each other) to android studio on your computer. select wear from the modules list and the galaxy watch device from the devices list, then click run. the wearable application launches on the watch. connected devices select mobile from the modules list and the android mobile device from the devices list, then click run. the mobile application launches on the mobile device. wear the watch on your wrist and tap start. the watch begins tracking your heart rate. after some tracked values appear on the watch screen, to send the values to the mobile application, tap send. if the mobile application is not running, it is launched. the tracked heart data appears on the mobile application screen. to stop tracking, tap stop on the watch. conclusions the samsung health sensor sdk enables you to track health data, such as heart rate, from a user’s galaxy watch4 or higher smartwatch model. to display the tracked data on a larger screen, you can use the messageclient of the wearable data layer api to send the data to a companion application on the connected mobile device. to develop more advanced application features, you can also use the dataclient class to send data to devices not currently in range of the watch, delivering it only when the device is connected. resources heart rate data transfer code lab
Samsung Developers
Learn Code Lab
codelabestablish a health research system using samsung health research stack objective learn how to create a health research system that collects data from mobile and wearable devices and visualizes the collected data in a web portal using samsung health research stack overview samsung health research stack is an open-source toolset that helps collect and analyze data from devices in android and wear os environments it provides tools and infrastructure for developing and deploying health studies, ranging from medical research to clinician services and more the framework consists of four components backend services - offers api endpoints to access and interact with a robust data engine web portal - a customizable interface for creating surveys, managing team members, tracking subjects, and analyzing data app sdk - an sdk for building android and wear os apps capable of collecting data from wearable devices starter app - a health research app with mobile and wearable versions created using basic features provided by the app sdk for detailed information, see samsung health research stack set up your environment you will need the following android studio latest version recommended samsung galaxy mobile device with updated health connect app and samsung health app installed samsung galaxy watch synced to the mobile device docker desktop sample code to start your learning experience, download the project files of the samsung health research stack starter mobile and wearable app notedepending on your preferred development style, you can either download or clone the repository of the project files to your local computer feel free to edit and customize this project for your own purposes, including this code lab activity set up your galaxy mobile and watch device connect your galaxy mobile device to your pc and enable adb debugging next, connect your galaxy watch to android studio over wi-fi lastly, enable the developer mode of the health platform app on your watch by following these steps a go to settings b tap on apps c select health platform d quickly tap on health platform several times until [dev mode] appears notethe samsung health developer mode is only intended for testing or debugging your application it is not for application users deploy the backend and web portal locally download the backend-config-files zip file and unzip it the folder contains the docker-compose yaml file open the terminal window of docker desktop in the terminal, go to the directory where your docker-compose yaml file is located, and run the following command $ docker compose up –d the script deploys the backend and the web portal to your local computer, and it includes 6 services redis - redis watcher for the backend casbin service mongo - for saving data from the backend postgres - for supertokens database and the backend casbin database supertokens - for username and password authentication backend - backend for the samsung health research stack portal - web portal for the samsung health research stack you can change the port number, username, and password for each database with the default setting, you can access the web portal in your browser at localhost 80 the script file has simple settings for easy deployment to add more features, you can change the environment in the docker-compose yaml file's services > backend > environment part set the aws environment variables optional you can enable uploading and downloading features by setting the following aws environment variables aws_bucket_name aws_region aws_access_key_id aws_secret_access_key aws_session_token you can follow the instructions in using the default credential provider chain for setting up aws credentials set google openid connect optional to enable google openid connect oidc login, you can set the following environment variables oidc_google_oauth2_url default "https //oauth2 googleapis com" oidc_google_client_id oidc_google_client_secret oidc_google_redirect_uri you can refer to openid connect for more information about setting google oidc create a new study the health research system has two user groups investigators - conduct research studies and use the web portal for managing studies and analyzing data subjects - participate in studies by answering surveys and performing tasks through the mobile app, as well as collecting health data from wearable apps to start your research study, as an investigator, follow the steps below create an account and sign in to the web portal page you deployed fill out the form with your information on the study collection page, click the create study button noteall enrolled investigators can create a study the creator becomes the study admin in the basic info tab, input the details of the study 5 for the study scope, choose public noteyou can set the study scope as either public or private if you choose private, you need to input a participation code that subjects must enter into the mobile app to join however, for the ease of testing in this code lab, it is recommended to set the scope as public for the study requirements field, you can input any text and click next go to participation requirements tab and select the data types to collect in wear category for this code lab, choose wear accelerometer wear ecg wear heart rate the logo and title of the created study show on the study collection page connect the mobile app to backend system to connect the starter mobile app to the backend system, follow these steps noteto ensure that the galaxy mobile device can connect to the machine where the backend system is deployed, it is recommended to connect both the machine and the mobile device to the same network open the downloaded project file in android studio and go to samples > starter-mobile-app in the local properties file, set the server_address to the ip address of the machine where the backend system is deployed server_address ="input ip address here" tipyou can check your ip address using the command line windows in command prompt, type ipconfig and find the ip address under ipv4 address mac in terminal, type ifconfig and look for the ip address under inet next to en0 next, set the server_port to 50001 if you used the default values in the provided docker-compose yaml file for deployment if not, use the port number you set server_port=50001 set authentication method the app sdk supports three types of authentication methods for registration samsung utilizes samsung account cognito incorporates amazon cognito authentication super-tokens enables anonymous login to allow research participants to register and log in using their personal emails, set the sign_in_mode as super-tokens in the local properties file sign_in_mode="super-tokens" upload wearable data via grpc when synchronizing wearable device data, the app sdk offers two approaches utilizing grpc for high-performance remote procedure calls or synchronization through files each approach has advantages and disadvantages regarding factors such as battery life and server workload however, it is advisable to utilize grpc during local development to configure the mobile application to upload wearable data via grpc rather than files, add the following code in the local properties file enable_upload_wearble_data_by_file=false show the sync button in starter wearable app after configuring the mobile app, modify the wearable app to meet the requirements of your study go to samples > starter-wearable-app and open the local properties file the wearable app features a sync button, which can be displayed or hidden when this button is pressed, it synchronizes the collected data with the backend system instantly to show the sync button, set the value of enable_instant_sync_button as below enable_instant_sync_button=true notethis instant sync feature can negatively affect the battery consumption of both apps, so it is recommended to remove the sync button when you publish your app the samsung health research stack has an optimized data synchronization process that minimizes battery consumption set data measurement parameters you can customize the data collection and storage process of the wearable app by setting the values of the following data measurement parameters passive_data_insert_interval_in_seconds sets the data measurement buffer the buffer saves data in an in-memory database before the interval expires then, at regular intervals, the data from the buffer is stored in persistent memory data_split_interval_in_millis specifies the size of segmented data in persistent memory if these values are not specified, the wearable app uses its default values to verify that the data is being measured and synchronized instantly, you can set the values as follows passive_data_insert_interval_in_seconds=12 data_split_interval_in_millis=30000 run the starter mobile and wearable app after configuring the local properties of both starter apps, build and run your app in android studio by following these steps run the starter mobile app select your mobile app starter-mobile-app from the run configurations menu in the toolbar choose a connected galaxy mobile device as the target device for running the app click run to install the app after installation, clear the app's data run the starter mobile app follow the same steps as for the starter mobile app but select starter-wearable-app instead choose a connected galaxy watch device for running the app allow the app to access physical activity, sensor data, and send notifications when prompted ensure that the galaxy watch is connected with the galaxy mobile device register and join a study since you have set super-tokens as the authentication method, you can now register and log into the app at once open the starter mobile app and sign up with an unregistered email address after logging in and accepting permissions, the app displays the study you created from the web portal tap on the study card to view its details and click join study noteif a study is set to private and you wish to join it, press enter the study code located at the top of the screen and input the assigned participation code in the study code field agree to data collection and terms of research you can see that the sensor data to be collected are dependent upon the selection made in the web portal while creating the study sign and click next to complete the study onboarding process measure and collect health data in the starter wearable app, you can see a list of on-demand measurements that you can contribute to health research for this code lab, choose ecg and click measure follow the onscreen measurement instruction after measuring successfully, scroll to the bottom of the wearable app and press the sync button to synchronize the data with the mobile app in the mobile app, go to data tab, click the more button, and click sync to transfer the collected data to the web portal visualize the collected data in web portal you can display the collected data as a graph in any way you choose for further analysis of the study from the overview page of the study in the web portal, navigate to the dashboard page click on the add chart button provide a title for the chart and select the desired chart type then, edit the chart source choose the database where the data is stored for this code lab, enter the following query to display only the first ten heart rate data from wearheartrate table select * from wearheartrate limit 10 click run query and save select value and timestamp for the value and category columns respectively check the preview of the graph finally, click save to display the graph into the dashboard you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create your own health research system by yourself! to learn more, see samsung health research stack
Learn Code Lab
codelabtransfer heart rate data from galaxy watch to a mobile device objective create a health app for galaxy watch, operating on wear os powered by samsung, to measure heart rate and inter-beat interval ibi , send data to a paired android phone, and create an android application for receiving data sent from a paired galaxy watch overview with this code lab, you can measure various health data using samsung health sensor sdk and send it to a paired android mobile device for further processing samsung health sensor sdk tracks various health data, but it cannot save or send collected results meanwhile, wearable data layer allows you to synchronize data from your galaxy watch to an android mobile device using a paired mobile device allows the data to be more organized by taking advantage of a bigger screen and better performance see samsung health sensor sdk descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android mobile device android studio latest version recommended java se development kit jdk 17 or later sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! heart rate data transfer sample code 218 3 kb connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that the wi-fi is enabled from the list of available wi-fi networks, choose and connect to the same one as your pc turn on developer mode and adjust its settings on your watch, go to settings > about watch > software and tap on software version 5 times upon successful activation of developer mode, a toast message displays as on the image below afterwards, developer options is going to be visible under settings tap developer options and enable the following options adb debugging in developer options find wireless debugging turn on wireless debugging check always allow on this network and tap allow go back to developer options and click turn off automatic wi-fi notethere may be differences in settings depending on your one ui version connect your galaxy watch to android studio go to settings > developer options > wireless debugging and choose pair new device take note of the wi-fi pairing code, ip address & port in android studio, go to terminal and type adb pair <ip address> <port> <wi-fi pairing code> when prompted, tap always allow from this computer to allow debugging after successfully pairing, type adb connect <ip address of your watch> <port> upon successful connection, you can see the following message in the terminal connected to <ip address of your watch> now, you can run the app directly on your watch turn on developer mode for health platform swipe down from the top of the screen to open the quick panel, then tap the settings icon scroll down and tap apps select health platform quckly tap health platform for about 10 times developer mode is enabled when [dev mode] appears below health platform noteyou can disable developer mode by quickly tapping the health platform until [dev mode] disappears set up your android device click on the following links to setup your android device enable developer options run apps on a hardware device connect the galaxy watch with you samsung mobile phone start your project in android studio, click open to open an existing project locate the downloaded android project hrdatatransfer-code-lab from the directory and click ok you should see both devices and applications available in android studio as in the screenshots below initiate heart rate tracking noteyou may refer to this blog post for more detailed analysis of the heart rate tracking using samsung health sensor sdk first, you need to connect to the healthtrackingservice to do that create connectionlistener, create healthtrackingservice object by invoking healthtrackingservice connectionlistener, context invoke healthtrackingservice connectservice when connected to the health tracking service, check the tracking capability the available trackers may vary depending on samsung health sensor sdk, health platform versions or watch hardware version use the gettrackingcapability function of the healthtrackingservice object obtain heart rate tracker object using the function healthtrackingservice gethealthtracker healthtrackertype heart_rate_continuous define event listener healthtracker trackereventlistener, where the heart rate values are collected start tracking the tracker starts collecting heart rate data when healthtracker seteventlistener updatelistener is invoked, using the event listener collect heart data from the watch the updatelistener collects datapoint instances from the watch, which contains a collection of valuekey objects those objects contain heart rate, ibi values, and ibi statuses there's always one value for heart rate while the number of ibi values vary from 0-4 both ibi value and ibi status lists have the same size go to wear > java > data > com samsung health hrdatatransfer > data under ibidataparsing kt, provide the implementation for the function below /******************************************************************************* * [practice 1] get list of valid inter-beat interval values from a datapoint * - return arraylist<int> of valid ibi values validibilist * - if no ibi value is valid, return an empty arraylist * * var ibivalues is a list representing ibivalues up to 4 * var ibistatuses is a list of their statuses has the same size as ibivalues ------------------------------------------------------------------------------- * - hints * use local function isibivalid status, value to check validity of ibi * ****************************************************************************/ fun getvalidibilist datapoint datapoint arraylist<int> { val ibivalues = datapoint getvalue valuekey heartrateset ibi_list val ibistatuses = datapoint getvalue valuekey heartrateset ibi_status_list val validibilist = arraylist<int> //todo 1 return validibilist } check data sending capabilities for the watch once the heart rate tracker can collect data, set up the wearable data layer so it can send data to a paired android mobile device wearable data layer api provides data synchronization between wear os and android devices noteto know more about wearable data layer api, go here to determine if a remote mobile device is available, the wearable data layer api uses concept of capabilities not to be confused with samsung health sensor sdk’s tracking capabilities, providing information about available tracker types using the wearable data layer's capabilityclient, you can get information about nodes remote devices being able to consume messages from the watch go to wear > java > com samsung health hrdatatransfer > data in capabilityrepositoryimpl kt, and fill in the function below the purpose of this part is to filter all capabilities represented by allcapabilities argument by capability argument and return the set of nodes set<node> having this capability later on, we need those nodes to send the message to them /************************************************************************************** * [practice 2] check capabilities for reachable remote nodes devices * - return a set of node objects out of all capabilities represented by 2nd function * argument, having the capability represented by 1st function argument * - return empty set if no node has the capability -------------------------------------------------------------------------------------- * - hints * you might want to use filtervalues function on the given allcapabilities map * ***********************************************************************************/ override suspend fun getnodesforcapability capability string, allcapabilities map<node, set<string>> set<node> { //todo 2 } encode message for the watch before sending the results of the heart rate and ibi to the paired mobile device, you need to encode the message into a string for sending data to the paired mobile device we are using wearable data layer api’s messageclient object and its function sendmessage string nodeid, string path, byte[] message go to wear > java > com samsung health hrdatatransfer > domain in sendmessageusecase kt, fill in the function below and use json format to encode the list of results arraylist<trackeddata> into a string /*********************************************************************** * [practice 3] - encode heart rate & inter-beat interval into string * - encode function argument trackeddata into json format * - return the encoded string ----------------------------------------------------------------------- * - hint * use json encodetostring function **********************************************************************/ fun encodemessage trackeddata arraylist<trackeddata> string { //todo 3 } notetrackeddata is an object, containing data received from heart rate tracker’s single datapoint object @serializable data class trackeddata var hr int, var ibi arraylist<int> = arraylist run unit tests for your convenience, you can find an additional unit tests package this lets you verify your code changes even without using a physical watch or mobile device see the instruction below on how to run unit tests right-click on com samsung health hrdatatransfer test , and execute run 'tests in 'com samsung health hrdatatransfer" command if you have completed all the tasks correctly, you can see all the unit tests pass successfully run the app after building the apks, you can run the applications on your watch to measure heart rate and ibi values, and on your mobile device to collect the data from your watch once the app starts, allow the app to receive data from the body sensors afterwards, it shows the application's main screen to get the heart rate and ibi values, tap the start button tap the send button to send the data to your mobile device notethe watch keeps last ~40 values of heart rate and ibi you’re done! congratulations! you have successfully achieved the goal of this code lab now, you can create a health app on a watch to measure heart rate and ibi, and develop a mobile app that receives that health data! if you face any trouble, you may download this file heart rate data transfer complete code 217 8 kb to learn more about samsung health, visit developer samsung com/health
Develop Health
apisamsung health data sdk/com samsung android sdk health data request/datatype/heartratetype heartratetype class heartratetype datatype, datatype readable<healthdatapoint, readdatarequest dualtimebuilder<healthdatapoint>> , datatype changereadable<healthdatapoint> , datatype writeable<healthdatapoint> the data type representing heart rate data specifications continuous heart rate data from galaxy wearable devices such as galaxy watch, galaxy fit, and galaxy ring can be recorded in this data type the samsung health application's settings provide a heart rate measurement option if the user selects the option with 'measure continuously' or 'every 10 mins', the galaxy wearable device will measure the user's heart rate accordingly the measured data is then synchronized to the smartphone with heartratetype data continuous heart rate details are stored in heartratetype series_data predefined instanceusing the following instance allows for obtaining heart rate data with more concise code datatypes heart_rate available aggregate operationsmin to get the minimum heart rate value within the received heart rate data for a data request max to get the maximum heart rate value within the received heart rate data for a data request required permissionthe user's consent is required to access this data type check the granted permissions and request permissions if the required permission is not granted yet with healthdatastore getgrantedpermissionshealthdatastore requestpermissionssee a code example in here available requestshealthdatastore readdatahealthdatastore readdataasynchealthdatastore aggregatedatahealthdatastore aggregatedataasynchealthdatastore readchangeshealthdatastore readchangesasynchealthdatastore insertdatahealthdatastore insertdataasynchealthdatastore updatedatahealthdatastore updatedataasynchealthdatastore deletedatahealthdatastore deletedataasync data specificationsthis data type includes the following information propertydescriptionuid[mandatory] the data's unique identifier assigned by the samsung health starttime[mandatory] the timestamp representing the start of measurement, specified as instant, in milliseconds endtime[mandatory] the timestamp representing the end of measurement, specified as instant, in milliseconds zoneoffset[mandatory] the zoneoffset for starttime and endtimedatasource[mandatory] the data's source information including the application package name and which device's id heart_rate[mandatory] the heart rate value in beats per minute series_datathe details regarding continuous heart rate it is presented as the list of heartrate min_heart_ratethe lowest heart rate value, in beats per minute max_heart_ratethe highest heart rate value, in beats per minute since1 0 0 members types companion link copied to clipboard object companion properties changeddatarequestbuilder link copied to clipboard open override val changeddatarequestbuilder changeddatarequest basicbuilder<healthdatapoint>retrieves a changeddatarequest instance to retrieve changed heart rate data deletedatarequestbuilder link copied to clipboard open override val deletedatarequestbuilder deletedatarequest basicbuilderretrieves a deletedatarequest instance to delete heart rate data that the application inserted into the samsung health insertdatarequestbuilder link copied to clipboard open override val insertdatarequestbuilder insertdatarequest basicbuilder<healthdatapoint>retrieves an insertdatarequest instance to insert new heart rate data to the samsung health readdatarequestbuilder link copied to clipboard open override val readdatarequestbuilder readdatarequest dualtimebuilder<healthdatapoint>retrieves a readdatarequest instance to read heart rate data updatedatarequestbuilder link copied to clipboard open override val updatedatarequestbuilder updatedatarequest basicbuilder<healthdatapoint>retrieves an updatedatarequest instance to update heart rate data that the application inserted into the samsung health
Develop Health
docfaq what are the benefits of the samsung health research stack? samsung health research stack provides end-to-end solutions for collecting and analyzing data from wearable devices in android and wear os environments and allows developers to design advanced health and wellness applications developers can also build research study portal which acts as a centralized hub for managing every facet of research studies, from enrollment to compliance how do i get access to the samsung health research stack? you can learn about accessing samsung health research stack here here what devices are compatible with samsung health research stack? the galaxy watch 5 and later has been tested for compatibility with this tech stack is it possible to contribute to samsung health research stack? yes, as an open-source project, samsung health research stack welcomes contributions from the developer community if you'd like to contribute, check out contributing to the open source project here how can i modify the ui on the starter-app? you can customize the ui by modifying the presentation package classes in starter mobile/wearable app specifically, you can edit the files in starter-mobile-app/src/main/kotlin/researchstack/presentation/ for theme or color changes, update the theme/appcolors kt file are the screens and flows for the mobile app available in android studio? yes, the screens and flows for the mobile app are available in android studio, and they are not configured in the container and backend how does data synchronization work in the app? the app uses android workmanager for periodic data sync once the user permits the use of their health data and finishes logging in, workmanager is initialized and periodically syncs health data from healthconnect to the backend, even when the app is not open what is the minimum interval for data sync, and can it be manually triggered? the least interval that can be set for data sync is 15 minutes workmanager cannot be manually triggered; it operates based on the configuration is it expected for data to only be pushed when the app is engaged? no, once workmanager is initialized, it syncs data periodically even when the app is not engaged various sequences of opening and closing the researchsample app and samsung health may trigger data transfer, but workmanager operates independently based on the configuration how do i modify the ui of the web portal? you might need to change ui materials before building the container please, contact our support to get a more precise answer how can i capture more types of health data from samsung health? there are two steps specify the app’s permissions for health connect in the health_permissions xml file, and add healthdatasyncspecs to mainactivity kt the healthconnectadapter currently supports 11 types of health data alternatively, you could utilize samsung health sdks what should i do if the account verification email is not sent when creating a web portal account? ensure that smtp access is activated on the account and that outbound calls on the corresponding smtp port are allowed from your server if using 2-factor authentication 2fa , try signing in with an app password if not, you might need to allow less secure apps to access your account what could cause authentication issues when sending emails from the account service? if you are using 2-factor authentication 2fa , try signing in with an app password if it does not work, you might need to allow less secure apps to access your account where can i find logs or monitor the workmanager for debugging? you can briefly monitor the workmanager in the "app inspection" tab in android studio how can i monitor and troubleshoot workmanager for data synchronization? you can monitor workmanager in the "app inspection" tab in android studio this can help you check if data sync is happening as expected and identify any issues how can i change the configuration for data synchronization? the data synchronization process is handled by workmanager, and the interval for data sync is set in the configuration you can modify this configuration according to your needs, but the minimum interval that can be set is 15 minutes missing google-services json file in the source code if you want to use firebase to provide a 3rd party login to users the google-services json file must be included in the source code a reference to integrate it can be found here need guidance on backend installation for the app the app fetches project information such as surveys and activity tasks from the backend for testing, it's recommended to follow the backend installation guide instead of integrating your own backend system detailed instructions can be found here how to capture and export accelerometry continuously, not just during the activity task? the app regularly sends health data logged by health connect at intervals that can be set by the user for sensor data related to each activity task, it's collected & synced when the activity is conducted specific activity tasks and their associated sensor types are provided what data types from health connect can be utilized? the app can utilize all data types supported by health connect by modifying the list of healthdatarequired, you can adjust the app to collect additional data types recorded by health connect however, to have data input, that data needs to exist in health connect resolution to /gradlew clean failing for app-sdk? this appears to be an issue with the system failing to communicate with the gradle plugin repository ensure that your system is online, and if you're using a proxy environment, check proxy settings if a proxy is in use, the issue might be an ssl handshake failure check ssl settings and proxy configurations
tutorials galaxy watch, mobile
bloggalaxy watch apps can offer a range of features and services, but the watch's smaller size compared to a mobile device means there are limitations, including fewer hardware resources and a smaller screen. to make the most of the capabilities of a mobile device, you can develop a companion mobile application for the wearable application. the companion application handles complex and resource-intensive tasks while the wearable application provides a seamless experience. previously in this series, we showed how to create a companion mobile application for a galaxy watch running wear os powered by samsung and use the wearable data layer api to send messages from the watch to the mobile device. while it is easy to check the watch's battery level from the mobile device, the reverse is more complex. this tutorial describes how to establish two-way communication between the wearable and mobile applications and use it to check the mobile device's battery level from the watch. prerequisites to develop a wearable application and its companion mobile application, create a multi-module project in android studio. the steps are described in the previous tutorial, and the same dependencies and modifications are required for the wearable application in this tutorial: add the following dependencies to the build.gradle filedependencies { ... implementation "com.google.android.gms:play-services-wearable:xx.x.x" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x" implementation "androidx.lifecycle:lifecycle-extensions:x.x.x" implementation "androidx.lifecycle:lifecycle-runtime-ktx:x.x.x" implementation "androidx.appcompat:appcompat:x.x.x" } modify the mainactivity class to inherit appcompatactivity() instead of activity(). in the "androidmanifest.xml" file, in the <application> element, change the android:theme attribute value to "@style/theme.appcompat.noactionbar" or another custom theme. warningthe package ids of the wearable and mobile applications must be identical. to test the project, you need a galaxy watch running wear os powered by samsung and a connected galaxy mobile device. request battery information from the companion application to be able to retrieve the mobile device's battery level as a percentage from the watch, the companion application on the mobile device must advertise the "battery_percentage" capability. in the mobile application, create an xml file named "wear.xml" in the "res/values/" directory with the following content: <!--xml configuration file--> <?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@array/android_wear_capabilities"> <string-array name="android_wear_capabilities"> <item>battery_percentage</item> </string-array> </resources> while a watch can be connected to only one device at a time, a mobile device can be connected to multiple wearables at the same time. to determine which node (connected device) corresponds to the watch, use the capabilityclient class of the wearable data layer api to retrieve all the available nodes and select the best or closest node to deliver your message. // mainactivity class in the wearable application private var batterynodeid: string? = null private fun setupbatterypercentage() { // store the reachable nodes val capabilityinfo: capabilityinfo = tasks.await( wearable.getcapabilityclient(applicationcontext) // retrieve all connected nodes with the 'battery_percentage' capability .getcapability( battery_percentage_capability_name, capabilityclient.filter_reachable ) ) // use a listener to retrieve the reachable nodes updatebatterycapability(capabilityinfo).also { capabilitylistener -> wearable.getcapabilityclient(this @mainactivity).addlistener( capabilitylistener, battery_percentage_capability_name ) } } private fun pickbestnodeid(nodes: set<node>): string? { // find the best node return nodes.firstornull { it.isnearby }?.id ?: nodes.firstornull()?.id } private fun updatebatterycapability(capabilityinfo: capabilityinfo) { // specify the recipient node for the message batterynodeid = pickbestnodeid(capabilityinfo.nodes) } companion object{ private const val tag = "mainwearactivity" private const val battery_percentage_capability_name = "battery_percentage" private const val battery_message_path = "/message_battery" } to implement bi-directional communication between watch and mobile device, you can use the messageclient class of the wearable data layer api. in the wearable application ui, create a button and a textview. to display the mobile device's battery level on the textview when the button is tapped, implement the button's onclicklistener() function. send the battery level request message through a specific message path to the mobile device, using a coroutine that calls the setupbatterypercentage() and requestbatterypercentage() methods on a separate thread. a separate thread must be used because these are synchronous calls that block the ui thread. // mainactivity class in the wearable application private lateinit var binding: activitymainbinding override fun oncreate(savedinstancestate: bundle?) { super.oncreate(savedinstancestate) binding = activitymainbinding.inflate(layoutinflater) setcontentview(binding.root) log.d(tag, "oncreate()") binding.apply{ phonebutton.setonclicklistener{ lifecyclescope.launch(dispatchers.io){ setupbatterypercentage() requestbatterypercentage("battery".tobytearray()) } } } } // deliver the message to the selected node private fun requestbatterypercentage(data: bytearray) { batterynodeid?.also { nodeid -> val sendtask: task<*> = wearable.getmessageclient(this @mainactivity).sendmessage( nodeid, battery_message_path, data ).apply { addonsuccesslistener { log.d(tag, "onsuccess") } addonfailurelistener { log.d(tag, "onfailure") } } } } receive the message on the companion application the companion application must be able to receive and respond to the message from the background. to accomplish this, implement a service that listens for incoming messages. in the mobile application, create a class that extends wearablelistenerservice() and add the service to the application manifest file: <!--android manifest file for the mobile application--> <service android:name=".phonelistenerservice" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.google.android.gms.wearable.message_received" /> <data android:host="*" android:pathprefix="/" android:scheme="wear" /> </intent-filter> </service> use the batterymanager class to retrieve the current battery level of the device. to send the retrieved value back to the wearable application, use the sendmessage() function again. for simplicity, send the message to the first connected node on the mobile device. alternatively, you can broadcast to all connected nodes. implement the onmessagereceived() function to receive the incoming request for battery level and send the retrieved value to the wearable application. // service class in the mobile application private val scope = coroutinescope(supervisorjob() + dispatchers.main.immediate) private var batterynodeid: string? = null override fun ondestroy() { scope.cancel() super.ondestroy() } override fun onmessagereceived(messageevent: messageevent) { log.d(tag, "onmessagereceived(): $messageevent") log.d(tag, string(messageevent.data)) if (messageevent.path == battery_message_path && string(messageevent.data) == "battery") { // check that the request and path are correct val batterymanager = applicationcontext.getsystemservice(battery_service) as batterymanager val batteryvalue:int = batterymanager.getintproperty(batterymanager.battery_property_capacity) scope.launch(dispatchers.io){ // send the message to the first node batterynodeid = getnodes().first()?.also { nodeid-> val sendtask: task<*> = wearable.getmessageclient(applicationcontext).sendmessage( nodeid, battery_message_path, batteryvalue.tostring().tobytearray() ).apply { addonsuccesslistener { log.d(tag, "onsuccess") } addonfailurelistener { log.d(tag, "onfailure") } } } } } ondestroy() } private fun getnodes(): collection<string> { return tasks.await(wearable.getnodeclient(this).connectednodes).map { it.id } } companion object{ private const val tag = "phonelistenerservice" private const val battery_message_path = "/message_battery" } display the battery information on the wearable application when receiving the battery information on the wearable application, because the user is actively interacting with the application, a resource-intensive service is not needed and registering a live listener is sufficient. use the addlistener() method of the messageclient class to implement the messageclient.onmessagereceivedlistener interface within the mainactivity class in the wearable application. // mainactivity class in the wearable application override fun onresume(){ super.onresume() log.d(tag, "onresume()") // wearable api clients are not resource-intensive wearable.getmessageclient(this).addlistener(this) } override fun onpause(){ super.onpause() log.d(tag, "onpause()") wearable.getmessageclient(this).removelistener(this) } override fun onmessagereceived(messageevent: messageevent) { // receive the message and display it if(messageevent.path == battery_message_path){ log.d(tag, "mobile battery percentage: " + string(messageevent.data) + "%") binding.phonetextview.text = string(messageevent.data) } } conclusion to test the project, build both applications and run them on your galaxy watch and mobile device. when you tap the ui button on the watch, the application retrieves the battery level from the mobile device and displays the percentage on the watch. this demonstration has shown how the wearable data layer api enables you to implement seamless bi-directional communication between a galaxy watch running wear os powered by samsung and its connected mobile device. in addition to battery level, you can use the capabilityclient and messageclient classes to transfer various data between the devices in a similar way. for more information about implementing communication between watch and mobile devices, see send and receive messages on wear. if you have questions about or need help with the information in this tutorial, you can share your queries on the samsung developers forum. for more specialized support, you can contact us through samsung developer support. stay tuned for the next installment in this tutorial series.
Samiul Hossain
Develop Smart TV
apitizenfx api references the tizenfx api allows applications to call in platform-specific functionality from shared code it enables you to implement native features in xamarin forms applications the following table lists the tizenfx api modules and their smart tv and tv emulator support namespace assembly support tv emulator elmsharp provides pre-built ui components for creating a rich gui elmsharp dll yes yes elmsharp accessible provides ui information for the screen reader elmsharp wearable provides pre-built ui components for creating a rich wearable device gui elmsharp wearable dll no no tizen provides the tizen logging and trace messaging functionalities tizen log dll yes yes tizen tracer dll tizen account accountmanager provides crud create, read, update, delete account management functionality tizen account accountmanager dll no no tizen account fidoclient provides user authentication functionality using the fido uaf protocol tizen account fidoclient dll tizen account oauth 2 provides account management functionality using the oauth2 rfc 6749 protocol tizen account oauth2 dll tizen account syncmanager manages account synchronization operations tizen account syncmanager dll tizen applications provides the tizen application framework tizen applications alarm dll yes yes tizen applications badge dll no no tizen applications common dll yes yes tizen applications packagemanager dll tizen applications preference dll tizen applications remoteview dll tizen applications service dll tizen applications toastmessage dll tizen applications ui dll tizen applications watchapplication dll no no tizen applications widgetapplication dll yes yes tizen applications widgetcontrol dll tizen applications attachpanel provides the attach panel functionality tizen applications attachpanel dll no no tizen applications corebackend provides the application backend life-cycle, including state change events tizen applications common dll yes yes tizen applications watchapplication dll no no tizen applications datacontrol provides a standard mechanism for exchanging specific data between applications tizen applications datacontrol dll yes yes tizen applications exceptions provides exception messages tizen applications common dll tizen applications messages sends and receives messages between applications tizen applications messageport dll tizen applications notificationeventlistener manages notification events tizen applications notificationeventlistener dll tizen applications notifications displays messages in the notification area tizen applications notification dll tizen applications shortcut manages application shortcuts tizen applications shortcut dll no no tizen common provides predefined color names tizen dll yes yes tizen content download manages downloading content from the web tizen content download dll tizen content mediacontent stores and indexes audio, image, and video content tizen content mediacontent dll tizen content mimetype associates file extensions with mime types tizen content mimetype dll tizen context apphistory accesses the user's application history tizen context dll no no tizen internals errors provides error messages tizen dll yes yes tizen location manages geographical location services tizen location dll no no tizen location geofence provides the geofence functionality tizen location geofence dll tizen maps enables creating map-aware applications tizen maps dll yes yes tizen messaging email enables sending email tizen messaging dll no no tizen messaging messages enables sending and receiving various messages, such as sms, mms, and cell broadcast messages tizen messaging push enables receiving push notifications tizen messaging push dll no no tizen multimedia interacts with media services, including playback and recording, and device policy tizen multimedia audioio dll yes yes tizen multimedia camera dll no no tizen multimedia dll yes yes tizen multimedia mediaplayer dll tizen multimedia metadata dll tizen multimedia radio dll no no tizen multimedia recorder dll tizen multimedia streamrecorder dll tizen multimedia mediacodec encodes and decodes video and audio data tizen multimedia mediacodec dll tizen multimedia remoting provides the media controller and screen mirroring functionalities tizen multimedia remoting dll tizen multimedia util processes image files, such as resizing, rotating, cropping, and encoding and decoding them tizen multimedia util dll yes yes tizen multimedia vision provides visual detection and recognition functionalities, such as face detection and barcode recognition tizen multimedia vision dll no no tizen network bluetooth provides bluetooth functionalities tizen network bluetooth dll yes partially no tizen network connection manages various network connection information tizen network connection dll yes yes tizen network iotconnectivity provides iot connectivity functionality tizen network iotconnectivity dll tizen network nfc provides near-field communication nfc functionality tizen network nfc dll no no tizen network nsd manages network service discovery tizen network nsd dll yes yes tizen network smartcard provides smart card functionality tizen network smartcard dll no no tizen network wifi manages wi-fi devices and access points tizen network wifi dll yes tizen network wifidirect manages wi-fi direct® connections and settings tizen network wifidirect dll no tizen nui provides the natural user interface nui toolkit for creating a rich gui tizen nui dll yes yes tizen nui basecomponents provides the nui base components tizen nui constants provides various constants for nui component properties tizen phonenumberutils parses and formats phone numbers tizen phonenumberutils dll no no tizen pims calendar provides calendar services tizen pims calendar dll yes yes tizen pims calendar calendarviews provides calendar view properties tizen pims contacts provides contact information services tizen pims contacts dll no no tizen pims contacts contactsviews provides contact information view properties tizen security manages permissions for privacy-related privileges tizen security dll yes yes tizen security privacyprivilegemanager dll tizen security securerepository provides a secure repository for keys, certificates, and other sensitive data tizen security securerepository dll tizen security securerepository crypto provides secure cryptographic operations tizen security teec enables secure communication with applications within a trusted execution environment tee tizen security teec dll tizen sensor accesses device sensors and sensor information tizen sensor dll no no tizen system provides device-specific services, including device status, system information and settings, haptic feedback, and sensor control tizen system dll yes yes tizen system feedback dll tizen system information dll tizen system mediakey dll tizen system storage dll tizen system systemsettings dll tizen system usb manages attached usb devices tizen system usb dll no no tizen telephony provides telephony functionality tizen telephony dll tizen uix inputmethod enables the user to enter text tizen uix inputmethod dll yes yes tizen uix inputmethodmanager manages the installed input method editors tizen uix inputmethodmanager dll tizen uix stt enables speech recognition tizen uix stt dll no tizen uix sttengine provides the speech-to-text stt engine tizen uix sttengine dll tizen uix tts enables speech synthesis tizen uix tts dll yes tizen uix ttsengine provides the text-to-speech tts engine tizen uix ttsengine dll tizen uix voicecontrol enables voice control tizen uix voicecontrol dll no tizen webview accesses web pages and web content tizen webview dll yes table 1 tizenfx api module support
tutorials galaxy watch
blogsome features on galaxy watch running wear os powered by samsung function only when the watch is being worn on the user’s wrist. notifications are an important example of one such feature. when the watch is not being worn, phone notifications are not synchronized to the watch and local notifications generated on the watch are muted. off-body detection enables you to determine if the user is wearing the watch. to enable this, the watch contains a low latency off-body sensor. the data from this sensor allows you to enhance your application by implementing it to, for example, send or avoid notifications or to show or hide sensitive information, as appropriate. this tutorial demonstrates how to detect if the watch is being worn, and a sample application is provided so you can examine how the code works in practice. the tutorial also describes how you can override the off-body sensor for testing purposes. implementing off-body detection for galaxy watch to access the low latency off-body sensor data on a galaxy watch running wear os powered by samsung, the sensormanager library provides the type_low_latency_offbody_detect key, which enables you to check if the watch is being worn. to detect if the watch is being worn: in android studio, to create a wearable application project, select "new project > wear os > blank activity > finish." because the low latency off-body sensor is a body sensor, in the application manifest file, define the required permission to use the body sensors: <uses-permission android:name="android.permission.body_sensors" /> for android 6 (api level 23) and higher, to access sensor-related information, the application must obtain permission from the user. in the application code, check that the user has granted access to sensor data: if (checkselfpermission(manifest.permission.body_sensors) != packagemanager.permission_granted) { requestpermissions( new string[]{manifest.permission.body_sensors}, 1); } else { log.d(tag, "already granted"); } if the user has not yet granted permission to access sensor data, they are prompted to do so. your application can extract sensor information only if the user selects "allow." if they select "deny," the application cannot access any information from the sensor. for more information about runtime permissions, see request permissions. in the application code, create an instance of the sensormanager class: msensormanager = (sensormanager) getsystemservice(getapplicationcontext().sensor_service); implement the low latency off-body sensor: offbodysensor = msensormanager.getdefaultsensor(sensor.type_low_latency_offbody_detect); to implement an event listener to notify when the sensor value changes, override onsensorchanged(): float offbodydatafloat = sensorevent.values[0]; int offbodydata = math.>round(offbodydatafloat); if (offbodydata == 0) { mtextview.settext("the watch is not being worn!"); mtextview.settextcolor(color.parsecolor("#ff0000")); } else { mtextview.settext("the watch is being worn!"); mtextview.settextcolor(color.parsecolor("#76ba1b")); } when the offbodydata value is 1, the watch is on the user’s wrist. otherwise, its value is 0, which means the watch is not being worn. to activate the listener when the application is running, register it by overriding the onresume() method: msensormanager.registerlistener(mainactivity.this, offbodysensor, sensormanager.sensor_delay_normal); alternatively, you can implement registering the listener through a button in the application ui. when the listener is no longer needed, unregister it by overriding the onpause() method: msensormanager.unregisterlistener(this); alternatively, you can implement unregistering the listener within the onpause() method, or through a button in the application ui. sample application to see for yourself how the off-body sensor works, download the following sample application that supports galaxy watch4 or higher. offbodysensorexample (242kb) jun. 14, 2023 extract the application files and open the "offbodysensorexample/build.gradle" file in android studio. to run the sample application on a galaxy watch4 or higher, enable usb debugging mode on the watch. connect the watch to your computer and run the application through android studio. when you have granted the application permission to access the watch’s sensor data, tap the "check" button to check if the watch is currently being worn. figure 1: sample application manually overriding the off-body sensor for testing during application development, it can be inconvenient to wear the watch while testing. for testing purposes, you can manually override the off-body sensor: connect the watch to your computer. in the adb shell, to override the off-body sensor manually: wearing the watch $ adb shell am broadcast -a com.samsung.android.hardware.sensormanager.service.offbody_detector --ei force_set 1 not wearing the watch $ adb shell am broadcast -a com.samsung.android.hardware.sensormanager.service.offbody_detector --ei force_set 2 when the command is successful, you see a message similar to "broadcast completed: result=0." to receive notifications, make sure the watch is not in charging mode: a. to simulate disconnecting the charger, use the following adb command: dumpsys battery unplug b. to re-enable detecting the watch’s charging state normally: dumpsys battery reset disconnect the watch from your computer and test your application. after testing, return the watch to its default state. to disable the sensor override, use the following adb command: $ adb shell am broadcast -a com.samsung.android.hardware.sensormanager.service.offbody_detector --ei force_set 0 summary various galaxy watch features, such as notifications, work only when the user is wearing the watch. the low latency off-body sensor enables you to implement application features that react to if the watch is being worn. to ease application development, you can override the sensor so the watch does not need to be physically worn during testing. if you have questions about or need help with the information in this tutorial, you can contact samsung developer support.
Shamima Nasrin
Develop Health
docnotesamsung health sdk for android partners, please migrate to samsung health data sdk to access additional health data types and continue to utilize existing data types supported via samsung health sdk for android samsung health sdk for android has been deprecated please find instructions to migrate to samsung health data sdk migration 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 will be deprecated in few months 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 development process previously samsung health sdk for android required developers to submit requires a partner request to get access 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 the convenience of more developers, the samsung health data sdk has improved its developer mode functionality if you only need to read the samsung health app's data, you can activate the developer mode and proceed with development and testing without requiring the partner request if you want to test writing data to the samsung health app using the samsung health data sdk or to distribute your app, you need to submit a partner request registration is necessary if you want to see the detailed process for developing an app with the samsung health data sdk can be found on, please refer to the process page 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 the samsung health sdk for android sdk corresponding data type in the 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 note when 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 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 app manifest - remove the element for samsung health sdk for android <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 app manifest - remove the data permission declarations for samsung health sdk for android <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> 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 the 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 only for development purposes to ensure that an app that`s 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 market places after partner app approval, 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 //for females, age 19 - 50, according to https //nap nationalacademies org/catalog/11537/dietary-reference-intakes-the-essential-guide-to-nutrient-requirements val referenceindexforironinmilligrams = 8 1f // for age 19-50, refer to the link above 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 } } 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 https //developer samsung com/dev-support and submit your query after logging in your samsung account
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.
These cookies gather information about your browser habits. They remember that you've visited our website and share this information with other organizations such as advertisers.
You have successfully updated your cookie preferences.