Create a Daily Step Counter on Galaxy Watch


Objective

Create a native app for Galaxy Watch4, 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 Watch4 Classic
  • 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
(120.48 KB)

Turn on Developer Mode and adjust its settings

  1. On your watch, go to Settings > About watch > Software and tap 5 times on Software version.

  2. Upon successful activation of Developer mode, a toast message is displayed as on the image below.

  3. Afterwards, Developer options will be visible under Settings.

  4. Tap Developer options and enable the following options:

    • ADB debugging

    • Debug over Wi-Fi

    • Turn off automatic Wi-Fi

Connect your watch to Wi-Fi

  1. Go to Settings > Connection > Wi-Fi and make sure that Wi-Fi is enabled.
  2. From the list of available Wi-Fi networks, choose and connect to the same one as your PC.
  3. 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 Watch4 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 will be able to 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'
	// ...
}

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.
CumulativeData

AggregatedData 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:
AggregatedValue

Value 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:

  1. Right click on com.samsung.sdc21.stepcount (test) and execute Run 'Tests in 'com.samsung.sdc21.stepcount'' command.

  1. If you completed all the tasks correctly, you will see all the unit tests passed successfully.

Run the app on Galaxy Watch4

After building the APK, you can run the application on a connected device to see real-life aggregated steps count measured by a smartwatch.

  1. Right after the app is started, it will request for the user permission. Allow the app to receive data of the activity.

  1. 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
(120.41 KB)

Learn more by going to Health Platform.