Measure and Transfer Heart Rate Data from Galaxy Watch to a Paired Android Phone
the samsung privileged health 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 2 connected sample applications. a watch application uses the samsung privileged health 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 2 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(trackingtype) 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 on-demand heart rate tracking, the update listener is invoked every second and each data point list contains 1 element. 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. since samsung privileged health sdk version 1.2.0, 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 privileged health 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