Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
Learn Code Lab
codelabestablish a health research system using samsung health research stack objective learn how to create a health research system that collects data from mobile and wearable devices and visualizes the collected data in a web portal using samsung health research stack overview samsung health research stack is an open-source toolset that helps collect and analyze data from devices in android and wear os environments it provides tools and infrastructure for developing and deploying health studies, ranging from medical research to clinician services and more the framework consists of four components backend services - offers api endpoints to access and interact with a robust data engine web portal - a customizable interface for creating surveys, managing team members, tracking subjects, and analyzing data app sdk - an sdk for building android and wear os apps capable of collecting data from wearable devices starter app - a health research app with mobile and wearable versions created using basic features provided by the app sdk for detailed information, see samsung health research stack set up your environment you will need the following android studio latest version recommended samsung galaxy mobile device with updated health connect app and samsung health app installed samsung galaxy watch synced to the mobile device docker desktop sample code to start your learning experience, download the project files of the samsung health research stack starter mobile and wearable app notedepending on your preferred development style, you can either download or clone the repository of the project files to your local computer feel free to edit and customize this project for your own purposes, including this code lab activity set up your galaxy mobile and watch device connect your galaxy mobile device to your pc and enable adb debugging next, connect your galaxy watch to android studio over wi-fi lastly, enable the developer mode of the health platform app on your watch by following these steps a go to settings b tap on apps c select health platform d quickly tap on health platform several times until [dev mode] appears notethe samsung health developer mode is only intended for testing or debugging your application it is not for application users deploy the backend and web portal locally download the backend-config-files zip file and unzip it the folder contains the docker-compose yaml file open the terminal window of docker desktop in the terminal, go to the directory where your docker-compose yaml file is located, and run the following command $ docker compose up –d the script deploys the backend and the web portal to your local computer, and it includes 6 services redis - redis watcher for the backend casbin service mongo - for saving data from the backend postgres - for supertokens database and the backend casbin database supertokens - for username and password authentication backend - backend for the samsung health research stack portal - web portal for the samsung health research stack you can change the port number, username, and password for each database with the default setting, you can access the web portal in your browser at localhost 80 the script file has simple settings for easy deployment to add more features, you can change the environment in the docker-compose yaml file's services > backend > environment part set the aws environment variables optional you can enable uploading and downloading features by setting the following aws environment variables aws_bucket_name aws_region aws_access_key_id aws_secret_access_key aws_session_token you can follow the instructions in using the default credential provider chain for setting up aws credentials set google openid connect optional to enable google openid connect oidc login, you can set the following environment variables oidc_google_oauth2_url default "https //oauth2 googleapis com" oidc_google_client_id oidc_google_client_secret oidc_google_redirect_uri you can refer to openid connect for more information about setting google oidc create a new study the health research system has two user groups investigators - conduct research studies and use the web portal for managing studies and analyzing data subjects - participate in studies by answering surveys and performing tasks through the mobile app, as well as collecting health data from wearable apps to start your research study, as an investigator, follow the steps below create an account and sign in to the web portal page you deployed fill out the form with your information on the study collection page, click the create study button noteall enrolled investigators can create a study the creator becomes the study admin in the basic info tab, input the details of the study 5 for the study scope, choose public noteyou can set the study scope as either public or private if you choose private, you need to input a participation code that subjects must enter into the mobile app to join however, for the ease of testing in this code lab, it is recommended to set the scope as public for the study requirements field, you can input any text and click next go to participation requirements tab and select the data types to collect in wear category for this code lab, choose wear accelerometer wear ecg wear heart rate the logo and title of the created study show on the study collection page connect the mobile app to backend system to connect the starter mobile app to the backend system, follow these steps noteto ensure that the galaxy mobile device can connect to the machine where the backend system is deployed, it is recommended to connect both the machine and the mobile device to the same network open the downloaded project file in android studio and go to samples > starter-mobile-app in the local properties file, set the server_address to the ip address of the machine where the backend system is deployed server_address ="input ip address here" tipyou can check your ip address using the command line windows in command prompt, type ipconfig and find the ip address under ipv4 address mac in terminal, type ifconfig and look for the ip address under inet next to en0 next, set the server_port to 50001 if you used the default values in the provided docker-compose yaml file for deployment if not, use the port number you set server_port=50001 set authentication method the app sdk supports three types of authentication methods for registration samsung utilizes samsung account cognito incorporates amazon cognito authentication super-tokens enables anonymous login to allow research participants to register and log in using their personal emails, set the sign_in_mode as super-tokens in the local properties file sign_in_mode="super-tokens" upload wearable data via grpc when synchronizing wearable device data, the app sdk offers two approaches utilizing grpc for high-performance remote procedure calls or synchronization through files each approach has advantages and disadvantages regarding factors such as battery life and server workload however, it is advisable to utilize grpc during local development to configure the mobile application to upload wearable data via grpc rather than files, add the following code in the local properties file enable_upload_wearble_data_by_file=false show the sync button in starter wearable app after configuring the mobile app, modify the wearable app to meet the requirements of your study go to samples > starter-wearable-app and open the local properties file the wearable app features a sync button, which can be displayed or hidden when this button is pressed, it synchronizes the collected data with the backend system instantly to show the sync button, set the value of enable_instant_sync_button as below enable_instant_sync_button=true notethis instant sync feature can negatively affect the battery consumption of both apps, so it is recommended to remove the sync button when you publish your app the samsung health research stack has an optimized data synchronization process that minimizes battery consumption set data measurement parameters you can customize the data collection and storage process of the wearable app by setting the values of the following data measurement parameters passive_data_insert_interval_in_seconds sets the data measurement buffer the buffer saves data in an in-memory database before the interval expires then, at regular intervals, the data from the buffer is stored in persistent memory data_split_interval_in_millis specifies the size of segmented data in persistent memory if these values are not specified, the wearable app uses its default values to verify that the data is being measured and synchronized instantly, you can set the values as follows passive_data_insert_interval_in_seconds=12 data_split_interval_in_millis=30000 run the starter mobile and wearable app after configuring the local properties of both starter apps, build and run your app in android studio by following these steps run the starter mobile app select your mobile app starter-mobile-app from the run configurations menu in the toolbar choose a connected galaxy mobile device as the target device for running the app click run to install the app after installation, clear the app's data run the starter mobile app follow the same steps as for the starter mobile app but select starter-wearable-app instead choose a connected galaxy watch device for running the app allow the app to access physical activity, sensor data, and send notifications when prompted ensure that the galaxy watch is connected with the galaxy mobile device register and join a study since you have set super-tokens as the authentication method, you can now register and log into the app at once open the starter mobile app and sign up with an unregistered email address after logging in and accepting permissions, the app displays the study you created from the web portal tap on the study card to view its details and click join study noteif a study is set to private and you wish to join it, press enter the study code located at the top of the screen and input the assigned participation code in the study code field agree to data collection and terms of research you can see that the sensor data to be collected are dependent upon the selection made in the web portal while creating the study sign and click next to complete the study onboarding process measure and collect health data in the starter wearable app, you can see a list of on-demand measurements that you can contribute to health research for this code lab, choose ecg and click measure follow the onscreen measurement instruction after measuring successfully, scroll to the bottom of the wearable app and press the sync button to synchronize the data with the mobile app in the mobile app, go to data tab, click the more button, and click sync to transfer the collected data to the web portal visualize the collected data in web portal you can display the collected data as a graph in any way you choose for further analysis of the study from the overview page of the study in the web portal, navigate to the dashboard page click on the add chart button provide a title for the chart and select the desired chart type then, edit the chart source choose the database where the data is stored for this code lab, enter the following query to display only the first ten heart rate data from wearheartrate table select * from wearheartrate limit 10 click run query and save select value and timestamp for the value and category columns respectively check the preview of the graph finally, click save to display the graph into the dashboard you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create your own health research system by yourself! to learn more, see samsung health research stack
Learn Code Lab
codelabbuild a health app with steps from samsung health and its connected wearables objective create a step counter application for android devices, utilizing the samsung health data sdk to read steps data collected by the samsung health app overview samsung health offers various features to monitor user health data such as their daily step activity with the samsung health data sdk, android applications can easily access collected data, including steps recorded over a specific period or from a certain device you can retrieve steps data collected by samsung health, obtain the total number of steps taken within the day, and the total number of steps per hour, and apply local time filters to refine your queries effectively set up your environment you will need the following android studio latest version recommended java se development kit jdk 17 or later android mobile device compatible with the latest samsung health version sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! health data steps sample code 573 9 kb set up your android device click on the following links to set up your android device enable developer options run apps on a hardware device activate samsung health's developer mode to enable the developer mode in the samsung health app, follow these steps go to settings > about samsung health then, tap the version number quickly 10 times or more if you are successful, the developer mode new button is shown tap developer mode new and choose on now, you can test your app with samsung health notethe samsung health developer mode is only intended for testing or debugging your application it is not for application users start your project in android studio click open to open existing project locate the downloaded android project mysteps from the directory and click ok check gradle settings before using the samsung health data sdk library, certain configurations are necessary these steps are already applied in the sample code provided the samsung-health-data-api-1 0 0b1 aar library is added to the app\libs folder, and included as a dependency in the module-level build gradle file in the same file, the gson library is also added as a dependency dependencies { implementation filetree mapof "dir" to "libs", "include" to listof "* aar" implementation libs gson } next, the kotlin-parcelize plugin is applied plugins { id "kotlin-parcelize" } lastly, the following entries are also added in the gradle > libs version toml file [versions] gson = "2 10 1" parcelize = “1 9 0” [libraries] gson = { module = "com google code gson gson", version ref = "gson" } [plugins] parcelize = { id = “org jetbrains kotlin plugin parcelize”, version ref = ”parcelize” } request steps data permissions noteyou can access data from samsung health by obtaining a healthdatastore object using the healthdataservice getstore appcontext method to read data from samsung health, you need to acquire proper permissions from the app user each health data type has its own permission additionally, separate permissions are required for reading and writing operations the user must grant the following permissions in the app steps for read operation steps_goal for read operation when launching the application, it is important to verify if the necessary permissions have already been granted this can be achieved through the library function healthdatastore getgrantedpermissions permissions set<permission> set<permission> go to app > kotlin+java > com samsung health mysteps domain in the arepermissionsgrantedusecase kt file, navigate to the permissions object and create the permissions needed to read the steps and steps goal data from samsung health /**************************************************************************** * [practice 1] create permission set to receive step data * * make permissions set down below contain two permission * com samsung android sdk health data permission permission objects of types * - 'datatypes steps' of 'accesstype read' * - 'datatypes steps_goal of 'accesstype read' ****************************************************************************/ object permissions { //todo 1 val permissions = emptyset<permission> } if the permissions are not granted, invoke an ask-for-permissions view the special function provided by the library is called from mainactivity, where the context is an activity's context val result = healthdatastore requestpermissions permissions, context after invoking the function, the app user sees the following pop-up upon starting the application if the user does not consent to read their steps data, the application displays a message explaining why this authorization is vital for the app to function properly notepermissions can be granted or revoked at any time by tapping the more button on the toolbar and selecting the connect to samsung health tab once the user grants the necessary permissions, you can proceed with retrieving the step data from the healthdatastore retrieve steps data from samsung health understand how to retrieve step goal a step goal is a target number of steps set by an individual to achieve within a day this can be set in the samsung health app by navigating to steps > settings > set target check the readlaststepgoal function in readstepgoalfromtodayusecase kt to know how to retrieve the most recent step goal from samsung health @throws healthdataexception class private suspend fun readlaststepgoal int { val startdate = localdate now val enddate = localdate now plusdays 1 log i tag, "startdate $startdate; enddate $enddate" val readrequest = datatype stepsgoaltype last requestbuilder setlocaldatefilter localdatefilter of startdate, enddate build val result = healthdatastore aggregatedata readrequest var stepgoal = 0 result datalist foreach { data -> log i tag, "step goal ${data value}" log i tag, "data starttime ${data starttime}" log i tag, "data endtime ${data endtime}" data value? let { stepgoal = it } } return stepgoal } the function readlaststepgoal retrieves the most recent step goal from samsung health first, it filters the data by setting the startdate and enddate to the current date and the next day respectively using a localdatefilter next, the function builds a request using the datatype stepsgoaltype last constant to retrieve the most recent value and specifies the date range using the setlocaldatefilter method the request is then executed by calling the aggregatedata function of the healthdatastore once the data is fetched, the function loops through each entry and extracts the step goal value finally, it returns the step goal value as the result collect today's total number of steps to verify if the user reached their daily step goal, get the number of steps taken from midnight until the current time perform this calculation by creating a generic function that calculates the total number of steps within a specified time frame then, set the start time as the beginning of today and the end time as the current timestamp total is an aggregate operation that obtains the sum of steps to achieve this task, use the following healthdatastore getgrantedpermissions permissions set<permission> set containsall elements collection<@unsafevariance e> aggregaterequest it represents a request for an aggregation query over time it is used to run aggregate operations like total and last for healthdatapoint localtimefilter filter with a localdatetime type time interval as a condition the time interval is represented as local date time companion function of starttime localdatetime?, endtime localdatetime? creates a localtimefilter with starttime and endtime aggregaterequest localtimebuilder<t> provides a convenient and safe way to set the fields and create an aggregaterequest setlocaltimefilter localtimefilter localtimefilter sets the local time filter of the request in readstepsfromatimerangeusecase kt, navigate to the function getaggregaterequestbuilder and filter today's steps /*************************************************************************** * [practice 2] - create a read request builder to obtain steps from given * time range * collecting steps from a period of time is an aggregate operation which * sums up all the steps from that period * in this exercise you need to * - create a localtimefilter with starttime and endtime for the * aggregaterequest * - apply the filter to the aggregaterequest * ------------------------------------------------------------------------- * - hint * use localtimefilter of to create a time filter for the request **************************************************************************/ fun getaggregaterequestbuilder starttime localdatetime, endtime localdatetime aggregaterequest<long> { val aggregaterequest = datatype stepstype total requestbuilder build // todo 2 return aggregaterequest } a list of aggregated data is received as a result of the request in this example, it's a single-item list containing the total number of steps taken from the beginning of the day to the present moment with the given code, you can iterate over the list and check if the value of the analyzed aggregateddata element is not null if so, assign it to the stepcount variable however, if the value is empty, the code returns a value of 0, indicating that no steps were recorded val result = healthdatastore aggregatedata aggregaterequest var stepcount = 0l result datalist foreach { aggregateddata -> aggregateddata value? let { stepcount = it } } obtain the number of steps for each hour after setting up the functions to fetch steps data from samsung health and aggregating the data to calculate the total step count, you need to obtain the total number of steps for each hour and visualize the steps the user took during every hour of the day to achieve this, utilize the aggregate operation sum of steps , but this time incorporate additional filtering grouping by hour aggregaterequest it represents a request for an aggregation query over time it is used to run aggregate operations like total and last on healthdatapoint localtimefilter filter with a localdatetime type time interval as a condition the time interval is represented as local date time companion function of starttime localdatetime?, endtime localdatetime? creates a localtimefilter with starttime and endtime localtimegroup grouped time interval with a pair of localtimegroupunit and multiplier this means that the grouping is applied to intervals as much as multiplier in local date and time companion function of timegroupunit localtimegroupunit, multiplier int creates a localtimegroup with the given timegroupunit and multiplier localtimebuilder<t> provides a convenient and safe way to set the fields and create an aggregaterequest setlocaltimefilterwithgroup localtimefilter localtimefilter?, localtimegroup localtimegroup? sets the local time filter with the local time group of the request in readgroupedstepsbytimerangeusecase kt, navigate to the getaggregaterequestbuilder function obtain the total number of steps from every hour by creating two variables one to specify the time range using localtimefilter of and another to define the grouping using localtimegroup of by combining these variables, you can set an aggregate request that retrieves the desired data /************************************************************************ * [practice 3] - create an aggregate request for steps from given period * of time * for this, datatype steps grouped by hour is needed * in this exercise you need to * - create an aggregate request, with grouping and time filters, * for filters' parameters use the method's arguments * - return the request * ---------------------------------------------------------------------- * - hint * use setlocaltimefilterwithgroup function to apply time and grouping * filters to the request builder ***********************************************************************/ fun getaggregaterequestbuilder startdatetime localdatetime, enddatetime localdatetime, localtimegroupunit localtimegroupunit, multiplier int aggregaterequest<long> { val aggregaterequest = datatype stepstype total requestbuilder build // todo 3 return aggregaterequest } to apply local time filtering with the given group, use the localtimefilter and localtimegroup classes the localtimegroup consists of a localtimegroupunit, which in this case is hourly, and a multiplier you can also group by other time periods such as daily, weekly, monthly, minutely, and yearly since you want data from every hour period, use a multiplier value of 1 the returned data from the request is a list, where each item represents a grouped value healthdatastore only returns values for periods when the step count is greater than zero the code below shows that by iterating over the returned datalist and adding non-null groupeddata to the output steplist, you can obtain the aggregated value of steps for each hour of the day val result = healthdatastore aggregatedata aggregaterequest val steplist arraylist<groupeddata> = arraylist result datalist foreach { aggregateddata -> var stepcount = 0l aggregateddata value? let { stepcount = it } val starttime = aggregateddata starttime atzone zoneid systemdefault val groupeddata = groupeddata stepcount, starttime tolocaldatetime steplist add groupeddata } noteevery usage of samsung health data sdk might throw a healthdataexception such exceptions are thrown from every backend function up the call stack and handled in viewmodel the healthdataexception has four possible subclasses an example is resolvableplatformexception, which means it can be automatically resolved by invoking resolvableplatformexception resolve activitycontext the reason for such an exception is, for instance, when samsung health app is not installed on the device resolving it results in opening samsung health page in the app store run unit tests for your convenience, an additional unit tests package is provided this package lets you verify your code changes even without using a physical device right-click on com samsung health mysteps test and select run 'tests in 'com samsung health mysteps' 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 app on a connected device to read your steps data once the app starts, allow all permissions to read steps data from samsung health and tap done afterwards, the app's main screen appears, displaying the daily summary of steps taken, target, and steps by hour swipe down to sync the latest data from samsung health you can scroll down to steps by hour to see the hourly breakdown you're done! congratulations! you have successfully achieved the goal of this code lab now, you can create a mobile health app that reads samsung health steps count data by yourself! if you are having trouble, you may download this file health data steps complete code 573 4 kb to learn more about samsung health, visit developer samsung com/health
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
These cookies gather information about your browser habits. They remember that you've visited our website and share this information with other organizations such as advertisers.
You have successfully updated your cookie preferences.