Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
tutorials health, galaxy watch
bloggalaxy watch offers a convenient way of measuring exercise progress. modern sensors designed specifically for health services provide the most precise readings. after connecting to health services, you can measure certain exercises and track their values. this blog describes all the important steps to build an exercise tracking app using the health services api. we use example code introduced in health code lab for tracking exercise. you can download the source code from this code lab. health services defines a variety of exercise types. for a full exercise type list, take a look at exercisetype. on galaxy watch4 and galaxy watch4 classic, a repetition counter is available for the following exercises: back_extension barbell_shoulder_press bench_press bench_sit_up burpee crunch deadlift forward_twist dumbbell_curl_right_arm dumbbell_front_raise dumbbell_lateral_raise dumbbell_triceps_extension_left_arm dumbbell_triceps_extension_right_arm dumbbell_triceps_extension_two_arm dumbbell_curl_left_arm jump_rope jumping_jack lat_pull_down lunge squat upper_twist in this application, we are going to use deadlift. the example code used for deadlift can be easily adapted to track all repetition-based exercises. the basics of connecting to health services are covered in the blog using health services on galaxy watch. setting up an exercise once connected to the health services api, we are ready to set up the exercise. in this case we use deadlift as a sample exercise. first, we need to get the exercise client: exerciseclient exerciseclient = client.getexerciseclient(); after that, we need to set the exercise type in the configuration builder: exercisetype exercisetype = exercisetype.deadlift exerciseconfigbuilder exerciseconfigbuilder = exerciseconfig.builder() .setexercisetype(exercisetype); to see what can be tracked for our exercise, we need to check its capabilities. we do this by using a listenablefuture object and listening for a callback from health services. listenablefuture<exercisecapabilities> capabilitieslistenablefuture = exerciseclient.getcapabilities(); when we receive a callback, we can receive a set with capabilities: futurecallback<exercisecapabilities>() { @override public void onsuccess(@nullable exercisecapabilities result) { try { exercisetypecapabilities exercisetypecapabilities = result.getexercisetypecapabilities(exercisetype); set<datatype> exercisecapabilitiesset = exercisetypecapabilities.getexercisecapabilities(result); } if you do not want to track some of these values, at this point, you can remove them from a set. by default, all datatypes that a certain exercise can measure are being stored as a set. by removing them before setting up a configuration builder, you can exclude tracking unnecessary values. once we are ready, we can finish configuring an exercise: exerciseconfigbuilder = exerciseconfig.builder() .setexercisetype(exercisetype) .setdatatypes(exercisecapabilitiesset); setting up exercise listener an exercise listener is an object that allows us to get exercise updates from health services, whenever they are available. to set up the listener, we need to override three methods: exerciseupdatelistener exerciseupdatelistener = new exerciseupdatelistener() { @override public void onexerciseupdate(exerciseupdate update) { //processing your update } @override public void onavailabilitychanged(datatype datatype, availability availability) { //processing availability } @override public void onlapsummary(exerciselapsummary summary) { //processing lap summary } }; starting and stopping the exercise we are ready to start tracking our exercise. to do that, we use the listenablefuture object that gets callbacks from the healthservices api whenever an update is available. to build this object, we send our configuration to the exercise client while starting measurement: listenablefuture<void> startexerciselistenablefuture = exerciseclient.startexercise(exerciseconfigbuilder.build()); when we get a callback from the healthservices api, we start our listener: listenablefuture<void> updatelistenablefuture = exerciseclient.setupdatelistener(exerciseupdatelistener); we finish exercise in a similar way, by creating a listenablefuture object that asks the health services api to stop tracking exercise: listenablefuture<void> endexerciselistenablefuture = exerciseclient.endexercise() processing exercise update data exercise update data contains various information about the performed exercise. after setting up a listener, we retrieve it in a callback: public void onexerciseupdate(@nonnull exerciseupdate update) { try { updaterepcount(update); } catch (deadliftexception exception) { log.e(tag, "error getting exercise update: ", exception); } } in this example, we focus on one of most important readings—latest metrics. we store them in a map: map<datatype, list<datapoint>> map = update.getlatestmetrics(); now we can read particular values by looking for their key: list<datapoint> reppoints = map.get(datatype.rep_count); list<datapoint> caloriespoints = map.get(datatype.total_calories); the last value on the list is the latest reading in the current update. we can use it in our application, for example, when updating a label: string repvalue = string.format("%d", iterables.getlast(reppoints).getvalue().aslong()); txtreps.settext(string.format("reps count: %s", repvalue)); this is how exercise data can be accessed and processed using health services on galaxy watch. it’s a quick and convenient way to track its progress that everybody can implement into a watch application.
Feb 16, 2022
tutorials health, galaxy watch
blogthe galaxy watch running wear os powered by samsung can detect events like hard falls. to detect the hard falls, the watch uses a built-in accelerometer. using the health services api, you can receive a fall detection event in your watch application. in this blog, we create a wear os application to identify a fall detection event and demonstrate how to use the health services api to achieve this on the galaxy watch. the galaxy watch uses the fall detection event in its sos feature. for more information, see use your samsung smart watch in an emergency situation. it can be used to take care of elderly people or patients. how to trigger a fall detection event in your application on the galaxy watch if the functionality provided with the watch is not sufficient for your solution, you can use the health services api to detect this event in your own application. in this section, we describe all the important steps that you must follow when building an events tracking app. as an example, we use the eventsmonitor sample project. project settings before you start writing your code, you need to import the health services api library in the dependencies section of the app/build.gradle file. implementation androidx.health:health-services-client:1.0.0-beta01 now you are ready to use the health services api. get passivemonitoringclient passivemonitoringclient enables tracking of the data in the background (without requiring an ongoing workout) and the events that can occur. you need to get this client to make your application suscribe to the events. private var healthservicesclient: healthservicesclient private var passivemonitoringclient: passivemonitoringclient init { healthservicesclient = healthservices.getclient(context) passivemonitoringclient = healthservicesclient.passivemonitoringclient } ask for permissions in the first step, you need to modify the androidmanifest.xml file. add the <uses-permission> element in the global section: <uses-permission android:name="android.permission.activity_recognition" /> <uses-permission android:name="android.permission.receive_boot_completed" /> <uses-permission android:name="android.permission.foreground_service" /> add the <queries> element: <queries> <package android:name="com.google.android.wearable.healthservices" /> </queries> it is a good practice to ask for the required permissions whenever the application tries to use this data type. first, you should check whether the user has consented to use the particular functionality. permissiongranted = applicationcontext.checkselfpermission( manifest.permission.activity_recognition) == packagemanager.permission_granted if not, you must ask for it before using the api. private fun requestpermissions() { permissionlauncher.launch(android.manifest.permission.activity_recognition) } to ask about permissions, you need to create a request permissions object. permissionlauncher = registerforactivityresult(activityresultcontracts.requestpermission()) { result -> permissiongranted = result } this is an example of a permission request window: using health services api to get events to asynchronously receive information about a fall detection event, provide the class which inherits from the passivelistenerservice class and override the onhealtheventreceived method. class passivehealtheventservice : passivelistenerservice() { override fun onhealtheventreceived(event: healthevent) { runblocking { log.i(tag, "onhealtheventreceived received with type: ${event.type}") healthservicesmanager.getinstance(applicationcontext).recordhealthevent(event) super.onhealtheventreceived(event) } } } add information about this class with the permissions to the androidmanifest.xml file. <service android:name=".passivehealtheventservice" android:exported="true" android:permission="com.google.android.wearable.healthservices.permission.passive_data_binding" /> when you have the passivemonitoringclient and passivehealtheventservice classes, you can then subscribe to the events. private val healtheventtypes = setof(healthevent.type.fall_detected) suspend fun registerforhealtheventsdata() { log.i(tag, "registering listener") val passivelistenerconfig = passivelistenerconfig.builder() .sethealtheventtypes(healtheventtypes) .build() passivemonitoringclient.setpassivelistenerserviceasync( passivehealtheventservice::class.java, passivelistenerconfig ).await() registered = true } if you no longer want to receive information about the fall detection event, please unregister your application from the service. this can be done using the passivemonitoringclient api. suspend fun unregisterhealtheventsdata() { log.i(tag, "unregistering listeners") passivemonitoringclient.clearpassivelistenerserviceasync().await() registered = false } the healthevent class contains information about the event, such as: type - returns the type of the event (fall_detected, unknown). instant - returns the time of the health event. datapointcontainer - returns the metrics associated with the event. test application on the galaxy watch you can test this functionality in the following two ways: manual test you can simulate a fall by trying to fall on a mat. notebefore performing the manual test, ensure that you have taken all safety precautions for yourself. for example, use cushions to soften the fall impact, etc. use synthetic data testing is available on an emulator. use the command line to run and execute commands for synthetic data generation. for more details about this feature, see simulate sensor data with health services. with adb, you can send subsequent commands to the device. notethis blog is based on wear os 4. you can check your watch’s wear os version in galaxy watch > settings > about watch > software information> wear os version. for testing on wear os 3, see more information here. to start the synthetic data generation, run the following command: $ adb shell am broadcast \ -a "whs.use_synthetic_providers" \ com.google.android.wearable.healthservices to simulate a fall, run the following command: $ adb shell am broadcast \ -a "whs.fall_over" \ com.google.android.wearable.healthservices when the tests are finished, to switch back to using real sensors, run the following command: $ adb shell am broadcast \ -a "whs.use_sensor_providers" \ com.google.android.wearable.healthservices resources this blog is based on the eventsmonitor application. the whole presented code comes from this application. the entire application can be downloaded from: eventsmonitor version 1.0 (86,0kb) dec 12, 2022 enjoy your adventure creating the ultimate health application now you are ready to start the fall detection event in your application. we encourage you to try doing it by yourself and explore other features provided by the health services sdk.
Jan 18, 2024
Samsung Developers
tutorials health, galaxy watch
blogtracking exercise progress throughout its duration can be a problematic task requiring a lot of work from the developer. health services available on a samsung galaxy watch provide a precise and convenient way to gather statistics. in this blog post we cover different ways to gather exercise data. we created an example application called exercise monitor which gathers statistics about your heart rate and speed while running on a treadmill. in the application we use two ways to gather statistics: statisticaldatapoint for speed and manual heart rate tracking for comparison. you can download it here. we also include an example in this blog using cumulativedatapoint to gather statistics. the basics of connecting to health services are covered in the blog using health services on galaxy watch. let's start by setting up your exercise then continue by working with the exercise data. tracking data with statisticaldatapoint to obtain a statisticaldatapoint object, we need to read aggregated metrics in the exercise configuration builder: exercisecapabilitiesset = result.getexercisetypecapabilities(exercisetype).getsupporteddatatypes(); exerciseconfigbuilder = exerciseconfig.builder() .setexercisetype(exercisetype) .setdatatypes(exercisecapabilitiesset) .setaggregatedatatypes(exercisecapabilitiesset); after that we can read these metrics from exerciseupdate: map<datatype, aggregatedatapoint> aggregatemap = update.getlatestaggregatemetrics(); then we have to read the appropriate datatype from the map. in this case—speed: aggregatedatapoint aggregatespeed = aggregatemap.get(datatype.speed); the aggregatedatapoint object that is obtained can be an instance of two classes—either statisticaldatapoint or cumulativedatapoint (which we cover later): statisticaldatapoint sdpspeed = (statisticaldatapoint) aggregatespeed; from there we can easily read all important statistical data: double minspeed = sdpspeed.getmin().asdouble(); double maxspeed = sdpspeed.getmax().asdouble(); double avgspeed = sdpspeed.getaverage().asdouble(); and use them however we like in the application, for example updating text on labels: txtminspeed.settext(string.format("min speed: %.1f km/h", minspeed)); txtmaxspeed.settext(string.format("max speed: %.1f km/h", maxspeed)); txtavgspeed.settext(string.format("average speed: %.1f km/h", avgspeed)); that’s all we need to do—easy to read and fast to implement. in this case we have only read exercise data, but statistics can be obtained from other health services areas as well. tracking data manually now let's compare tracking data with statisticaldatapoint to tracking heart rate manually. first we need to create appropriate global variables required to track data—especially for the average heart rate that requires information about count samples we gather throughout exercising: double hrmin = 1000, hrmax = 0, hrsum = 0; int hrcount = 0; since our application assumes that we can exercise multiple times, we need to reset these global variables each time we stop and start an exercise. therefore, we need a separate function that resets the variables each time we start an exercise: void init() { hrcount = 0; hrmin = 1000; hrmax = 0; hrsum = 0; txtminhr = binding.txtminhr; txtminspeed = binding.txtminspeed; txtmaxhr = binding.txtmaxhr; txtmaxspeed = binding.txtmaxspeed; txtavghr = binding.txtavghr; txtavgspeed = binding.txtavgspeed; } we are ready to work on reading data from exerciseupdate. first we get the latest readings: map<datatype, list<datapoint>> datamap = update.getlatestmetrics(); then we read heartrate datatype from the map: list<datapoint> hrpoints = datamap.get(datatype.heart_rate_bpm); this returns a list of heart rates registered since the previous exerciseupdate callback. we have to iterate through every element and compare its values to our statistical points: for (int i = 0; i < hrpoints.size(); i++) { double curval = hrpoints.get(i).getvalue().asdouble(); if (curval == 0) continue; hrcount++; hrsum += curval; if (curval < hrmin) hrmin = curval; if (curval > hrmax) hrmax = curval; } this covers min and max values. as for the average, we have to remember that not every exerciseupdate may contain heart rate readings. if it doesn’t, we need to prevent division by 0: if (hrcount == 0) return; double avghr = hrsum / hrcount; now we are ready to update our text labels—with the exception of the minimum heart rate. if there were no readings, we leave it at 0 instead of updating it to the initialized value: txtavghr.settext(string.format("average hr: %.0f bpm", avghr)); if (hrmin < 1000) txtminhr.settext(string.format("min hr: %.0f bpm", hrmin)); txtmaxhr.settext(string.format("max hr: %.0f bpm", hrmax)); tracking data with cumulativedatapoint the third option to gather data statistics is using cumulativedatapoint. it is not used in the exercise monitor sample application, but we present an example application in this post. one example cumulativedatapoint can be used for is repetition statistics, like counting deadlift or dumbbell curl repetitions throughout sets. we start similarly to statisticaldatapoint by gathering the latest aggregate metrics. but, this time we read the repetition count and cast it to cumulativedatapoint: map<datatype, aggregatedatapoint> aggregatemap = update.getlatestaggregatemetrics(); cumulativedatapoint cdprepetitions = (cumulativedatapoint) aggregatereps; now we can measure total repetitions done throughout sets, as well as the workout start and end time: long totalreps = cdprepetitions.gettotal().aslong(); instant starttime = cdprepetitions.getstarttime(); instant endtime = cdprepetitions.getendtime(); enjoy your adventure creating an application that will track anything you want! we have shown you three ways of gathering exercise statistics. we encourage you to use statisticaldatapoint or cumulativedatapoint whenever possible, as they are well-designed to track exercise progress and might significantly simplify development of your fitness app. now you are ready to start gathering aggregated exercise statistics using health services data in the background in your application on galaxy watch with wear os powered by samsung. we encourage you to experiment on your own with data you wish to track and exercises you want to perform and see how easy and convenient it is!
Jun 22, 2022
tutorials health, galaxy watch
blogone of the methods for obtaining data from health services running on galaxy watch with wear os powered by samsung is to register notifications for fitness goals. galaxy watch collects physical activity data in real-time and allows the user to sign up for information about achieving their goals. this mechanism allows you to monitor the health services data in the background. a sample application named goalevent shows the above described mechanism. full source code of this application can be downloaded from goalevent. application overview goalevent is a sample application with only one task: it is designed to monitor health services data in the background. its interface allows the user to subscribe to a health event. two buttons make it possible to set the amount of steps to achieve and a third button makes it is possible to subscribe to an event. a toast with information about achieving the goal is shown when the step count is greater than or equal to the set amount of steps. the construction of the most important elements of this application is described in the next sections, step-by-step. the code below comes from the goalevent application. add health services the first step to start using health services is to add the implementation of the service client to application dependencies. there are also necessary changes in the manifest file. to interact with health services, there should be information about this package. more information about adding health services usage to a project is contained in this article: using health services on galaxy watch obtain permissions the second step of the application is to obtain permissions. to use necessary operating system elements, you should place all of the required permissions in the android manifest. there are two types of permissions needed for receiving steps information and for showing an ongoing notification. permissions required by the application: <!-- for receiving steps information. --> <uses-permission android:name="android.permission.activity_recognition" /> <!-- for showing an ongoing notification. --> <uses-permission android:name="android.permission.foreground_service" /> as a next step, these permissions should be requested in the main activity of the application. after receiving the results of the permissions request and making sure that all of them are granted, it is possible to go on and check capabilities. request permission example code: requestpermissions(new string[]{ manifest.permission.foreground_service, manifest.permission.activity_recognition}, 0); check capabilities the next step, after obtaining the permissions, that is necessary to use the health platform and making sure that all permissions have been obtained, is to check that the device can provide passive goals. this takes place in the passive monitoring client where there are data types corresponding to a chosen activity—for example, steps. check capabilities in goal event client: boolean supportsstepsevent = result .getsupporteddatatypesevents() .contains(datatype.steps); if(supportsstepsevent) { registergoal(context); } register a goal after getting information that step goals are supported, it is possible to register a goal. to do this, you need to create a passive goal and register the appropriate callback. the callback, which is received, must be served by a specially designed interface. this class should be appropriately marked in the android manifest as a goal receiver. register a goal in the goal event client: public class goaleventclient { //... public void registergoal(context context) { if(goalregistered) return; goalregistered = true; mpassivegoal = new passivegoal( new datatypecondition(datatype.steps, value.oflong(number_of_steps), comparisontype.greater_than_or_equal), passivegoal.triggertype.once); mpassivemonitoringclient.registerpassivegoalcallback(mpassivegoal, new componentname(context, eventreceiver.class)); } //... } add receiver information inside of the application tag in the android manifest: <application <!--....--> <receiver android:name="com.samsung.android.goalevent.eventreceiver" android:exported="true"> <intent-filter> <action android:name="hs.passivemonitoring.goal" /> </intent-filter> </receiver> <!--...--> </application> receive notification in the receiver code, first you need to check the intent action to ensure that it is a passive goal. then reconstruct the passive goal from the intent to determine that the incoming goal is the same as the goal created earlier. override the receive method in the event receiver: public final class eventreceiver extends broadcastreceiver { private static final string tag = "eventreceiver"; @override public void onreceive(context context, intent intent) { if(!intent.getaction().equals(passivegoal.action_goal)){ return; } passivegoal goal = passivegoal.fromintent(intent); if(goal != null && goal.equals(goaleventclient.getinstance(context).getpassivegoal())){ log.i(tag, "step goal achieved!"); toast.maketext(context, r.string.step_goal_achieved, toast.length_long) .show(); goaleventclient.getinstance(context).unregistergoal(); } } } unregister the goal it is a good practice to unregister the goal when the application is destroyed by the os. to do this, add an additional boolean parameter which holds information about the registration status. this parameter should be set to "true" at the time of registration and to "false" at the time of goal deregistration. add a function to unregister a goal which is triggered at the time of destroying the application: public class goaleventclient { //... public void unregistergoal() { if(!goalregistered) return; goalregistered = false; mpassivemonitoringclient.unregisterpassivegoalcallback(mpassivegoal); mpassivegoal = null; } //... } test the application on a device the application can be tested on the galaxy watch with wear os powered by samsung by running it directly from android studio. to test the application, follow these steps: set the number of steps you want to achieve. push the 'set goal' button. 3. put your watch on your wrist and walk the set number of steps. 4. after reaching the goal, you receive information on the screen about achieving the goal and the watch vibrates. enjoy your adventure creating the ultimate health application now you are ready to start handling fitness goals using health services data in the background in your application on galaxy watch with wear os powered by samsung. check out our next series of posts that cover ways to access exercises using the health services api!
Apr 27, 2022
tutorials health
bloghealth connect is a platform that enables you to integrate samsung health data with your applications, creating new opportunities for health applications that enhance the user's journey towards better health. using the health connect apis, you can, for example, retrieve a user's samsung health data, such as their exercise, sleep, and heart rate information, and send data to the samsung health application. this is the first blog post in a series introducing you to the health connect api features and how you can use them in your applications. let's begin by looking at how health connect interacts with samsung health data and the basic workflow. understanding this is essential for creating applications that use data from samsung health and health connect. samsung health samsung health is an application that can be installed on android smartphones and tablets, and on galaxy watches. it can use the sensors on the device, including the galaxy watch's bioactive sensor, to measure the user's overall health data, including steps, exercises, heart rate, sleep, blood oxygen saturation and body composition. the samsung health application is installed on both the galaxy watch and a smartphone. the application synchronizes the measurements between both devices and manages the user's health data securely on them. figure 1: samsung health on galaxy watch and android smartphone health connect since the samsung health application supports various useful health data types and gathers data from all connected devices, developers have been interested in obtaining access to that data. consequently, samsung collaborated with google to build the health connect platform, which was released in may 2022. health connect enables applications to share health and fitness data across android devices with the user's consent. for more information about health connect, see health connect guide and health connect apis. samsung health has supported synchronizing data with health connect since application version 6.22.5, released in october 2022. the health connect apis support devices using android sdk 28 (pie) or higher. notesince android 14, health connect is a system application and is supported by the health connect api versions 1.1.0 and higher. make sure your samsung health application version is up to date, to enable support for the latest health connect features. for more information on health connect as a system application, see: migrate health connect. once the user has connected samsung health to health connect, new or updated data in samsung health is shared to health connect. this means that your applications can use the health connect apis to access samsung health data. samsung health synchronizes health data with health connect in both directions: when samsung health has new or updated data, it writes the data to health connect. when health connect has updated data, samsung health retrieves it. for example, a blood glucose meter connected to samsung health measures the user's blood glucose level. this data is saved in samsung health and then sent to health connect. similarly, whenever there is new blood glucose data in health connect, samsung health retrieves that data and saves it in samsung health. figure 2: accessing samsung health data through health connect to demonstrate how data synchronization works, let's walk through an example of adding nutrition information to samsung health. to start data synchronization between samsung health and health connect, you must enable it in the samsung health application on your android device. from the settings menu, select health connect. if health connect is not installed, you are prompted to install it. the first time you access the health connect menu item in samsung health, tap get started. figure 3: get started screen you are asked to grant permissions to share your samsung health data with health connect. select the data you consent to sharing and tap allow. note“read” and “write” permissions are granted separately. figure 4: data sharing consent samsung health and health connect are now linked and data is shared between them. to test the data synchronization, in samsung health, go to food tracker and create some nutrition data. figure 5: nutrition data input in samsung health, go to settings > health connect, and select data and access. if health connect has received nutrition data from samsung health, a nutrition item appears in the browse data list. figure 6: synchronized nutrition data to view the synchronized data, select nutrition. figure 7: nutrition data in health connect data synchronization timing data synchronization between samsung health and health connect occurs on the smartphone side. to take advantage of health data collected by a galaxy watch, you must understand at which times the galaxy watch sends its data to the samsung health smartphone application. figure 8: data synchronization between watch and smartphone new or updated health data on each connected device is generally synchronized with samsung health in the following situations: the galaxy watch reconnects with the smartphone the user opens the samsung health application home screen on the smartphone the user pulls down on the samsung health application home screen on the smartphone however, some types of health data are synchronized differently: for battery conservation reasons, continuous heart rate data from the galaxy watch is not sent to the samsung health application on the smartphone immediately. however, manual heart rate measurements on the watch are synchronized immediately. enabling settings in samsung health to synchronize health data between samsung health and health connect please consider: using the latest samsung health. if you're interested in galaxy watch's data, check its version too. allowing data permissions through the following path: samsung health > settings > health connect > app permissions > samsung health (note that you must enter from the samsung health settings) synchronizing samsung health data in: samsung health > settings > sync with samsung cloud > switch to 'on'. accessing health connect apis if the user has synchronized their samsung health data with health connect, you can use the health connect apis to interact with it in various ways. for example: read and write data: you can retrieve data that has been shared from samsung health to health connect and send data to health connect to be synchronized to samsung health. delete specific data records: you can remove a specific data point or data of a specific type within a time interval. aggregate and filter data: you can filter the retrieved data by type or tag and analyze it, such as determining the average, maximum, minimum or sum of the values. session data: you can group data into sessions by time interval, such as to generate a sleep or activity session report. notefor security reasons, health connect data can only be retrieved by applications running in the foreground. the following table lists the various health data that can be synchronized between samsung health and health connect. samsung health data corresponding health connect data type all steps stepsrecord blood glucose bloodglucoserecord blood oxygen oxygensaturationrecord blood pressure bloodpressurerecord exercise, session exercisesessionrecord exercise, calories totalcaloriesburnedrecord exercise, distance distancerecord exercise, heart rate heartraterecord exercise, power powerrecord exercise, speed speedrecord exercise, vo2max vo2maxrecord heart rate heartraterecord nutrition nutritionrecord sleep session sleep stage sleepsessionrecord weight weightrecord weight, body fat bodyfatrecord weight, basial metabolic rate basalmetabolicraterecord weight, height heightrecord notesynchronized data scope can be changed depending on the samsung health version. notethe exercise data in the table (total calories burned, distance, power, speed, vo2max) are samsung health exercise tracker's data. samsung health’s activity tracker data are not synchronized to health connect. to get started with implementing health connect api functionality in your application: add the latest version of the health connect api library dependencies to your application's "build.gradle" file, for example: implementation "androidx.health.connect:connect-client:1.1.0-alpha02" declare the health connect application package name in your "androidmanifest.xml" file. check that the user has the health connect application, then create the "healthconnectclient" instance. declare the permissions for the health data types you want to use. now your application is ready to use the health connect apis. other blog posts in this series explore various health connect api use cases in more detail. related blogs reading body composition data with galaxy watch via health connect api
Jun 4, 2024
tutorials health, galaxy watch, mobile
blogsleep is an important factor in our everyday life. good sleeping habits play a major role in physical health and overall well-being. with galaxy watch and samsung health, users can track their sleep, evaluate its quality, and get coaching to develop healthy habits. when the user wakes up, the sleep data is analyzed and the user can review key sleep statistics and how much time they spent in each sleep stage. sleep coaching functionality compares data to previous days, so the user can track how their daily routine improvements influence their sleep quality. galaxy watch devices can also measure blood oxygen during sleep, and users with a galaxy watch5 or higher can also track their skin temperature. when a phone is used together with the watch for sleep tracking, snoring detection is also possible. sleep tracking you can leverage samsung health advanced sleep tracking and health connect api to create applications that can read users’ real sleep data and create custom sleep session information that can be synchronized to samsung health. this blog demonstrates how to use the health connect api to read data from health connect, work with session data, and insert data to health connect, using sleep data as an example. to follow along with the steps in this blog, download the sample application: sleep recorder version 1.0 (128,0kb) jan 15, 2024 for more information about samsung health and health connect, see accessing samsung health data through health connect.. sleep data synchronization with health connect the health connect platform collects health-related data and synchronizes it with samsung health, enabling you to use it in your applications. sleep data is created on a smartwatch when the user wakes up. the data must be transferred to a paired mobile device for processing. data transfer is initiated when the mobile device is connected. the processed data creates a sleep record, which samsung health synchronizes to health connect. transfer and synchronization tasks can be delayed, depending on processor availability. prerequisites implementing functionality that uses health data in an application requires health connect library, healthconnectionclient, and permissions. add health connect api library dependencies to use the health connect api features in your application: dependencies { // add health connect library implementation "androidx.health.connect:connect-client:1.1.0-alpha06" } configure the “androidmanifest.xml” file declare the required permissions: <uses-permission android:name="android.permission.health.write_sleep"/> <uses-permission android:name="android.permission.health.read_sleep" /> add <intent-filter> in the <activity> section: <intent-filter> <action android:name="androidx.health.action_show_permissions_rationale" /> </intent-filter> add the <activity-alias> element required in android 14: <activity-alias android:name="viewpermissionusageactivity" android:exported="true" android:targetactivity=".mainmenuactivity" android:permission="android.permission.start_view_permission_usage"> <intent-filter> <action android:name="android.intent.action.view_permission_usage" /> <category android:name="android.intent.category.health_permissions" /> </intent-filter> </activity-alias> add <uses-permission> elements: <uses-permission android:name="android.permission.health.write_sleep"/> <uses-permission android:name="android.permission.health.read_sleep" /> add the <queries> element: <queries> <package android:name="com.google.android.apps.healthdata" /> </queries> note that in this application we also use: <package android:name="com.sec.android.app.shealth" /> adding this element is necessary, since we are going to open the samsung health app. however, if you are interested in using only the health connect api – the above part is not required. get a healthconnect client the healthconnectclient class is an entry point to the health connect api. it automatically manages the connection to the underlying storage layer and handles all ipc and serialization of the outgoing requests and the incoming responses. it is a good practice to ensure that the device running your application actually supports the health connect api library. the library is available only when the health connect application is installed on the device. noteandroid 14 health connect is part of the system and is installed by default. however in earlier versions, it's necessary to check if health connect is present on the device. check for health connect availability. if it is missing, display an error and redirect the user to the app store if installation of the app is possible: when (healthconnectclient.getsdkstatus(this)) { healthconnectclient.sdk_unavailable -> { // error message } healthconnectclient.sdk_unavailable_provider_update_required -> { // error message try { startactivity( intent( intent.action_view, uri.parse("market://details?id=com.google.android.apps.healthdata"), ), ) } catch (e: activitynotfoundexception) { startactivity( intent( intent.action_view, uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.healthdata"), ), ) } } if health connect is available, get a healthconnectclient class instance: private val healthconnectclient by lazy { healthconnectclient.getorcreate(context) } request user permissions your application must request permission from the user to use their health data. create a set of permissions for the required data types. the permissions must match those you defined in the androidmanifest.xml file. val permissions = setof( healthpermission.getwritepermission(sleepsessionrecord::class), healthpermission.getreadpermission(sleepsessionrecord::class), ) check whether the user has granted the required permissions: suspend fun hasallpermissions(): boolean { if (healthconnectclient.sdkstatus(context) != healthconnectclient.sdk_available) { return false } return healthconnectclient.permissioncontroller.getgrantedpermissions() .containsall(permissions) } if not, launch the permission request: if (!healthconnectmanager.hasallpermissions()) { requestpermissions.launch(healthconnectmanager.permissions) } create the permissions prompt: private fun createrequestpermissionsobject() { requestpermissions = registerforactivityresult(healthconnectmanager.requestpermissionactivitycontract) { granted -> lifecyclescope.launch { if (granted.isnotempty() && healthconnectmanager.hasallpermissions()) { runonuithread { toast.maketext( this@mainmenuactivity, r.string.permission_granted, toast.length_short, ) .show() } } else { runonuithread { alertdialog.builder(this@mainmenuactivity) .setmessage(r.string.permissions_not_granted) .setpositivebutton(r.string.ok, null) .show() } } } } } retrieve sleep data from health connect in the sample application, to display sleep data, select a date and tap read data. a list of sleep sessions for that day is displayed. when you select a session, the application retrieves and displays its sleep stage information from health connect. to retrieve and display sleep session data: define the desired time range and send it to health connect manager. since a sleep session can start on the day before the selected date, be sure the application also retrieves sleep sessions from the previous day and later ignores the sessions that do not match the desired time range. val starttime = chosenday.minusdays(1).atstartofday(zoneid.systemdefault()).toinstant() val endtime = starttime.plus(2, chronounit.days).minus(1, chronounit.millis) val sleepsessions = healthconnectmanager.readsleepsessionrecords( starttime, endtime, ) retrieve the list of sleep session records in health connect manager. create a readrecordsrequest object and send it to health connect: val request = readrecordsrequest( recordtype = sleepsessionrecord::class, timerangefilter = timerangefilter.between(start, end), ) val response = healthconnectclient.readrecords(request) return response.records display the records in a listview on the application screen: for (session in sleepsessions) { sleepsessionranges.add(timerange.between(session.starttime, session.endtime)) val sessionstart = session.starttime.atzone(zoneid.systemdefault()).format( datetimeformatter.iso_local_time, ) val sessionend = session.endtime.atzone(zoneid.systemdefault()).format( datetimeformatter.iso_local_time, ) sleepstageslists.add(session.stages) sleepsessionsadapter.add("start: $sessionstart\t\tend: $sessionend gmt ${session.startzoneoffset}") } when a session is selected, display its sleep stage details: for (stage in sleepstageslists[sleepsessionindex]) { val stagestart = stage.starttime.atzone(zoneid.systemdefault()).format( datetimeformatter.iso_local_time, ) val stageend = stage.endtime.atzone(zoneid.systemdefault()).format( datetimeformatter.iso_local_time, ) val stagename = healthconnectmanager.enumtostagemap.getvalue(stage.stage) sleepstagesadapter.add("$stagestart\t-\t$stageend\t\t$stagename") } notealthough data is inserted to and stored in health connect in utc time with time zone offset, data retrieved from health connect is displayed in local time. you can extract health connect sleep data from any source, including data from galaxy watch. the following figure shows a sleep session in samsung health and the same data presented in the sample application. sleep data in samsung health and sample application create and insert sleep session data health connect not only allows you to read sleep data that is collected through samsung health, it also enables you to manually insert sleep data that can be synchronized to samsung health. to manually insert sleep data to health connect, you must prepare both a sleep session and sleep stage data. a session is a time interval during which a user performs an activity, such as sleeping. to prepare a session, you need to know its start and end time. in the sample application, an optional time zone offset is also implemented, since data in health connect database is stored in utc. if the session start hour and minute is later than the end hour and minute, the session is interpreted as starting on the previous day. in the following figure, the session is interpreted to have started at 22:00 on 2023-12-10 and ended at 06:00 on 2023-12-11. sleep session duration in the following part of the application, sleep stages can be added within the sleep session. to add a sleep stage, define its start time, end time, and name. for compatibility with samsung health, use the sleep stage names awake, light, rem, and deep. each defined sleep stage is visible in the list. ideally, sleep stages cover the entire sleep session, but this is not a requirement for synchronizing with samsung health. sleep stage creation to create and add a sleep session to health connect: check that the user has granted the necessary permissions: if (!healthconnectmanager.hasallpermissions()) { showdialoginfo(r.string.permissions_not_granted_api_call) return@launch } define the sleep session start and end time: val starttime = sleepsessiontimerange.startdatetimemillis val endtime = sleepsessiontimerange.enddatetimemillis val timezoneoffset = dateofsleepend.offset to add sleep stage data to the session, create a sleepstage record for each stage var sleepstageslist: arraylist<sleepsessionrecord.stage> val sleepstage = sleepsessionrecord.stage( starttime = sleepstagestart, endtime = sleepstageend, stage = healthconnectmanager.stagetoenummap.getvalue( activitysleepstagesbinding.spinstage.selecteditem.tostring(), ), ) sleepstageslist.add(sleepstage) in health connect manager, create a sleep session record and include the sleep stage list: suspend fun insertsleepsessionrecord( sleepstarttime: instant, sleependtime: instant, timezoneoffset: zoneoffset, stages: arraylist<sleepsessionrecord.stage>, ): boolean { var wasinsertsuccessful = false try { val sleepsessionrecord = sleepsessionrecord( sleepstarttime, timezoneoffset, sleependtime, timezoneoffset, "sleep record sample", "this is a sleep record sample recorded by sleeprecorder app", stages, ) insert the sleep session record into health connect: var wasinsertsuccessful = false try { wasinsertsuccessful = healthconnectclient.insertrecords(listof(sleepsessionrecord)).recordidslist.isnotempty() } catch (e: exception) { log.i(app_tag, "error inserting record: " + e.message) } the sleep session is now in health connect and visible in samsung health after data synchronization. in samsung health, go to the “sleep” screen. the inserted sleep session can be reviewed there with visualizations and analysis just like any other sleep session, such as those tracked on a galaxy watch. below is a sleep session from the sample application: sleep session conclusion this blog has demonstrated how you can develop an application that retrieves data from and inserts data into health connect, making it visible in the samsung health application after data synchronization.
Jan 22, 2024
Learn Code Lab
codelabcreate a daily step counter on galaxy watch objective create a native app for galaxy watch, operating on wear os powered by samsung, using health platform to read your daily steps overview health platform provides a unified and straightforward way for accessing a wide range of health and wellness related data with health platform api, you may easily read and write data stored in health platform on android and wear os powered by samsung applications can have access to these secured data only with explicit user consent additionally, users may disable access to the data at any point in time see health platform descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android studio latest version recommended java se development kit jdk 11 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! health step count sample code 119 87 kb 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 will display as on the image below afterwards, developer options will be visible under settings tap developer options and enable the following options adb debugging debug over wi-fi turn off automatic wi-fi connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that wi-fi is enabled from the list of available wi-fi networks, choose and connect to the same one as your pc when successfully connected, tap a wi-fi network name, swipe down, and note the ip address you will need this to connect your watch over adb from your pc connect your galaxy watch to android studio in android studio, go to terminal and type adb connect <ip address as mentioned in previous step> when prompted, tap always allow from this computer to allow debugging upon successful connection, you will see the following message in android studio’s terminal connected to <ip address of your watch> now, you can run the app directly on your watch start your project after downloading the sample code containing the project files, in android studio click open to open existing project locate the downloaded android project stepcount from the directory and click ok check dependency and app manifest in the dependencies section of stepcount/app/build gradle file, see the appropriate dependency for health platform dependencies { implementation com google android libraries healthdata health-data-api 1 0 0-alpha01' // } notelibrary might update from time to time if necessary, choose the version suggested by android studio request for data permissions before accessing any data through health platform, the client app must obtain necessary permissions from the user in permissions java, create a permission instance to trigger relevant permission screen and obtain required consent from end user data type name intervaldatatypes steps read access accesstype read /******************************************************************************************* * [practice 1] build permission object grand permissions for read today's steps * - set interval data type of steps * - set read access type ------------------------------------------------------------------------------------------- * - hint uncomment lines below and fill todos with * 1 for interval data type intervaldatatypes steps * 2 for read access accesstype read ******************************************************************************************/ permission stepsreadpermission = permission builder // setdatatype "todo 1 1 " // setaccesstype "todo 1 2 " build ; make a query to aggregate today’s steps create read request with all necessary information to read data through health platform api the answer from the platform will be asynchronous with the result from which you can get all the data you are interested in follow the steps below to get today's steps count in stepsreader java, create a readaggregateddatarequest with cumulativeaggregationspec instance data type name intervaldatatypes steps /******************************************************************************************* * [practice 2] build read aggregated data request object for read today's steps * - set interval data type of steps ------------------------------------------------------------------------------------------- * - hint uncomment line below and fill todo 2 with * 1 for interval data type intervaldatatypes steps ******************************************************************************************/ readaggregateddatarequest readaggregateddatarequest = readaggregateddatarequest builder settimespec timespec builder setstartlocaldatetime localdatetime now with localtime midnight build // addcumulativeaggregationspec cumulativeaggregationspec builder "todo 2 1 " build build ; read cumulative steps count from cumulativedata set variable steps value to 0l it is the count of daily steps get aggregatedvalue object using cumulativedata api cumulativedataaggregateddata representing total of intervaldata over a period of time e g total steps in a day public aggregatedvalue gettotal check the result if it is not null, get aggregated value using aggregatedvalue api aggregatedvaluevalue fields aggregated over a period of time only numeric fields longfield, doublefield can be included in aggregation public long getlongvalue returns all longfields and their values that are already set add value to the daily steps result counter /******************************************************************************************* * [practice 3] read aggregated value from cumulative data and add them to the result * - get aggregatedvalue from cumulativedata object * - get steps count from aggregatedvalue object ------------------------------------------------------------------------------------------- * - hint uncomment lines below and replace todo 3 with parts of code * 1 get aggregatedvalue object 'obj' using cumulativedata gettotal * 2 get value using obj getlongvalue and add to the result ******************************************************************************************/ long steps = 0l; if result != null { list<cumulativedata> cumulativedatalist = result getcumulativedatalist ; if !cumulativedatalist isempty { for cumulativedata cumulativedata cumulativedatalist { //"todo 3 1 " //"todo 3 2 " } } } return steps; run unit tests for your convenience, you will find an additional unit tests package this will let you verify your code changes even without using a physical watch see instruction below on how to run unit tests right click on com samsung sdc21 stepcount test and execute run 'tests in 'com samsung sdc21 stepcount'' command if you completed all the tasks correctly, you will see all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to see real-life aggregated steps count measured by a smartwatch right after the app is started, it will request for the user permission allow the app to receive data of the activity afterwards, the application main screen will be shown it will automatically display today’s step count tap on refresh button to read current steps count from health platform you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a daily step counter app by yourself! if you're having trouble, you may download this file health step count complete code 119 79 kb learn more by going to health platform
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 213 7 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 will display as on the image below afterwards, developer options will 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 will 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 to use the app, you need to enable developer mode in the health platform on your watch go to settings > apps > health platform quickly tap health platform title for 10 times this enables developer mode and displays [dev mode] below the title to stop using developer mode, quickly tap health platform title for 10 times to disable it 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 will be 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 will find an additional unit tests package this will let 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 will 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 213 9 kb to learn more about samsung health, visit developer samsung com/health
Learn Code Lab
codelabmeasure blood oxygen level on galaxy watch objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung health sensor sdk to trigger and obtain blood oxygen level spo2 measurement results overview samsung health sensor sdk provides means of accessing and tracking health information contained in the health data storage its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor the latest bioactive sensor of galaxy watch runs powerful health sensors such as photoplethysmogram ppg , electrocardiogram ecg , bioelectrical impedance analysis bia , sweat loss, and spo2 see samsung health sensor sdk descriptions for detailed information set up your environment you will need the following galaxy watch4 or newer android studio latest version recommended java se development kit jdk 11 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! measuring blood oxygen level sample code 146 3 kb connect your galaxy watch to wi-fi go to settings > connection > wi-fi and make sure that 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 will display as on the image below afterwards, developer options will 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 will see the following message in android studio’s 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 on your watch go to settings > apps > health platform quickly tap health platform title for 10 times this enables developer mode and displays [dev mode] below the title to stop using developer mode, quickly tap health platform title for 10 times to disable it start your project in android studio, click open to open existing project locate the downloaded android project from the directory and click ok check capabilities for the device to track data with the samsung health sensor sdk, it must support a given tracker type – blood oxygen level to check this, get the list of available tracker types and verify that the tracker is on the list in the connectionmanager java file, navigate to the isspo2available function, use a provided healthtrackingservice object to create a healthtrackercapability instance, send it to the checkavailabletrackers function, and assign its result to the availabletrackers list gettrackingcapability returns a healthtrackercapability instance in the healthtrackingservice object healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype public healthtrackercapability gettrackingcapability provide a healthtrackercapability instance to get a supporting health tracker type list /****************************************************************************************** * [practice 1] check capabilities to confirm spo2 availability * * ---------------------------------------------------------------------------------------- * * hint replace todo 1 with java code * get healthtrackercapability object from healthtrackingservice * send the object to checkavailabletrackers ******************************************************************************************/ public boolean isspo2available healthtrackingservice healthtrackingservice { if healthtrackingservice == null return false; list<healthtrackertype> availabletrackers = null; //"todo 1" if availabletrackers == null return false; else return availabletrackers contains healthtrackertype spo2_on_demand ; } check connection error resolution using samsung health sensor sdk api, resolve any error when connecting to health tracking service in the connectionmanager java file, navigate to the processtrackerexception function, and check if the provided healthtrackerexception object has a resolution assign the result to hasresolution variable hasresolution function in the healthtrackerexception object checks if the api can fix the error healthtrackerexceptionhealthtrackerexception contains error codes and checks the error's resolution if there is a resolution, solving the error is available by calling resolve activity boolean hasresolution checks whether the given error has a resolution /******************************************************************************************* * [practice 2] resolve healthtrackerexception error * * ----------------------------------------------------------------------------------------- * * hint replace todo 2 with java code * call hasresolution on healthtrackerexception object ******************************************************************************************/ public void processtrackerexception healthtrackerexception e { boolean hasresolution = false; //"todo 2" if hasresolution e resolve callingactivity ; if e geterrorcode == healthtrackerexception old_platform_version || e geterrorcode == healthtrackerexception package_not_installed observerupdater getobserverupdater notifyconnectionobservers r string novalidhealthplatform ; else observerupdater getobserverupdater notifyconnectionobservers r string connectionerror ; log e tag, "could not connect to health tracking service " + e getmessage ; } initialize spo2 tracker before the measurement starts, initialize the spo2 tracker by obtaining the proper health tracker object in the spo2listener java file, navigate to the init function using the provided healthtrackingservice object, create an instance of the spo2 tracker and assign it to the spo2tracker object gethealthtracker with healthtrackertype spo2_on_demand as an argument will create a healthtracker instance healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype healthtracker gethealthtracker healthtrackertype healthtrackertype provides a healthtracker instance for the given healthtrackertype /******************************************************************************************* * [practice 3] initialize spo2 tracker * * ---------------------------------------------------------------------------------------- * * hint replace todo 3 with java code * initialize spo2tracker with proper samsung health sensor sdk functionality * call gethealthtracker on healthtrackingservice object * use healthtrackertype spo2_on_demand as an argument ******************************************************************************************/ void init healthtrackingservice healthtrackingservice { //"todo 3" } perform measurement for the client app to start obtaining the data through the sdk, it has to set a listener method on the healthtracker the application setups the listener when the user taps on the measure button each time there is new data, the listener callback receives it after the measurement is completed, the listener has to be disconnected due to battery drain, on-demand measurement should not last more than 30 seconds the measurement is cancelled if the final value is not delivered in time note that the sensor needs a few seconds to warm up and provide correct values, which adds to the overall measurement time the blood oxygen level values come in the ondatareceived callback of trackereventlistener in spo2listener java file, you can see the code for reading the value private final healthtracker trackereventlistener spo2listener = new healthtracker trackereventlistener { @override public void ondatareceived @nonnull list<datapoint> list { for datapoint data list { updatespo2 data ; } } }; private void updatespo2 datapoint data { int status = data getvalue valuekey spo2set status ; int spo2value = 0; if status == measurement_completed spo2value = data getvalue valuekey spo2set spo2 ; observerupdater getobserverupdater notifytrackerobservers status, spo2value ; } 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 see instructions below on how to run unit tests right click on com samsung health spo2tracking test and execute run 'tests in 'com samsung health spo2tracking'' command if you completed all the tasks correctly, you can see that all the unit tests passed successfully run the app after building the apk, you can run the application on a connected device to measure blood oxygen level right after the app is started, it requests for user permission allow the app to receive data from the body sensors afterwards, it shows the application's main screen to get the blood oxygen level, tap on the measure button to stop the measurement, tap on the stop button you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a health app that measures blood oxygen level by yourself! if you're having trouble, you may download this file measuring blood oxygen level complete code 146 2 kb to learn more about samsung health, visit developer samsung com/health
Learn Code Lab
codelabmeasure skin temperature on galaxy watch objective create a health app for galaxy watch, operating on wear os powered by samsung, utilizing samsung health sensor sdk to obtain skin temperature measurement results overview samsung health sensor sdk provides means of accessing and tracking health information contained in the health data storage its tracking service gives raw and processed sensor data such as accelerometer and body composition data sent by the samsung bioactive sensor the active sensor of galaxy watch runs powerful health sensors such as photoplethysmogram ppg , electrocardiogram ecg , bioelectrical impedance analysis bia , sweat loss, and spo2 see samsung health sensor sdk descriptions for detailed information set up your environment you will need the following galaxy watch5 or newer with updated health platform 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! skin temperature tracking sample code 148 0 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 will display as on the image below afterwards, developer options will be visible under settings tap developer options and enable the following options adb debugging in developer options, search for 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 will see the following message in android studio’s 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 on your watch go to settings > apps > health platform quickly tap health platform title for 10 times this enables developer mode and displays [dev mode] below the title to stop using developer mode, quickly tap health platform title for 10 times to disable it start your project in android studio and click open to open an existing project locate the downloaded android project skintemptracking from the directory and click ok check tracking capabilities to track the data with the sdk, the device must support skin temperature, like the galaxy watch5 skin temperature tracking can work in 2 modes batching and on-demand the tracker type for batching is healthtrackertype skin_temperature_continuous and healthtrackertype skin_temperature_on_demand for on-demand in this code lab, you are going to use on-demand tracker in connectionmanager java, navigate to isskintemperatureavailable function use a provided healthtrackingservice object to create a healthtrackercapability instance, and send it to checkavailabletrackers function, and assign its result to availabletrackers list gettrackingcapability returns a healthtrackercapability instance in healthtrackingservice object healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype public healthtrackercapability gettrackingcapability provide a healthtrackercapability instance to get a supporting healthtrackertype list /****************************************************************************************** * [practice 1] check capabilities to confirm skin temperature availability * * ---------------------------------------------------------------------------------------- * * hint replace todo 1 with java code * get healthtrackercapability object from healthtrackingservice * send the object to checkavailabletrackers ******************************************************************************************/ boolean isskintemperatureavailable healthtrackingservice healthtrackingservice { if healthtrackingservice == null return false; @suppresswarnings "unusedassignment" list<healthtrackertype> availabletrackers = null; //"todo 1" if availabletrackers == null return false; else return availabletrackers contains healthtrackertype skin_temperature ; } initialization of skin temperature tracker before starting the measurement, initialize the skin temperature tracker by creating a healthtracker object in skintemperaturelistener java, navigate to setskintemperaturetracker using the provided healthtrackingservice object, create an instance of the healthtracker class of skin_temperature_on_demand type and assign it to the skintemperaturetracker object gethealthtracker with healthtrackertype skin_temperature_on_demand as an argument creates a healthtracker instance after a single measurement, the tracker should be stopped when using on-demand measurement for continuous measurement, use healthtrackertype skin_temperature_continuous healthtrackingservicehealthtrackingservice initiates a connection to samsung's health tracking service and provides a healthtracker instance to track a healthtrackertype healthtracker gethealthtracker healthtrackertype healthtrackertype create a healthtracker instance for the given healthtrackertype /******************************************************************************************* * [practice 2] setup skin temperature tracker * * ---------------------------------------------------------------------------------------- * * hint replace todo 2 with java code * initialize skintemperaturetracker with proper samsung health sensor sdk functionality * call gethealthtracker on healthtrackingservice object * use healthtrackertype skin_temperature_on_demand as an argument ******************************************************************************************/ void setskintemperaturetracker healthtrackingservice healthtrackingservice { //"todo 2" } starting and stopping the tracker for the client app to obtain the data through the sdk, set a listener method on healthtracker this method is called every time there is new data healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype public void seteventlistener healthtracker trackereventlistener listener set an event listener to the healthtracker instance void starttracker { if !ishandlerrunning { skintemperaturehandler post -> skintemperaturetracker seteventlistener skintemperaturelistener ; ishandlerrunning = true; } } after the finished measurement, the on-demand tracker should be stopped you can do that by unsetting the event listener from healthtracker healthtrackerhealthtracker enables an application to set an event listener and get tracking data for a specific healthtrackertype public void unseteventlistener stop the registered event listener to this healthtracker instance void stoptracker { if skintemperaturetracker != null skintemperaturetracker unseteventlistener ; skintemperaturehandler removecallbacksandmessages null ; ishandlerrunning = false; } process obtained skin temperature data the answer from the healthtrackingservice is asynchronous the skintemperaturelistener receives the callback containing a data point with all the required information follow the steps below to get skin temperature data in skintemperaturelistener java, go to the updateskintemperature function and read skin temperature data from datapoint get skin temperature status using datapoint api key valuekey skintemperatureset status get skin temperature value using datapoint api key valuekey skintemperatureset object_temperature get ambient temperature value using datapoint api key valuekey skintemperatureset ambient_temperature datapointdatapoint provides a map of valuekey and value with a timestamp public <t>t getvalue valuekey<t>type get data value for the given key private final healthtracker trackereventlistener skintemperaturelistener = new healthtracker trackereventlistener { @override public void ondatareceived @nonnull list<datapoint> list { stoptracker ; for datapoint data list { updateskintemperature data ; } } }; /******************************************************************************************* * [practice 3] read values from datapoint object * - get skin temperature status value * - get wrist skin temperature value - it's named "object_temperature" in the library * - get ambient temperature value ------------------------------------------------------------------------------------------- * - hint replace todo 3 with parts of code * 1 remove skintemperaturestatus invalid_measurement and * set status from 'datapoint' object using data getvalue valuekey skintemperatureset status * * if status is 'skintemperaturestatus successful_measurement' then * 2 set wristskintemperaturevalue from 'datapoint' object using * data getvalue valuekey skintemperatureset object_temperature ; * 3 set ambienttemperaturevalue from 'datapoint' object using * data getvalue valuekey skintemperatureset ambient_temperature ; ******************************************************************************************/ void updateskintemperature datapoint data { final int status = skintemperaturestatus invalid_measurement; float wristskintemperaturevalue = 0; float ambienttemperaturevalue = 0; //"todo 3" trackerdatasubject notifyskintemperaturetrackerobservers status, ambienttemperaturevalue, wristskintemperaturevalue ; } run unit tests for your convenience, you will find an additional unit tests package this will let you verify your code changes even without using a physical watch see the instruction below on how to run unit tests right click on com samsung health skintemptracking test and execute run 'tests in 'com samsung health skintemptrackin" command if you have completed all the tasks correctly, you can see all the unit tests pass successfully run the app after building the apk, you can run the application on a connected device to measure your skin temperature once the app starts, allow the app to receive data from the body sensors afterwards, the screen shows the application tap the measure button to get your skin temperature to stop measuring, tap on the stop button you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a health app that measures skin temperature by yourself! if you are having trouble, you may download this file skin temperature tracking complete project 147 8 kb to learn more about samsung health, visit developer samsung com/health
Preferences Submitted
You have successfully updated your cookie preferences.