Programming GuideApr 27, 2017

Overview

Samsung Digital Health SDK helps developers to synchronize health data with S Health 4.x safely and to create useful health applications. The health data store’s integrated health data in S Health can be shared with other S Health's partner applications based on user’s consent. S Health supports Android devices with KitKat 4.4 including non-Samsung devices.

Figure 1: Samsung Digital Health service

Refer to Table 1 for Samsung Health SDK glossary.

Term Description
Health Data framework It provides useful features to handle the user’s health data. It is included in Samsung Health and its interface is provided with Samsung Health SDK. An app that uses the SDK works with Samsung Health.
Samsung Health An application that helps monitor the user’s activities and helps the user makes a healthier life with monitoring walking steps, exercise, heart rate, and etc. It can be downloaded from the app market like Google Play or Galaxy Apps.
It’s marked with italic to distinguish easily.
Table 1: Glossary

The SDK provides the following packages.

  • Health Data

  • Health Service

This document contains descriptions for the SDK’s Health Data. See the Health Service’s documents if you want to launch one of Samsung Health trackers or post your app’s tracker on Samsung Health.

Health Data Framework

The health data framework of Samsung Health SDK provides the following features:

  • Health Data Store

    • Handling the connection to Samsung Health
    • Inserting, reading, updating, deleting health data
    • Based on unified units. See API Reference’s descriptions for each data type
  • Health Data Type

    • Platform-defined and custom data type
  • Privacy

    • Granting permission based on the user’s consent to read or write the specific data type
Architecture

The SDK’s health data framework is designed to provide safe access of health data and a seamless health service to the user. Figure 2 is the health data framework’s architecture.

Figure 2: Health data framework architecture

The detailed description is presented below.

Health Data Framework

The health data framework is included in Samsung Health. Applications can access the health data store’s data of Samsung Health with the SDK. It keeps the user’s health data safely. Health data from various source devices that have pedometer, accelerator, or heart rate sensors are inserted to the health data framework with the unified data unit. The data in health data framework can be read with the SDK. Updating or deleting data is available if the app inserted the data.

Partner Apps

The Samsung Health’s partner app indicates an application that uses Samsung Health SDK. It can synchronize health data with Samsung Health through the partner app approval. Create your app with Samsung Health SDK and send a request for the partner app. Your app’s data synchronization with Samsung Health should be work well before the partner app request. The SDK’s DataViewer tool can help the app test efficiently. The partner app request is available in the developer site.

Figure 3: Class diagram for HealthDataStore

Figure 3 shows the class and interface relationships in Health Data. Detailed descriptions for each class and interface are in the API Reference.

HealthDataService.initialize()

It initializes the health data service. APIs of the com.samsung.android.sdk.healthdata works properly after calling it without an exception.

HealthDataStore

It handles the connection to the data storage of the device. It receives its connection result with HealthDataStore.ConnectionListener. Most requests require the connection to the health data store.

HealthDataResolver

The health data framework provides classes and interfaces to insert, read, update, or delete health data. HealthDataResolver is a central class to handle health data. It sends a data request with related request interfaces.

The query result can be received immediately with HealthDataHolder.BaseResult, HealthDataResolver.ReadResult or HealthDataResolver.AggregateResult. Or it can be received asynchronously with HealthResultHolder.ResultListener. See 6.1 for more information.

Application developers can use platform-defined data types that Samsung Health SDK provides. See 6.2 for more information. Especially HealthConstants.Common contains the following mandatory properties for health data.

  • Unique ID of health data

  • Created and updated time of health data

  • Application package name

  • Device that provides health data

HealthConstants.Common is the base class of predefined data types of Samsung Health SDK as in Figure 4.

Figure 4: Class diagram for health data types

User’s health data can be accessed with the user’s consent. Figure 5 shows relationship between classes and interfaces related to HealthPermissionManager. It requests permissions with HealthPermissionManager.PermissionKey that contains the required permission to read or write for the specific health data type. The permission result can be received synchronous or asynchronously. See 6.3 for more information.

Figure 5: Class diagram related to HealthPermissionManager

The Health Data library of Samsung Health SDK provides the following package:

  • com.samsung.android.sdk.healthdata

Main interfaces and classes in the library are described in Table 2. See the API reference on details.

com.samsung.android.sdk.healthdata
Interface / Class Description
HealthConnectionErrorResult This class handles errors for connection failure to the health data store.
HealthConstants This class defines constants of health data and contains interfaces for various kinds of health data such as the step count or exercise.
HealthData This class is an object for a health data type, e.g., the blood pressure or weight. Quantitative and qualitative values can be specified for the specific health data type based on its data structure definition. It is used to manage health data with HealthDataResolver.
HealthDataObserver This class defines an observer to handle health data changes.
HealthDataResolver This class accesses health data to insert, read, update, and delete with the filter and aggregate functions.
HealthDataService This class initializes the health data service.
HealthDataStore This class handles the connection to the data store in the device.
HealthDataUnit This class provides unified units for the health data store.
HealthDevice This class contains detailed device information that provides health data.
HeatlthDeviceManager This class manages devices related health data.
HealthPermissionManager This class requests permission to read or write health data for the specific health data type.
HealthResultHolder This interface represents the result of invoking method.
HealthUserProfile This class provides user information.
Table 2: Interfaces and classes of com.samsung.android.sdk.healthdata

Development Environment

Check prerequisites first and follow all steps below to create a Samsung Health’s partner app.

Prerequisites

Check following prerequisites before downloading Samsung Health SDK.

Android Version

Android 4.4 KitKat (API level 19) or above

Available Devices

Android smartphones including non-Samsung devices

Samsung Health Version

A partner app runs with Samsung Health 4.0 or higher

Downloading Samsung Health SDK

Samsung Health SDK can be downloaded on the Samsung developer site. You can find the following content in the SDK’s Health Data.

Folder in SDK Description
Docs API Reference
Describes the SDK’s Health Data APIs
Programming Guide

Contains development information to create a Samsung Health’s partner app with Health Data
Libs samsung-health-data-va.b.c.jar
Health Data library of Samsung Health SDK
Samples SimpleHealth
Sample application that demonstrates how to use Samsung Health SDK

FoodNote
Sample application to check daily calorie intake
Tools DataViewer.apk
A test tool for the connection between your app and Samsung Health. It works on the Samsung Health’s developer mode. It reads Samsung Health‘s saved health data and write a test data to Samsung Health.
Table 3: Samsung Health SDK – Health Data

Development Process

If you checked prerequisites and downloaded the SDK, it’s ready to create your application. Make it with the following steps.

Samsung Health Branding Guidelines

Samsung Health SDK provides user interface guidelines for its partner applications to unify the entry point for the connection to Samsung Health and related interfaces. Read " Samsung Health Branding Guidelines" and apply them to your application. An application that doesn’t keep the guidelines can be rejected for the partner application.

Data Synchronization Design

The partner app of Samsung Health needs to synchronize health data with Samsung Health. The available data types are:

Samsung Health SDK enables your app to read Samsung Health’s data and write your app’s data to Samsung Health.

Main data types that represent your application should be contained for data integration. The synchronized data between your application and Samsung Health needs to give a natural flow to users. E.g. In case of the nutrition app, the user thinks food intake data would be shared with Samsung Health without doubt.

Creating an Application

Create an app project and complete your app. See hello health data for Samsung Health‘s partner apps first.

Testing Your Application

The app that uses the SDK works with Samsung Health after the partner app approval. It needs to be tested fully before applying for the partner app. The SDK provides the following environments.

  • Samsung Health‘s developer mode

  • SDK’s DataViewer

  • Checklist for Samsung Health’s partner app

You can apply for Samsung Health’s partner app before publishing your app. Otherwise the app publication can be first before applying for partner app. The former is proper to provide a seamless service of your app.

Note

Samsung Health SDK doesn’t support the Emulator test. Android 4.4 KitKat (API level 19) device or above is required to test your app.

Samsung Health’s Developer Mode

Samsung Health has the developer mode for the app test before the partner app approval. The Samsung Health’s developer mode is not activated by default. You can activate it with the following steps.

  1. Select the action overflow of Samsung Health on the top-right side.
  2. Find Settings < About Samsung Health in the action list.
  3. Tap the version region quickly for 10 times.
    The exact region, illustrated in the red and blue box in Figure 6 needs to be tapped.
  4. If it succeeds, "*(Developer Mode)*" is shown in front of the version and it means the developer mode is activated. Now you can test your app with Samsung Health.

Figure 6 shows how to turn on or off the developer mode in Samsung Health. If you tap the version region quickly for 10 times in the developer mode as the right figure, the developer mode is deactivated.

Figure 6: On or off of Samsung Health’s developer mode
DataViewer

DataViewer reads saved health data in Samsung Health and can create new test data for each data type. It works after the Samsung Health’s developer mode is active. See Data Viewer for more information.

Figure 7: DataViewer
Checklist for Samsung Health’s Partner App

Samsung Health SDK provides a checklist that includes basic test items for the app test. Download ithere and check your app before applying for partner app. It helps you save the time on the registration process for Samsung Health’s partner app.

Publishing Your Application

Your released app should run well even if it doesn’t become the Samsung Health’s partner app yet. Check connection error handling to the health data store of Samsung Health especially.

Registering for Partner Apps

The application works properly with Samsung Health after the partner app approval. Samsung Health team checks the app’s violations and registers your app as the Samsung Health’s partner because health data is closely connected to the privacy issue.

You can request for the partner application on the developer site .

Note

Only the approved partner app runs with Samsung Health. Otherwise the application can be run and tested on the developer mode.

DataViewer

DataViewer is a very useful tool to check save data to Samsung Health. You can find it in the downloaded SDK's /Data/Tools folder.

Prerequisites
  • Activate the Samsung Health’s developer mode.

  • Install DataViewer and open it.

DataViewer provides the SDK’s supported data type list and some useful menus. Figure 8 shows its main screen and menus.

Figure 8: DataViewer‘s main screen and menu
Checking Saved Data

You can check saved data in Samsung Health by selecting one of data types in Figure 9.

Saved data are listed up with its saved time after allowing the selected data type’s permission. Each data contains detailed information for the data type’s properties and you can see it by selecting one of data.

Data’s detailed information describes its measured time and value including common information such as its created time, the source app’s package name, and source device.

Checking saved data with DataViewer is the exact way to test your app when the app writes measured data to Samsung Health. Because some inserted data to Samsung Health cannot be shown on Samsung Health with its UI policy. Make sure if the following information is saved well especially:

  • Measured data value and its unit

  • "start_time" that indicates the measurement time and "time_offset"

  • Other interesting information

Figure 9: Checking saved step data in DataViewer
Adding New Data

You can add new data easily with DataViewer by selecting the “ADD” upper right button on the saved data list.

It is very helpful to test your app when it reads Samsung Health’s new data. Check your app after creating a new data with DataViewer with filling values of mandatory properties and saving it. Data’s mandatory properties are marked with 'not null'.

Connecting to Samsung Health

DataViewer handles Samsung Health’s all data types and each data type can be accessed after the data permission agreement. Whenever you select any data type on the main screen’s data list, the permission UI is popped up as the middle one of Figure 9 to allow only one data type’s permission.

If you want to allow access for several data types at once, use “Connect to Samsung Health” of DataViewer. It shows the permission UI pop-up that contains permission of all data types.

Exporting Data

DataViewer’s data can be exported to the csv file by selecting “Export Data” on the DataViewer’s main screen.

Showing on Tracker Tile

DataViewer has its tracker and its tracker tile can be posted on Samsung Health as other trackers. Interesting data type’s latest data displays on the posted tile by setting “Show on Tracker Tile” of DataViewer.

Figure 10: DataViewer’s tracker tile

Hello Health Data

The following sections give you fundamentals for developing the Samsung Health’s partner app. Check development environment for Samsung Health‘s partner apps first.

Importing Library

Add the following library to the “libs” folder in your created application project.

  • samsung-health-data-a.b.c.jar

Health Data Service Initialization

The health data service can be initialized with:

  • HealthDataService.initialize()

public class MainActivity extends Activity {

public static final String APP_TAG = "SimpleHealth";

private static MainActivity mInstance = null;
private HealthDataStore mStore;
private HealthConnectionErrorResult mConnError;
private Set<PermissionKey> mKeySet;

@Override
public void onCreate(Bundle savedInstanceState) {
	// ...

	mInstance = this;
	mKeySet = new HashSet<PermissionKey>();
	mKeySet.add(new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, PermissionType.READ));
	HealthDataService healthDataService = new HealthDataService();
	try {
		healthDataService.initialize(this);
	} catch (Exception e) {
		e.printStackTrace();
	}
Health Data Store Connection

If the health data service initialization succeeds, connect to the health data store with HealthDataStore.

// Create a HealthDataStore instance and set its listener
	mStore = new HealthDataStore(this, mConnectionListener);
	// Request the connection to the health data store
	mStore.connectService();
}

You can end the health data store connection when the activity is destroyed.

private final HealthDataStore.ConnectionListener mConnectionListener = new HealthDataStore.ConnectionListener() {

		@Override
		public void onConnected() {
			Log.d(APP_TAG, "Health data service is connected.");
			HealthPermissionManager pmsManager = new HealthPermissionManager(mStore);

			try {
				// Check whether the permissions that this application needs are acquired
				// Request the permission for reading step counts if it is not acquired

				// Get the current step count and display it if data permission is required
				// ...
			} catch (Exception e) {
				Log.e(APP_TAG, e.getClass().getName() + " - " + e.getMessage());
				Log.e(APP_TAG, "Permission setting fails.");
			}
		}

		@Override
		public void onConnectionFailed(HealthConnectionErrorResult error) {
			Log.d(APP_TAG, "Health data service is not available.");
			showConnectionFailureDialog(error);
		}

		@Override
		public void onDisconnected() {
			Log.d(APP_TAG, "Health data service is disconnected.");
		}
	};

The connection to the health data store can fail and you can check its error result in onConnectionFailed(). If there is an error, an application checks whether the health framework provides a solution with hasResolution() and calls resolve().

If the health framework provides its solution, resolve() makes an application move to one of the following page without a dialog message:

  • App market’sSamsung Health page to install or update it

  • Device’s Settings page to make Samsung Health available

  • Samsung Health s user’s agreement page

An application needs to show a proper message for each error case and call resolve().

private void showConnectionFailureDialog(HealthConnectionErrorResult error) {

	AlertDialog.Builder alert = new AlertDialog.Builder(this);
	mConnError = error;
	String message = "Connection with Samsung Health is not available";

	if (mConnError.hasResolution()) {
		switch(error.getErrorCode()) {
		case HealthConnectionErrorResult.PLATFORM_NOT_INSTALLED:
			message = "Please install Samsung Health";
			break;
		case HealthConnectionErrorResult.OLD_VERSION_PLATFORM:
			message = "Please upgrade Samsung Health";
			break;
		case HealthConnectionErrorResult.PLATFORM_DISABLED:
			message = "Please enable Samsung Health";
			break;
		case HealthConnectionErrorResult.USER_AGREEMENT_NEEDED:
			message = "Please agree with Samsung Health policy";
			break;
		default:
			message = "Please make Samsung Health available";
			break;
		}
	}

	alert.setMessage(message);

	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int id) {
			if (mConnError.hasResolution()) {
				mConnError.resolve(mInstance);
			}
		}
	});

	if (error.hasResolution()) {
		alert.setNegativeButton("Cancel", null);
	}

	alert.show();
}

See the health data store for more information.

Permission Request

The meta-data element for required data permission value in manifest works with the permission request API. If you want to request data permission for reading step count, write its value in your application project’s manifest as the following example.

The declared data permission in manifest is checked when Samsung Health is initialized. See privacy check flow in privacy.

<application

<meta-data
	android:name="com.samsung.android.health.permission.read"
	android:value="com.samsung.health.step_count" />

Create a permission key set and add a permission key for reading step count.

public class MainActivity extends Activity {

private Set<PermissionKey> mKeySet;

@Override
public void onCreate(Bundle savedInstanceState) {
	// ...

	mKeySet = new HashSet<PermissionKey>();
	mKeySet.add(new PermissionKey(HealthConstants.StepCount.HEALTH_DATA_TYPE, PermissionType.READ));
	HealthDataService healthDataService = new HealthDataService();

	// initialize and connect to health data store
}

And call HealthPermissionManager.requestPermissions() with its listener.

private final HealthDataStore.ConnectionListener mConnectionListener = new HealthDataStore.ConnectionListener() {

	@Override
	public void onConnected() {
		Log.d(APP_TAG, "Health data service is connected.");
		HealthPermissionManager pmsManager = new HealthPermissionManager(mStore);

		try {
			// Check whether the permissions that this application needs are acquired
			Map<PermissionKey, Boolean> resultMap = pmsManager.isPermissionAcquired(mKeySet);

			if (resultMap.containsValue(Boolean.FALSE)) {
				// Request the permission for reading step counts if it is not acquired
				pmsManager.requestPermissions(mKeySet, MainActivity.this).setResultListener(mPermissionListener);
			} else {
				// Get the current step count and display it
				// ...
			}
		} catch (Exception e) {
			Log.e(APP_TAG, e.getClass().getName() + " - " + e.getMessage());
			Log.e(APP_TAG, "Permission setting fails.");
		}
	}
	// ...
};

If requestPermissions() is called successfully, the permission UI is popped up to the user.

Figure 11: Permission UI for reading step count

User’s permission information is saved by selecting “DONE” after the user allows each data permission. And it is received through HealthResultHolder.ResultListener.

private final HealthResultHolder.ResultListener<PermissionResult> mPermissionListener =
	new HealthResultHolder.ResultListener<PermissionResult>() {

	@Override
	public void onResult(PermissionResult result) {
		Log.d(APP_TAG, "Permission callback is received.");
		Map<PermissionKey, Boolean> resultMap = result.getResultMap();

		if (resultMap.containsValue(Boolean.FALSE)) {
			// Requesting permission fails
		} else {
			// Get the current step count and display it
		}
	}
};
}

See the health permission manager for more information.

Health Data Features

Key features of Samsung Health SDK are:

  • Health data store

  • Health data types

  • Privacy

Health Data Store

Samsung Health SDK provides the health data store to access health data with the user’s consent. Data in the Samsung Health’s health data store can be shared with other partner apps also.

Figure 12: Samsung Health data store
Preparing Data Access

An application needs to initialize the health data service, connect to the health data store, and acquire data permission to access the health data store’s data. Figure 13 shows a basic flow and main APIs for working with Samsung Health.

Figure 13 Flow for data access

In the connection failure case, all exceptions should be handled clearly with a proper message to user. It helps to prevent unexpected operations on your application. For detailed code, see:

Health Data Query

HealthDataResolver helps to access the health data store’s data with APIs of Figure 14.

Figure 14: Health data query

All queries except inserting data can be requested with the filter to set the target range for a query. And a data query is sent asynchronously or synchronously.

Asynchronous query is used usually and you can select one of methods for your need. See the following examples for more information.

The query result is retrieved as Table 4.

Source / Resource Description
insert()
update()
delete()
BaseResult
read() ReadResult
aggregate() AggregateResult
Table 4: Data request and its result

See data query snippets in API Reference.

Filter

HealthDataResolver.Filter is very useful to clear the data range for reading, updating, and aggregating health data. Multiple filters can be combined with:

  • and()

  • or()

See more descriptions in API Reference.

Data Normalization

The health data is stored based on the normalized unit as defined in International System of Unit (SI) in Table 5.

  • Item Unit
    Height cm
    Weight kg
    Temperature Celsius
    Blood glucose mmol/L
    Blood pressure mmHg
    HbA1c %
    SpO2 %
  • Calorie kcal
    Speed m/s
    Distance meter
    Time millisecond
    Water intake ml
    Caffeine intake mg
Table 5: International System of Unit

It enables your application to read health data without the specific unit. It means that you need to be careful to unify the data units when you insert health data to the health data store. HealthDataUnit helps to convert data value between units.

If there is no required unit in HealthDataUnit, you can define and register a new unit as the following example.

Health Data Type

Samsung Health SDK provides useful predefined and custom data types. The SDK’s predefined data types are in Table 6.

Name Description
HealthConstants.StepCount Accumulative step count.
HealthConstants.Exercise Whole workout that user does for enhancing fitness and health
HealthConstants.Sleep Information about user sleep
HealthConstants.SleepStage Sleep stage information for the specified sleep data
HealthConstants.FoodInfo Set of particular food information such as nutrition and calorie
HealthConstants.FoodIntake Records about how much user takes food and calories. Link to FoodInfo to show nutritional information on Samsung Health.
HealthConstants.CaffeinIntake Amount of caffeine intake
HealthConstants.WaterIntake Records about how much and many times user takes water
HealthConstants.Weight Historical records of user's weight
HealthConstants.HeartRate Measured heart rate values represented in beats per minute
HealthConstants.BodyTemperature Body temperature of user, known as normothermia or euthermia
HealthConstants.BloodPressure The pressure exerted by circulating blood upon walls of blood vessels
HealthConstants.BloodGlucose The amount of glucose (sugar) present in blood
HealthConstants.OxygenSaturation The oxygen saturation value of user
HealthConstants.HbA1c Glycated hemoglobin data
HealthConstants.Electrocardiogram Electrical activity of the heart
HealthConstants.AmbientTemperature Ambient temperature and humidity data around the device
HealthConstants.UvExposure Degree of exposure to ultraviolet(UV) radiated from the sun
HealthUserProfile Samsung Health’s user profile such as the date of birth or gender. It is provided with read-only.
Table 6: Predefined data types

And you can use daily step count trend if you need older data than one month as the custom data type.

All data types have the following mandatory properties in Table 7 and each data type’s detailed properties are written in the API Reference.

Property Description
UUID ID of health data.
Assigned by the system when new data is created in Samsung Health.
CREATED_TIME UTC time when data is created.
Assigned by the system when new data is created in Samsung Health.
UPDATED_TIME UTC time when data is updated.
Assigned by the system when new data is created in Samsung Health.
PACKAGE_NAME Application package name which provides data.
Assigned by the system when new data is created in Samsung Health.
DEVICE_UUID Device ID which provides health data
Table 7: Mandatory properties of health data

The manifest for the data type is composed of meta-data to present characteristics of the health data type. It is defined as the XML schema. Table 8 shows each element description for the manifest.

Element Description
<manifest> Base element for the data type. Its attributes are shown below.
  • "id"

    • Data type ID

  • "import"

    • Indicates another "id" of another manifest to extend

  • "version"

    • Indicates the version of the manifest. It’s numeric. If there are manifests with different version values, the higher version works.

<publisher>
  • "name": Name of publisher

<documentation> Documentation section defines informational text. It has the following sub elements.
  • <title>

  • <description>

<title> Title of the data type with the specific language code for localization. Its attribute is shown below.
  • "lang": It is composed of the following values. E.g. lang="en_US"

    • The language code with two-letter lowercase as defined by ISO 639-1.

    • The country code with two-letter uppercase as defined by ISO 3166-1.

The value of this element without the "lang" language attribute becomes the default title.
<description> Description for the data type. Its attribute is as follows.
  • "lang": It is composed of the following values. E.g. lang="en_US"

    • The language code with two-letter lowercase as defined by ISO 639-1.

    • The country code with two-letter uppercase as defined by ISO 3166-1.

The value of this element without the "lang" language attribute becomes the default title.
<visibility> Sharing scope of the data type. Its attribute is shown below.
  • "public"

    • "yes"(default) if the data type is shared to any application, or "no"

    • Specify <owner-app-list> as a sub element if it’s not public.

<owner-app-list> If the visibility is not public, you can list the allowed applications to access or extend this data type. It has a <package> sub element.
<package> Package name of the allowed application.
<policy> Data policy. Its attributes are shown below.
  • "lifetime": Data’s lifetime in months. E.g. lifetime="72" (it means 6 years.)

  • "measurement": Measurement type which is one of the following values.

    • "discrete" for discretely measured data without the end time.

    • "session" for measured data with the end time which has a session.

    • "no": Not measured data

  • "privacy": The privacy level which is one of the following values.

    • "insensitive": Data encryption is not required.

    • "sensitive": Data encryption is required. It’s the default value.

    • "medical": Data encryption and listing allowed countries with <medical-country> are required.

<medical-country> Need to write all allowed countries if the "privacy" attribute is "medical". It has the following attribute and allowed country code values.
  • "allowed"

    • "yes": If all allowed counties are written.

    • "no": If all prohibited countries are written.

  • Allowed or prohibited country codes with two-letter uppercase as defined by ISO 3166-1

    • Use comma "," as the delimiter between country codes.

    • E.g. <policy lifetime="72" measurement="discrete" privacy="medical"> <medical-country allowed="no"> AO, GB, IE</medical-country> </policy>

<property> Defines detailed information for each property of this data type including the default value, validation range, title and description. Its attributes are shown below.
  • "name"

  • "type"

    • One of "int", "long", "float", "double", "text", and "blob"

  • "mandatory"

    • The default value is "no".

    • "yes" if the property is a mandatory property for the data type. Be careful not to make the property as "yes" if you add a new property to update your application.

    • If the property is defined as mandatory, the value for the property has to be specified when new data is inserted.

  • "unique"

    • The default value is "no".

    • "yes" if the data value needs to be unique

<default-value> Default value of the property to be filled when a new health data is inserted without value specification
<validation> Validation range
  • "min"

    • The minimum value if the type is numeric

  • "max"

    • The maximum value if the type is numeric

  • "minLength"

    • The minimum length if the type is text

  • "maxLength"

    • The maximum length if the type is text

<documentation> Description for the property of the data type.
Table 8: Manifest definition

An example below shows the manifest definition for the health data type.

<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns="http://schemas.samsung.com/2014/10/iot"
          id="com.samsung.health.blood_glucose"
          version="1">
    <publisher name="Samsung Electronics Co., Ltd."/>
    <documentation>
        <title>Blood Glucose
        <title lang="es_US">Glucosa en la sangre
    </documentation>
    <visibility public="yes" />
    <policy lifetime="72" measurement="discrete" privacy="medical">
        <!-- AO (Angola), GB (United Kingdom), IE (Ireland), FR (France), NL (Netherland),
          BE (Belgium), LU (Luxembourg), AT (Austria), SK (Slovak), GR (Greece), CY (Cyprus),
          SI (Slovenia), DZ (Algeria), IR (Iran), CA (Canada), KR (Korea) --gt;
        <medical-country allowed="no">AO, GB, IE, FR, NL, BE, LU, AT, SK, GR, CY, SI, DZ, IR, CA, KR
    </policy>

    <property name="datauuid" mandatory="yes" type="text" unique="yes">
        <validation minLength="10" maxLength="36"/>
        <documentation>
            <title>Unique ID</title>
            <description>Unique ID</description>
        </documentation>
    </property>
    ...
    <property name="start_time" mandatory="yes" type="long">
        <documentation>
            <title>Start time</title>
            <description>When the measurement was taken</description>
        </documentation>
    </property>
    <property name="time_offset" mandatory="yes" type="long">
        <documentation>
            <title>Time offset<title>
            <description>Time zone in which data is entered</description>
        </documentation>
    </property>
    ...
</manifest>

Its detailed description is as follows.

  • Line 1: manifest schema version

  • Line 2: data type ID

  • Line 5-8: documentation for this data type

    • Line 6: data type name with the default language attribute
    • Line 7: data type name with the specific language attribute
  • Line 9: visibility of this data type

  • Line 10-16: data policy with its lifetime, measurement type, privacy level

    • Line 14: Prohibited country codes

  • Line 17-23: definition for one of properties

    • Line 17: Name, mandatory option, data type, and unique option for the property

    • Line 18: validation range of value

    • Line 19-22: Property description

Privacy

Privacy is a key for handling health data. Samsung Health SDK enables your application to access health data based on user’s consent. An application needs to declare proper permissions for handling required health data types and to handle SecureException when the application cannot gain user consent because user can withdraw consent at any time. See Permission Manager for permission declaration and request.

Samsung Health reads declared permissions of the application manifest file when it initialize and you can check them in Samsung Health > Settings > Data permissions > [App] as Figure 15.

On the other hand, an application needs to make a permission setting menu separately. The application calls a permission request API with required permission keys and the health data framework pops the permission UI up on the application. The flow can be preceded after user approves or denies the data type usage. User may change permission for each data type at any time.

In this time, items of the permission UI and Samsung Health’s setting menu can be different. Make same:

  • Declared permissions in manifest

  • Permission keys for the permission request API.

User consent is limited to the device. Even if multiple devices use the same Samsung account, the application has to acquire user consent on each device independently.

Figure 15: Privacy and user permission

Sample Application - SimpleHealth

The SDK’s Health Data provides a 'SimpleHealth' sample application to show how to read the today’s step count including its permission request. Check the sample application by importing its project with Android Studio (or Eclipse).

Prerequisites

Prerequisites to run SimpleHealth are:

  • Prepare an Android device that supports Android 4.4KitKat (API level 19) or above.
    (Samsung and non-Samsung devices are available both.)

  • Install latest Samsung Health.

  • Turn on the developer mode..

  • Import SimpleHealth with Android Studio (or Eclipse)

  • Run SimpleHealth on the device.

Overview

SimpleHealth demonstrates how to use Health Data’s APIs for retrieving the today’s step count with HealthConstants.StepCount health data and requesting permission.
Figure 16 shows its screenshots.

Figure 16: SimpleHealth

Especially, the health data store connection and exception handling would be helpful to your application to prepare unexpected error.

Table 9 describes source and resource files of SimpleHealth.

Source / Resource Description
AndroidManifest.xml Declaring required permissions with the element.
src/com/samsung/android/simplehealth
MainActivity.java SimpleHealth’s main activity.
  • Connecting to the health data store and handling exceptions through ConnectionListener
  • Checking permission to read HealthConstants.StepCount and requesting permission if required.
  • Creating an option menu for setting permission.
  • Showing today’s step count.
StepCountReporter.java
  • Reading today’s the total step count asynchronously.
  • Adding an observer to get notification for the step count‘s change.
Table 9: SimpleHealth’s source description

See detailed implementation in the imported SimpleHealth’s project through Android Studio (or Eclipse).

Sample Application - FoodNote

The SDK’s Health Data provides a 'FoodNote' sample application to show how to manage food intake data with Samsung Health including the permission request. Check the sample application by importing its project with Android Studio (or Eclipse).

Prerequisites

Prerequisites to run FoodNote are:

  • Prepare an Android device that supports Android 4.4KitKat (API level 19) or above.
    (Samsung and non-Samsung devices are available both.)

  • Install the latest Samsung Health.

  • Turn on the developer mode.

  • Import FoodNote with Android Studio (or Eclipse)

  • Run FoodNote on the device.

Overview

FoodNote demonstrates how to use Health Data’s APIs for checking the selected day’s calorie intake with HealthConstants.FoodIntake and HealthConstants.FoodInfo including permission request.
Figure 17 shows its screenshots.

Figure 17: FoodNote

Especially, the health data store connection and exception handling would be helpful to your application to prepare unexpected error.

Table 10 describes source and resource files of FoodNote.

Source / Resource Description
AndroidManifest.xml Declaring required permissions with the element.
src/com/samsung/android/simplehealth
AppConstants.java Getting the meal type name.
ChooseFoodActivity.java Loading the food list of the FoodInfoTable class and showing them that user can choose.
FoodDataHelper.java
  • Inserting food intake data
  • Deleting food intake data
  • Reading food intake data of the selected day and the meal type
FoodInfoTable.java Defining sample food information.
MainActivity.java
  • Connecting to the health data store and handling exceptions through ConnectionListener.
  • Checking permission for HealthConstants.FoodInfo and HealthConstants.FoodIntake, and requesting permission if required.
  • Creating an option menu for setting permission.
  • Showing the selected day’s calorie intake.
  • Adding an observer to get notification for the calories change.
MealStoreActivity.java
  • Showing a list of food intake items for the selected meal that is chosen on MainActivity.
  • Deleting a food intake item in the list.
Table 10: FoodNote’s source description

Copyright

Though every care has been taken to ensure the accuracy of this document, Samsung Electronics Co., Ltd. cannot accept responsibility for any errors or omissions or for any loss occurred to any person, whether legal or natural, from acting, or refraining from action, as a result of the information contained herein. Information in this document is subject to change at any time without obligation to notify any person of such changes.

Samsung Electronics Co. Ltd. may have patents or patent pending applications, trademarks copyrights or other intellectual property rights covering subject matter in this document. The furnishing of this document does not give the recipient or reader any license to these patents, trademarks copyrights or other intellectual property rights.

No part of this document may be communicated, distributed, reproduced or transmitted in any form or by any means, electronic or mechanical or otherwise, for any purpose, without the prior written permission of Samsung Electronics Co. Ltd.

The document is subject to revision without further notice.

All brand names and product names mentioned in this document are trademarks or registered trademarks of their respective owners.

For more information, please visit http://developer.samsung.com/