Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Mobile/Wearable
Visual Display
Digital Appliance
Platform
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, explore 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, explore samsung health sensor sdk
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
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 app'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 permission for a code example available operationshealthdatastore readdatahealthdatastore readdataasynchealthdatastore aggregatedatahealthdatastore aggregatedataasynchealthdatastore readchangeshealthdatastore readchangesasynchealthdatastore insertdatahealthdatastore insertdataasynchealthdatastore updatedatahealthdatastore updatedataasynchealthdatastore deletedatahealthdatastore deletedataasync data specificationsthis data type includes the following properties propertydescriptionuid[mandatory] the data's unique identifier assigned by 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 the device id heart_rate[mandatory] the heart rate value in beats per minute series_datathe details regarding continuous heart rate it is represented 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
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 Samsung Wallet
docmanage wallet card the samsung wallet partners portal provides partners with the necessary tools and functionality to integrate the “add to samsung wallet” feature into their services this guide outlines the process of registering, managing wallet cards, and ensuring that everything runs smoothly refer to the partner onboarding guide for the samsung wallet portal the partners need to complete the following steps to register and gain access to the samsung wallet portal note-wallet portal currently offers 'add to samsung wallet' functionality to the partners overall managing process once registered and logged into the samsung wallet portal, partners can follow the steps to manage wallet cards and monitor performance step 1 - create wallet card template begin by drafting the cards that will be added to samsung wallet these cards can include loyalty cards, tickets, boarding passes, and more draft status - initially, these cards will be in draft status until they are fully configured and ready for testing manage wallet card partners can manage all registered wallet cards this includes edit, update, and monitor the status of the wallet cards general information the general information page allows the partner to enter administrative details to manage their cards, as well as to define common parameters for the wallet folder contents testing mode all data generated in testing mode is periodically deleted be sure to turn off the "testing mode" setting after the test is over wallet card name representative title of the wallet card wallet card id unique wallet card domain name partner app package name partner application package name wallet card template pre-defined partner wallet card template partner get card data url for the partner api call to receive card data if the partner uses this api, enter the url otherwise leave it blank partner send card state url for the partner api call to send a card state notification if the partner uses this api, enter the url otherwise leave it blank samsung server ips samsung wallet server ips which need to be allowed by the partner’s firewall, separately described for inbound and outbound wearable wallet assistance whether to support the wearable wallet service support ‘no network’ status whether to support wallet card opening during the ‘no network’ status description description of the wallet card select card template the samsung wallet portal offers various wallet card templates optimized for different use cases, including boarding passes, tickets, coupons, and digital ids to streamline your integration, you can easily select the appropriate template from the select wallet card template pop-up window steps to select wallet card template navigate to the select wallet card template option within the portal in the wallet card type drop-down menu, select the category that best suits your use case e g , boarding pass, ticket, coupon, or digital id once the card type is selected, a list of templates will appear in the wallet card sub type section choose one of the available templates from the list that corresponds to your selected card type some card types support a flexible layout design after selecting the template, you can proceed with configuring the card’s details, including the branding, content, and data fields specific to the selected template samsung wallet supports various wallet card types designed to cater to different use cases each card type is optimized for specific functions, making it easier for partners to provide a seamless experience to users note-refer to section wallet card type to learn more about it view wallet card template partners can easily manage all their registered wallet cards through the samsung wallet portal this includes the ability to view, edit, and delete wallet cards as needed step 2 - launch wallet card template verifying status once a wallet card is ready for launch, it must go through the verifying status before it can be activated and made available to users partners can launch and activate their cards once they have been reviewed and approved, ensuring the card meets all requirements steps to launch card template to begin the launch process, click yes to confirm and approve the activation of the wallet card to begin the activation process, click the launch button for the card you wish to activate once a card is launched, the button text changes to launched the activation cannot be cancelled after the card is launched, its status will change to verifying during this stage, the system will conduct a final review to ensure all information is accurate and meets the necessary requirements after verification, the card will undergo administrator approval the admin will review and approve the card for activation once the card is approved by the administrator, its status will change to active, making it available for users to add to their samsung wallet launch wallet card template rejected status if the wallet card is rejected after launching, you can modify the card and re-launch steps to modify the card and re-launch the administrator registers the reason for rejection when rejecting the launched wallet card it is sent to the partner by email from the system, including the reason for rejection partners can apply for launch again by checking the reason for rejection and modifying the wallet card information step 3 – testing mode partners can use the testing mode to test a wallet card internally before it is officially released to users this feature ensures that all aspects of the card, including its functionality and user experience, are working as expected when you create a new wallet card, the testing mode option is enabled by default, allowing you to perform internal tests without affecting user access all data generated during testing is periodically deleted to ensure that no test data remains in the system once testing is complete even though testing mode is enabled, the card is still visible and accessible in the system testing does not prevent the card from being exposed to users, so you can verify its functionality without any restrictions once testing is complete and you are satisfied with the card’s performance, be sure to turn off testing mode note-remember to change the status from testing mode on to testing mode off to finalize the testing process and prepare the card for official release step 4 - admin approval active status after a wallet card is launched, it must go through an administrator approval process before it becomes active and visible to users steps for admin approval once the launch button is clicked, the card’s status automatically changes to verifying during this stage, the card is reviewed for accuracy, completeness, and compliance with samsung wallet requirements note-please ensure that testing is completed using either your own implementation or the add to wallet test tool, as the samsung wallet administrator will verify the results through server-side test logs an administrator will review the submitted wallet card to ensure it meets all content and technical guidelines if the card passes the review, it is approved for activation upon administrator approval, the card status updates 'active' once the card reaches active status, it becomes visible and accessible to end users, enabling them to add it to their wallets step 5 – add to samsung wallet integration to integrate the "add to samsung wallet" feature into your system, you need to insert the appropriate "add to wallet" script this script is available for various platforms, including web, android, and email/mms, and each platform requires a slightly different implementation approach follow the steps below to successfully implement the "add to wallet" button create the tokenized card data, known as cdata, which contains the actual wallet card content note-since cdata has a time-to-live ttl of 30 seconds, it is recommended that the system generates cdata in real time to ensure it remains valid when processed 2 the cdata format varies depending on the card type e g , loyalty card, ticket, coupon 3 refer to the [_cdata generation sample code_][cdata generation sample code] on the partners portal for detailed guidance 4 copy the sample **‘add to wallet’** script from [_partners portal’s wallet card_][partners portal’s wallet card] page 5 replace the placeholder "cdata" in the script with your generated tokenized card data 6 apply the script to your system see [_partners portal’s wallet card_][partners portal’s wallet card] for details note-for "add to wallet" integration, you may need some base data you can find that and other necessary information on partners portal and wallet api spec you can also add image beacon in the script for tracking effect analysis add to wallet script guide step 6 – merchant push notification partners can create a message template for sending pushes on each of their wallet cards type partners can only choose the merchant push type message type you can choose a message type from marketing or others rejected comment if the merchant push notification is rejected after request approval, you can modify the message template the administrator registers the reason for rejection when rejecting the merchant push notification it is sent to the partner by email from the system, including the reason for rejection partners can request for approval again by checking the reason for rejection and modifying the message template approved date displays the date and time when the push message is approved by the administrator message template you can create the contents of the push, and it is also possible to put the available variables in '{{}}' after configuring the content, click harmfulness verification to verify whether there is a harmful expression in the content the verified result is displayed as pass or fail, and if it is fail, it shows the filtered harmful expression together even if the verified result is fail, an approval request can be made, but it can be rejected by the administrator if a different language is added to the default language in general information, the message template must also be entered for each added language request approval button after completing the message template, click this button to send an e-mail requesting approval to the administrator configure the wallet card layout samsung wallet offers the flexibility to customize card layouts according to your preferences samsung wallet supports 2 different layout types while all cards can use the default layout type, the flexible layout type is only available for specific cards this section defines the design and attributes of the wallet cards to be supported through the flexible layout type supported card types with flexible layout the card types that support the flexible layout type are as follows loyalty membership , coupon, event ticket, generic card, boarding pass create a card with flexible layout when creating a wallet card that supports the flexible layout type, the user can choose between the default and flexible layouts when selecting the card type to create a wallet card with a flexible layout create a wallet card select the wallet card template to use select the type and sub type for the wallet card template selecting a card type that supports a flexible layout will display the available flexible layout identifiable by the name 'generic-subtypename-default' note-please choose carefully, as the layout type cannot be changed once the card is activated card design and attribute configuration step 1 determine the layout preset to determine the layout preset in the template editor, click the preset change button to modify the layout design presets consist of a combination of three areas card header area, card primary area, and card auxiliary area select each tabs respectively to create the desired combination note-the design types provided vary by card type and area note-• changing the preset updates all previously saved layouts • once a card has been activated, its layout cannot be modified ensure thorough testing before releasing the card card header area choose from six option, including logo type and sub-text combinations logo type logo image, logo image + text, text only the card header area has the same configuration across all card types, and 6 available configurations card primary area the main section that determines the card's primary layout the card primary area is configured differently for each card types the primary area of loyalty membership , coupon, event ticket, generic card has 7 available configurations the primary area of a boarding pass has 4 available configurations card auxiliary area select the number of text fields needed to provide additional information the card auxiliary area is configured differently for each card types the auxiliary area of loyalty membership ,, coupon, event ticket, generic card has 5 available configurations the auxiliary area of a boarding pass has 6 available configurations step 2 define key values for each attribute in the layout to define the key values for each attribute click on an empty container in the card preview where the key has not been set when an empty container consists of a label and a value pair, the label and value are selected as a group setting either a label or a value synchronizes and applies the values across all grouped containers click the entry key button to view the supported attribute names please refer to the wallet card spec for details on the attributes of each entry key boarding pass | event ticket | coupon | loyalty membership | generic card select an attribute from the list or if the desired attribute is not available, enter the value directly in the direct input field when selecting from the attribute list, samsung wallet's supported text will appear in your application save the key value by clicking the save button once all configurations are complete, click apply to implement the layout step 3 prepare card data matching the layout design to prepare the card data matching the chosen layout design refer to the specifications for each card type for wallet card data if you used direct input during layout setup, provide an extendedfields attribute corresponding to the key value entrykey the key entered in the input field label the name displayed in your application value the data corresponding to the label "extendedfields" "[{\"label\" \"group/boarding\", \"value\" \"6/10 35\", \"entrykey\" \"group/boarding\"}]"
Develop Health
docmigrating exercise app to samsung health data sdk as of july 2025, samsung health sdk for android has been deprecated while existing functionality will continue to operate for now, developers are strongly encouraged to migrate to samsung health data sdk to ensure long-term compatibility and continued support both sdks provide access to health data, stored in samsung health app this data may originate directly from the app itself, as is the case for steps, or from connected wearable devices such as the ring, watch or dedicated medical equipment samsung health data sdk offers several advantages over its predecessor more user-friendly api support for more features such as suspend functions cleaner and more compact source code for more information and resources, refer to samsung health data sdk introduction the steps on this page help you easily understand the overall process of migrating your app that reads and inserts exercise data to use the samsung health data sdk prerequisites set up your environment before you begin the integration, make sure that you have the following installed and ready android studio java jdk 17 or higher android mobile device compatible with the latest version of samsung health set up your android device refer to the following resources to set up your android device turn on the phone’s developer options run apps on a hardware device download samsung health data sdk visit samsung health data sdk page to download samsung health data sdk enable samsung health data sdk’s developer mode previously, samsung health sdk for android required developers to submit a partner request to gain access, which needed to be applied for and approved before use now, with samsung health data sdk, you can download and use the sdk in developer mode without submitting a partner request to enhance convenience for developers, samsung health data sdk has improved its developer mode functionality if you only need to read data from samsung health app, you can activate developer mode and proceed with development and testing without requiring a partner request for more information on developer mode, please refer to developer mode if you want to test writing data to samsung health app using samsung health data sdk or distribute your app, you need to obtain a partnership for samsung health data sdk you can request it by following this process project setup import sdk library replace samsung health sdk for android aar file in your project navigate to app/libs in your project replace samsung-health-data-1 5 1 aar with samsung-health-data-api- version aar from the downloaded sdk package app manifest when using samsung health data sdk, your app’s manifest should no longer include any entries related to health data permissions gradle settings sdk dependency update your module-level build gradle to include the correct dependency replace dependencies { implementation files "/libs/samsung-health-data-1 5 1 aar" } with entry samsung health data sdk version independent dependencies { implementation filetree mapof "dir" to "libs", "include" to listof "* aar" } other configuration add gson library to the dependencies of module-level build gradle dependencies { implementation "com google code gson gson 2 13 2" } apply the kotlin-parcelize plugin to the module-level build gradle plugins { id "kotlin-parcelize" } additionally, check the module-level build gradle file and include any other dependencies required by your implementation connect with samsung health after completing the initial setup, you are ready to connect your app to samsung health to access exercise data in the following paragraphs, we are going to show you how to migrate specific elements of logic from samsung health sdk for android to samsung health data sdk samsung health sdk for android with samsung health sdk for android, establishing a connection requires the following import healthdatastore import com samsung android sdk healthdata healthdatastore declare healthdatastore instance with lateinit var healthdatastore healthdatastore initialize the instance and start the connection with healthdatastore = healthdatastore context, listener also { it connectservice } these are the provided arguments listener – healthdatastore connectionlistener instance, used to observe the connection results and handle connection failures context – typically app or activity context samsung health data sdk with samsung health data sdk, establishing a connection is simpler, as there is no need to implement a connection listener import the following class import com samsung android sdk health data healthdatastore notethe class name healthdatastore class is the same as in samsung health sdk for android however, their import directories differ make sure that you are using the correct path we can now establish the connection and obtain a healthdatastore instance by calling healthdataservice getstore context here, context can be your app context request permissions upon successful connection to samsung health, your app must ensure that it has permissions to access the health data from samsung health since samsung sdks enforce data access control, defining and checking permissions must be done before any data operations are performed samsung health sdk for android in samsung health sdk for android, you must first create a permission set, specifying which data type your app intends to access and the access permission read or write for example, to request read and write permissions for exercise data val permissions = setof healthpermissionmanager permissionkey healthconstants exercise health_data_type, healthpermissionmanager permissiontype read , healthpermissionmanager permissionkey healthconstants exercise health_data_type, healthpermissionmanager permissiontype write then, to check existing permissions and request any that are missing, use the healthpermissionmanager class val permissionmanager = healthpermissionmanager healthdatastore runcatching { val grantedpermissions = permissionmanager ispermissionacquired permissions if grantedpermissions values all { it } { log i app_tag, "all required permissions granted" } else { log i app_tag, "not all required permissions granted" permissionmanager requestpermissions permissions, context setresultlistener permissionlistener } } onfailure { error -> error message? let { log i app_tag, it } } samsung health data sdk in samsung health data sdk, requesting data access permissions is simpler for example, to request read and write permissions for exercise data val permissions = setof permission of datatypes exercise, accesstype read , permission of datatypes exercise, accesstype write then, to check if all necessary permissions have been granted val grantedpermissions = healthdatastore getgrantedpermissions permissions val areallpermissionsgranted = grantedpermissions containsall permissions if there are any missing permissions, prompt the user to grant them try { val result = healthdatastore requestpermissions permissions, context // … } // catch any error read exercise data samsung health sdk for android in samsung health sdk for android, to read exercise data, you need to create a read request by defining the data type and time range set the data type using healthconstants exercise health_data_type and specify the local time range using setlocaltimerange, which accepts the start and end time in longs val readrequest = healthdataresolver readrequest builder setdatatype healthconstants exercise health_data_type setlocaltimerange healthconstants exercise start_time, healthconstants exercise time_offset, starttime, endtime build next, initialize a healthdataresolver object using the previously obtained healthdatastore instance and handler and launch the prepared readrequest to process the results for example, you can retrieve the device id associated with each recorded exercise this is useful when you want to determine which device the data originates from to achieve this, you can create an iterator to access healthdata that represents an exercise record val healthdataresolver = healthdataresolver healthdatastore, handler try { healthdataresolver read readrequest await run { try { val iterator = iterator while iterator hasnext { val healthdata = iterator next val deviceid = healthdata getstring healthconstants exercise device_uuid // process obtained deviceid or other data } } finally { close } } } catch exception exception { exception message? let { log i tag, it } } samsung health data sdk in samsung health data sdk, you can achieve the same result with simpler and more concise code as before, you need to create a read request first, create a localtimefilter to access data for the current day val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime then, apply it to the prepared request val readrequest = datatypes exercise readdatarequestbuilder setlocaltimefilter localtimefilter build to launch the request, simply call the readdata method of the healthdatastore instance, passing readrequest as an argument the result includes a datalist, which you can iterate through to access exercise data val exercisedatalist = healthdatastore readdata readrequest datalist exercisedatalist foreach { healthdatapoint -> val deviceid = healthdatapoint datasource? deviceid // process obtained deviceid or other data } read aggregated data for data types that represent summarized values, such as total, minimum, maximum or last values, you can use aggregate requests to compute these results samsung health sdk for android in samsung health sdk for android, to read aggregated data for a specific period, you need to create aggregaterequest with a defined time range and aggregation function for example, to read the total calories burned from exercise since the start of the day, you can call addfunction with aggregatefunction sum setlocaltimerange with starttime as the start of the day and endtime as the current time setdatatype with healthconstants exercise health_data_type below is an implementation of aggregaterequest that reads the total exercise calories since the start of the day note that you also need to define the key id to retrieve the aggregated data later val exercisetotalcaloriesid = "exercise_total_calories" val aggregaterequest = healthdataresolver aggregaterequest builder addfunction healthdataresolver aggregaterequest aggregatefunction sum, healthconstants exercise calorie, exercisetotalcaloriesid setlocaltimerange healthconstants exercise start_time, healthconstants exercise time_offset, starttime, endtime setdatatype healthconstants exercise health_data_type build next, launch the request synchronously and iterate through the results to get the total calories var totalcalories = 0 try { healthdataresolver aggregate aggregaterequest await run { try { val iterator = iterator if iterator hasnext { val healthdata = iterator next totalcalories = healthdata getint exercisetotalcaloriesid } } finally { close } } } catch exception exception { exception message? let { log i tag, it } } to get the total exercise duration, the logic remains the same the only difference is the property argument of the request’s addfunction , as well as the key to retrieve the aggregated data addfunction healthdataresolver aggregaterequest aggregatefunction sum, healthconstants exercise duration, "exercise_total_duration" samsung health data sdk in samsung health data sdk, it is simpler to get the aggregated data first, you need to create localtimefilter to define the time range val starttime = localdate now atstartofday val endtime = localdatetime now val localtimefilter = localtimefilter of starttime, endtime then, build an aggregaterequest instance by calling requestbuilder on the desired aggregate data type for exercise data, this could be either datatype exercisetype total_calories or datatype exercisetype total_duration the full request is shown below val aggregaterequest = datatype exercisetype total_calories requestbuilder setlocaltimefilter localtimefilter build to obtain the aggregated data, create an aggregate request and access the datalist since this type of request returns a single-element list containing the aggregated value, you can use kotlin’s mapnotnull function to extract it safely, ensuring it’s not null healthdatastore aggregatedata aggregaterequest datalist mapnotnull { it value } insert data let's explore how to insert prepared exercise data into samsung health samsung health sdk for android to insert data in samsung health sdk for android, you first need to create a healthdata instance that contains the exercise data to be inserted the health data includes the start time, end time, exercise type or duration, and live data time-series data across different exercise stages the livedata placeholder contains the user’s heart rate or speed across each exercise phase let's prepare a set of dummy data to insert in real-world scenarios, healthdata includes real-time measurements captured from wearable devices or other health and fitness equipment prepare data to be inserted first, create livedata - a list of objects of your custom data class exerciselivedata according to the documentation for samsung health sdk for android, it is recommended to provide start_time and at least one additional field for each instance of livedata for more details, please refer to livedata declare the start_time, heart_rate and speed data val livedatalist = listof exerciselivedata start_time = instant ofepochsecond 1766394000 toepochmilli , heart_rate = 144f, speed = 1 6f , exerciselivedata start_time = instant ofepochsecond 1766394030 toepochmilli , heart_rate = 146f, speed = 1 8f , // add more entries convert livedata list next, convert the livedata list to jsonblob bytearray format by using the sdk function getjsonblob this function takes a list of exerciselivedata as an argument and returns bytearray you can simply create a helper function for this task private fun createlivedata livedatalist list<exerciselivedata> bytearray { val zip = healthdatautil getjsonblob livedatalist return zip } create healthdata object create a healthdata object that holds all exercise data, including timestamps, calories, distance, duration and livedata the livedata is attached using the putblob function in addition to the standard fields start_time, end_time, and time_offset, it is necessary to specify the exercise type based on the predefined exercise type table, setting the value to 1002 represents a running exercise val calories = 73f val distance = 1000f val exercisetype = 1002 val starttime = instant ofepochsecond 1766394000 val endtime = instant ofepochsecond 1766394300 val duration = duration between starttime, endtime val timeoffset = timezone getdefault getoffset endtime toepochmilli tolong val healthdata = healthdata apply { sourcedevice = deviceid putlong healthconstants exercise start_time, starttime toepochmilli putlong healthconstants exercise end_time, endtime toepochmilli putlong healthconstants exercise time_offset, timeoffset putint healthconstants exercise exercise_type, exercisetype putlong healthconstants exercise duration, duration tomillis putfloat healthconstants exercise calorie, calories putfloat healthconstants exercise distance, distance putblob healthconstants exercise live_data, createlivedata livedatalist } insert the prepared data use a healthdataresolver class to build an insertrequest initialize a healthdataresolver instance and pass in the already connected healthdatastore utilize a builder function and set healthconstants exercise health_data_type as the data type retrieve the local device id using the healthdevicemanager instance, as you need to specify the source device that provides this data call the insert function with the prepared insertrequest and wait for the result below is an implementation example val handler = handler looper getmainlooper val healthdataresolver = healthdataresolver healthdatastore, handler try { val localdevice = healthdevicemanager healthdatastore localdevice uuid val data = exerciseinsertdata getexercisedata endtime, localdevice if data != null { val insertrequest = healthdataresolver insertrequest builder setdatatype healthconstants exercise health_data_type build insertrequest addhealthdata data val result = healthdataresolver insert insertrequest await if result status == healthresultholder baseresult status_successful { log i tag, "inserted running exercise count of data ${result count}" } else { log i tag, "inserting failed" } } } catch e exception { throw e } samsung health data sdk in samsung health data sdk, preparing livedata to be inserted into samsung health app is simplified by the help of the exerciselog class with predefined fields such as timestamp, heartrate, cadence and more, this class is ready to capture information for each phase of an exercise session this eliminates the need to manually encode it to jsonblob bytearray format instead, you can simply create a list of exerciselog objects, each representing a phase of the exercise val exerciselog = listof exerciselog of timestamp = instant ofepochsecond 1766394000 , heartrate = 144f, speed = 1 6f, cadence = null, count = null, power = null , exerciselog of timestamp = instant ofepochsecond 1766394030 , heartrate = 146f, speed = 1 8f, cadence = null, count = null, power = null // add more entries create a healthdatapoint instance another key difference in samsung health data sdk is that, instead of creating a healthdata instance, the sdk provides a healthdatapoint object that represents the entire exercise before creating a healthdatapoint instance, you need the following list of exerciselog objects predefined exercise type use addfielddata function to set the exercise type property with a predefined enum value and include list of datatype exercisetype sessions exercisesession object in the running exercise, there will always be a single-element list - an exercisesession element created based on a previously defined list of exerciselog objects to create an exercisesession object, use exercisesession builder and set the relevant data, such as start time, end time, exercise type, calories and duration once the relevant information is prepared, you can call the builder method to initialize a healthdatapoint instance and set the properties, such as start time, end time, and exercise type, by calling the addfielddata function the code is shown below val calories = 73f val distance = 1000f val starttime = instant ofepochsecond 1766394000 val endtime = instant ofepochsecond 1766394300 val duration = duration between starttime, endtime var healthdatapoint healthdatapoint? try { val session = exercisesession builder setstarttime starttime setendtime endtime setexercisetype datatype exercisetype predefinedexercisetype running setduration duration setcalories calories setdistance distance setcomment "routine running" setlog exerciselog build healthdatapoint = healthdatapoint builder setstarttime starttime setendtime endtime addfielddata datatype exercisetype exercise_type, datatype exercisetype predefinedexercisetype running addfielddata datatype exercisetype sessions, listof session build } catch e exception { throw e } insert the prepared data to insert the prepared data, simply build insertrequest by calling the insertdatarequestbuilder method on datatypes exercise attach the created data healthdatapoint instance by calling the adddata function finalize the request with the build method next, call the insertdata method of the healthdatastore instance and pass the created insertrequest as an argument val insertrequest = datatypes exercise insertdatarequestbuilder adddata data build healthdatastore insertdata insertrequest exception handling robust health apps can recover when things go wrong let's examine the differences between both sdks when handling such scenarios samsung health sdk for android in the case of samsung health sdk for android, the methods for handling errors depend on the exception types for example, connection exceptions with samsung health are handled by the healthdatastore connectionlistener's event handler you can use the healthconnectionerror class to check whether the error has a resolution based on the error type, you can implement different handling strategies for exceptions related to requests such as reading or writing data, refer to the healthresultholder baseresult class and its getstatus method however, since there are no dedicated exception class, developers must handle the exceptions that are part of the standard java language, such as illegalargumentexception, securityexception or illegalstateexception samsung health data sdk when working with samsung health data sdk, key functions such as aggregatedata , requestpermissions , or getgrantedpermissions may throw exceptions under certain conditions to prevent unexpected crashes or blank screens, it’s best to funnel these exceptions into a central error handler you can do so by wrapping every api invocation with try { // sdk function invocation } catch e healthdataexception { handlehealthdataexception e } about healthdataexception healthdataexception is the main exception class for samsung health data sdk the handlehealthdataexception function • shows an error log • tries to “resolve” the exception some healthdataexception instances include a resolution intent you can check if the exception has a resolution by checking the hasresolution property of the exception object and trying to fix it by invoking resolve examples of such exceptions • err_old_version_platform indicates samsung health app is outdated • err_platform_not_installed signals that samsung health app is not installed in both cases, the resolution involves opening the device’s app marketplace to prompt the user to install or update samsung health app once the issue is fixed, control returns to the app so it can continue functioning this approach not only keeps your ui clean, but allows for a consistent, guided error experience when something goes wrong, users can see a clear message of what happened and how to fix it include migration completion information in the app manifest please add the following details to the androidmanifest xml file of your app <manifest > <application > <meta-data android name="com samsung android sdk health data migration_completed" android value="true"/> </application> </manifest> summary we have covered how to migrate an app that uses samsung health sdk for android to samsung health data sdk when migrating your app to samsung health data sdk, you can follow the described process and code examples to complete the migration for more details, please refer to samsung health data sdk introduction partner request before distributing your app the developer mode of samsung health data sdk is a feature provided solely for development purposes to ensure that an app using samsung health data sdk functions properly without enabling developer mode, you need to submit a partner request through the developer site before distributing your app on app marketplaces after the partner app is approved, the app's detailed information will be registered in samsung's system having a trouble? we are operating a developer support channel on the samsung developer site if you encounter any issue or any question, please visit developer support and submit your query after logging in your samsung account
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
You have successfully updated your cookie preferences.