Huawei Health Kit Flutter Plugin


Contents


1. Introduction

HUAWEI Health Kit (Health Kit for short) allows ecosystem apps to access fitness and health data of users based on their HUAWEI ID and authorization. For consumers, Health Kit provides a mechanism for fitness and health data storage and sharing based on flexible authorization. For developers and partners, Health Kit provides a data platform and fitness and health open capabilities, so that they can build related apps and services based on a multitude of data types. Health Kit connects the hardware devices and ecosystem apps to provide consumers with health care, workout guidance, and ultimate service experience.

2. Installation Guide

Before you get started, you must register as a HUAWEI Developer and complete identity verification on the HUAWEI Developer website. For details, please refer to Register a HUAWEI ID.

Creating a Project in AppGallery Connect

Creating an app in the AppGallery Connect is required in order to communicate with the Huawei services. To create an app, perform the following steps:

Step 1. Sign in to AppGallery Connect and select My projects.

Step 2. Select your project from the project list or create a new one by clicking the Add Project button.

Step 3. Go to Project Setting > General information, and click Add app. If an app exists in the project and you need to add a new one, expand the app selection area on the top of the page and click Add app.

Step 4. On the Add app page, enter the app information, and click OK.

Configuring the Signing Certificate Fingerprint

A signing certificate fingerprint is used to verify the authenticity of an app when it attempts to access an HMS Core (APK) through the HMS SDK. Before using the HMS Core (APK), you must locally generate a signing certificate fingerprint and configure it in the AppGallery Connect. You can refer to 3rd and 4th steps of Generating a Signing Certificate codelab tutorial for the certificate generation. Perform the following steps after you have generated the certificate.

Step 1: Sign in to AppGallery Connect and select your project from My Projects. Then go to Project Setting > General information. In the App information field, click the add icon next to SHA-256 certificate fingerprint, and enter the obtained SHA-256 certificate fingerprint.

Step 2: After completing the configuration, click OK (Check mark icon) to save the changes.

Applying for the HUAWEI ID Service

HUAWEI Health Kit uses the HUAWEI ID Service in order the obtain the Health Kit permissions from the user. Head over to Huawei Developer Console and select the HUAWEI ID service from App Services under the Development Section. Click Apply for HUAWEI ID, agree to the agreement, and fill the information about your application for the required fields on the opened page. For details please visit Applying for the HUAWEI ID Service.

Note If the HUAWEI ID card can't be found, click Customize console in the upper right corner to add it.

Applying for the Health Kit

In order to successfully activate the Health Kit Service for your application you need to complete the steps in the Applying for Health Kit document. After the Health Kit Service is authorized and enabled for your application on the Huawei Developer Console you can continue with the integration process.

Integrating the Flutter Health Kit Plugin

Step 1: Sign in to AppGallery Connect and select your project from My Projects then navigate to Project Setting > General information page, under the App information field, click agconnect-services.json to download the configuration file.

Step 2: Copy the agconnect-services.json file to the android/app directory of your project.

Step 3: Open the build.gradle file in the android directory of your project.

  • Navigate to the buildscript section and configure the Maven repository address and agconnect plugin for the HMS SDK.

    buildscript {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    
      dependencies {
          /* 
          * <Other dependencies>
          */
          classpath 'com.huawei.agconnect:agcp:1.4.2.301'
      }
    }
    
  • Go to allprojects and configure the Maven repository address for the HMS SDK.

    allprojects {
      repositories {
          google()
          jcenter()
          maven { url 'https://developer.huawei.com/repo/' }
      }
    }
    

Step 5: Open the build.gradle file in the android/app/ directory.

  • Add apply plugin: 'com.huawei.agconnect' line after other apply entries.

    apply plugin: 'com.android.application'
    apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
    apply plugin: 'com.huawei.agconnect'
    
  • Set your package name in defaultConfig > applicationId and set minSdkVersion to 21 or higher. Package name must match with the package_name entry in the agconnect-services.json file.

    defaultConfig {
        applicationId "<package_name>"
        minSdkVersion 21
        /*
        * <Other configurations>
        */
    }
    

Step 6: Create a file <app_dir>/android/key.properties that contains a reference to your keystore which you generated on the previous step (Generating a Signing Certificate). Add the following lines to the key.properties file and change the values regarding to the keystore you've generated.

storePassword=<your_keystore_password>
keyPassword=<your_key_password>
keyAlias=<your_key_alias>
storeFile=<location of the keystore file, for example: D:\\Users\\<user_name>\\key.jks>

Warning: Keep this file private and don't include it on the public source control.

Step 7: Add the following code to the first line of android/app/build.gradle for reading the key.properties file:

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
    keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

Step 8: Edit buildTypes as follows and add the signingConfigs below:

signingConfigs {
    config {
        keyAlias keystoreProperties['keyAlias']
        keyPassword keystoreProperties['keyPassword']
        storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
        storePassword keystoreProperties['storePassword']
    }
}

buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {
        signingConfig signingConfigs.config
    }
}

Step 9: On your Flutter project directory, find and open your pubspec.yaml file and add the huawei_health library to dependencies. For more details please refer to the Using packages document.

  • To download the package from pub.dev.

      dependencies:
        huawei_health: {library version}
    

    or

    If you downloaded the package from the HUAWEI Developer website, specify the library path on your local device.

      dependencies:
        huawei_health:
            # Replace {library path} with actual library path of Huawei Health Kit Plugin for Flutter.
            path: {library path}
    
    • Replace {library path} with the actual library path of the Flutter Health Kit Plugin. The following are examples:
      • Relative path example: path: ../huawei_health
      • Absolute path example: path: D:\Projects\Libraries\huawei_health

Step 10: Run the following command to update the package info.

[project_path]> flutter pub get

Step 11: Import the library to access the methods.

import 'package:huawei_health/huawei_health.dart';

Step 12: Run the following command to start the app.

[project_path]> flutter run

3. API Reference

Overview

Detailed information about modules, classes and constants provided by this plugin is explained in this section. The summary is described in the table below.

NameDescription
ModulesFunction classes that provide interaction with the HUAWEI Health Kit SDK methods.
Option ClassesRequest object classes for CRUD operations.
Data ClassesDataset classes for interacting with the data provided by Health Kit.
Result ClassesResult classes for utilizing the Health Kit API results.
ConstantsConstants provided by the plugin.

Modules

Huawei Health Kit Plugin for Flutter provides a set of function classes as described in the table below.

NameDescription
HealthAuthProvides sign in method for obtaining the Health Kit Authorization from the user.
ActivityRecordsControllerProvides methods to create and manage user activity records.
AutoRecorderControllerProvides real-time data reading functions.
DataControllerProvides methods to add, delete, modify, and query the platform data.
SettingControllerProvides setting related functions.
ConsentsControllerProvides authorization management APIs that can be used to view and revoke the granted permissions.
HMSLoggerEnable/Disable functions for the HMSLogger.

HealthAuth

Provides signIn method for obtaining the Health Kit Authorization from the user.

Method Summary

MethodReturn TypeDescription
signInFuture<AuthHuaweiId>Obtains the Health Kit permissions from the user by the defined List of Scopes.

Methods

Future<AuthHuaweiId> signIn(List<Scope> scopes) async

Obtains the Health Kit permissions from the user by the defined List of Scopes. The scopes that are asked to the user for authorization should already be authorized for the app on Huawei Developer Console. Please see the Applying for the Health Kit section.

Parameters
ParameterTypeDescription
scopesList<Scope>List of Scopes to ask for authorization from the user.
Return Type
TypeDescription
Future<AuthHuaweiId>AuthHuaweiId object that contains the information about the user and granted Health Kit permissions.
Call Example
    // List of scopes to ask for authorization.
    //
    // Note: These scopes should also be authorized on the Huawei Developer Console.
    List<Scope> scopes = [
      Scope.HEALTHKIT_HEIGHTWEIGHT_READ,
      Scope.HEALTHKIT_HEIGHTWEIGHT_WRITE,
      Scope.HEALTHKIT_ACTIVITY_WRITE,
      Scope.HEALTHKIT_ACTIVITY_READ,
      Scope.HEALTHKIT_ACTIVITY_RECORD_WRITE,
      Scope.HEALTHKIT_ACTIVITY_RECORD_READ,
      Scope.HEALTHKIT_STEP_WRITE,
      Scope.HEALTHKIT_STEP_READ,
      Scope.HEALTHKIT_STEP_REALTIME,
      Scope.HEALTHKIT_CALORIES_READ,
      Scope.HEALTHKIT_CALORIES_WRITE
    ];
    
    AuthHuaweiId result = await HealthAuth.signIn(scopes);

ActivityRecordsController

Provides functions to create and manage user activities.

Method Summary

MethodReturn TypeDescription
addActivityRecordFuture<String>Inserts a specified activity record and corresponding data to the HUAWEI Health platform.
getActivityRecordFuture<List<ActivityRecord>>Reads ActivityRecord data from the HUAWEI Health platform.
beginActivityRecordFuture<void>Starts a new ActivityRecord for the current app.
endActivityRecordFuture<List<ActivityRecord>>Stops the ActivityRecord of a specific ID.
endAllActivityRecordsFuture<List<ActivityRecord>>Stops all the ongoing ActivityRecords.

Methods

Future<String> addActivityRecord(ActivityRecordInsertOptions activityRecordInsertOptions) async

Inserts a specified activity record and corresponding data to the HUAWEI Health platform.

Parameters
ParameterTypeDescription
activityRecordInsertOptionsActivityRecordInsertOptionsRequest parameter class for inserting an activity record, including the associated sampling dataset and sampling points to the platform.
Return Type
TypeDescription
Future<String>Result message.
Call Example
// Create start time that will be used to add activity record.
DateTime startTime = DateTime.now();

// Create end time that will be used to add activity record.
DateTime endTime = DateTime.now().add(Duration(hours: 2));

// Build an ActivityRecord object
ActivityRecord activityRecord = ActivityRecord(
  startTime: startTime,
  endTime: endTime,
  id: 'ActivityRecordRun1',
  name: 'BeginActivityRecordSteps',
  description: 'This is a test for ActivityRecord',
);
// Build the dataCollector object
DataCollector dataCollector = DataCollector(
dataGenerateType: DataGenerateType.DATA_TYPE_RAW,
  dataType: DataType.DT_CONTINUOUS_STEPS_DELTA,
  name: 'AddActivityRecord1');

// You can use sampleSets to add more sample points to the sampling dataset.
// Build a list of sampling point objects and add it to the sampling dataSet
List<SamplePoint> samplePoints = [
  SamplePoint(
    startTime: startTime,
    endTime: endTime,
    fieldValueOptions: FieldInt(Field.FIELD_STEPS_DELTA, 1024),
    timeUnit: TimeUnit.MILLISECONDS)
  ];
SampleSet sampleSet = SampleSet(dataCollector, samplePoints);

String result = await ActivityRecordsController.addActivityRecord(
  ActivityRecordInsertOptions(
    activityRecord: activityRecord, sampleSets: [sampleSet]),
  );
Future<List<ActivityRecord>> getActivityRecord(ActivityRecordReadOptions activityRecordReadOptions) async

Reads ActivityRecord data from the HUAWEI Health platform.

Parameters
ParameterTypeDescription
activityRecordReadOptionsActivityRecordReadOptionsDefines the activity record read options for an ActivityRecord read process.
Return Type
TypeDescription
Future<List<ActivityRecord>>Obtained ActivityRecord objects
Call Example
// Create start time that will be used to read activity record.
DateTime startTime = DateTime.now().subtract(Duration(days: 1));

// Create end time that will be used to read activity record.
DateTime endTime = DateTime.now().add(Duration(hours: 3));

ActivityRecordReadOptions activityRecordReadOptions =
  ActivityRecordReadOptions(
    startTime: startTime,
    endTime: endTime,
    timeUnit: TimeUnit.MILLISECONDS,
    dataType: DataType.DT_CONTINUOUS_STEPS_DELTA);

List<ActivityRecord> result =
  await ActivityRecordsController.getActivityRecord(activityRecordReadOptions);
Future<void> beginActivityRecord(ActivityRecord activityRecord) async

Starts a new activity record for the current app.

Parameters
ParameterTypeDescription
activityRecordActivityRecordActivityRecord object to be started.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
// Build an ActivityRecord object
ActivityRecord activityRecord = ActivityRecord(
  id: 'ActivityRecordRun0',
  name: 'BeginActivityRecord',
  description: 'This is ActivityRecord begin test!',
  activityTypeId: HiHealthActivities.running,
  startTime: DateTime.now().subtract(Duration(hours: 1)),
  );
await ActivityRecordsController.beginActivityRecord(activityRecord);
Future<List<ActivityRecord>> endActivityRecord(String activityRecordId) async

Stops the ActivityRecord with the specified id.

Parameters
ParameterTypeDescription
activityRecordIdStringId of the ActivityRecord to be stopped.
Return Type
TypeDescription
Future<List<ActivityRecord>>List of ActivityRecord objects that stopped.
Call Example
List<ActivityRecord> result =
  await ActivityRecordsController.endActivityRecord(
    'ActivityRecordRun0');
Future<List<ActivityRecord>> endAllActivityRecords() async

Ends all the ongoing activity records.

Return Type
TypeDescription
Future<List<ActivityRecord>>List of ActivityRecord objects that stopped.
Call Example
// Return the list of activity records that have stopped
List<ActivityRecord> result =
  await ActivityRecordsController.endAllActivityRecords();

AutoRecorderController

Provides the capabilities to read data in real time and cancel the reading.

Note: AutoRecorderController supports real-time data reading only for DataType.DT_CONTINUOUS_STEPS_TOTAL.

Method Summary

MethodReturn TypeDescription
startRecordFuture<void>Starts real-time data reading by specifying the data type.
stopRecordFuture<void>Stops the ongoing AutoRecorder service.
autoRecorderStreamStream<SamplePoint>Stream that emits SamplePoints objects after startRecord is activated.

Methods

Future<void> startRecord(DataType dataType, NotificationProperties notificationProperties) async

Starts real-time data reading by specifying the data type.

This method will trigger a foreground service that has an ongoing(sticky) notification. The notification properties can be customized by specifying a NotificationProperties instance. The SamplePoint results that include the count of steps are emitted to the autoRecorderStream.

If there is an ongoing AutoRecorder service present, an exception will be thrown.

Parameters
ParameterTypeDescription
dataTypeDataTypeData type specified for starting the real-time data reading.
notificationPropertiesNotificationPropertiesThe customization properties for the ongoing notification. Including but not limited to notification title, text, subtext.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await AutoRecorderController.startRecord(
  DataType.DT_CONTINUOUS_STEPS_TOTAL,
    NotificationProperties(
      title: "HMS Flutter Health Demo",
      text: "Counting steps",
      subText: "this is a subtext",
      showChronometer: true),
);
Future<void> stopRecord(DataType dataType) async

Stops the ongoing AutoRecorder service. If there is no ongoing AutoRecorder service this method will throw an exception.

Parameters
ParameterTypeDescription
dataTypeDataTypeData type specified for stopping the real-time data reading.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await AutoRecorderController.stopRecord(
  DataType.DT_CONTINUOUS_STEPS_TOTAL);
Stream<SamplePoint> get autoRecorderStream

Stream that emits SamplePoint objects after startRecord is activated.

Return Type
TypeDescription
Stream<SamplePoint>Listenable stream that emits SamplePoint objects.
Call Example
AutoRecorderController.autoRecorderStream.listen(_onAutoRecorderEvent);

void _onAutoRecorderEvent(SamplePoint res) {
  // Obtain the step values
  Map<String, dynamic> = res.fieldValues;
}

DataController

Determines the API for data management. The user can use this API to insert, delete, update, and read data, as well as query the data statistics of the current day and past days.

Method Summary

MethodReturn TypeDescription
initFuture<DataController>Initializes a DataController instance by a list of HiHealthOption objects that define data types and read/write permissions.
clearAllFuture<void>Clears all data inserted by the app from the device and the cloud.
deleteFuture<void>Deletes inserted sampling datasets by specifying a time range or deletes them all. It can also be used to delete workout records.
insertFuture<void>Inserts a sampling dataset into the Health platform.
readFuture<ReadReply>Reads user data.
readTodaySummationFuture<SampleSet>Reads the summary data of a specified data type of the current day.
readDailySummationFuture<SampleSet>Reads the daily statistics of a specified data type.
updateFuture<void>Updates existing data.

Methods

Future<DataController> init(List<HiHealthOption> hiHealthOptions) async

Initializes a DataController instance by a list of HiHealthOption objects that define data types and read/write permissions.

Parameters
ParameterTypeDescription
hiHealthOptionsList<HiHealthOption>List of HiHealthOption objects for specifying data types and permissions regarding those data types.
Return Type
TypeDescription
Future<DataController>a DataController instance.
Call Example
DataController dataController = await DataController.init(<HiHealthOption>[
  HiHealthOption(DataType.DT_CONTINUOUS_STEPS_DELTA, AccessType.read),
  HiHealthOption(DataType.DT_CONTINUOUS_STEPS_DELTA, AccessType.write),
]);
Future<void> clearAll() async

Clears all data inserted by the app from the device and the cloud.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await dataController.clearAll();
Future<void> delete(DeleteOptions options) async

Deletes inserted sampling datasets by specifying a time range or deletes them all. It can also be used to delete workout records.

Parameters
ParameterTypeDescription
optionsDeleteOptionsDeleteOptions object, used to specify the data collector, data type, and time range of data to be deleted.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
// Build the dataCollector object
DataCollector dataCollector = DataCollector(
  dataType: DataType.DT_CONTINUOUS_STEPS_DELTA,
  dataGenerateType: DataGenerateType.DATA_TYPE_RAW,
  dataStreamName: 'my_data_stream');

// Build the time range for the deletion: start time and end time.
DeleteOptions deleteOptions = DeleteOptions(
  dataCollectors: <DataCollector>[dataCollector],
  startTime: DateTime.parse('2020-10-10 08:00:00'),
  endTime: DateTime.parse('2020-10-10 12:30:00'));

// Call the method with the constructed DeleteOptions instance.
dataController.delete(deleteOptions);
Future<void> insert(SampleSet sampleSet) async

Inserts a sampling dataset into the Health platform.

Parameters
ParameterTypeDescription
sampleSetSampleSetSampling dataset to be inserted to the HUAWEI Health platform.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
// Build the dataCollector object
DataCollector dataCollector = DataCollector(
  dataType: DataType.DT_CONTINUOUS_STEPS_DELTA,
  dataStreamName: 'my_data_stream',
  dataGenerateType: DataGenerateType.DATA_TYPE_RAW);

// You can use sampleSets to add more sampling points to the sampling dataset.
SampleSet sampleSet = SampleSet(dataCollector, <SamplePoint>[
  SamplePoint(
    startTime: DateTime.parse('2020-10-10 12:00:00'),
    endTime: DateTime.parse('2020-10-10 12:12:00'),
    fieldValueOptions: FieldInt(Field.FIELD_STEPS_DELTA, 100))
]);

// Call the method with the constructed sample set.
dataController.insert(sampleSet);
Future<ReadReply> read(ReadOptions readOptions) async

Reads user data. You can read data by time, device, data collector, and more by specifying the related parameters in ReadOptions.

Parameters
ParameterTypeDescription
readOptionsReadOptionsReadOptions object, for specifying parameters in the data reading request. It is used to specify the data collector, data type, the time range for the requested data, and more.
Return Type
TypeDescription
Future<ReadReply>Read data. The start time or end time of the returned data points is within the specified time range.
Call Example
// Build the dataCollector object
DataCollector dataCollector = DataCollector(
  dataType: DataType.DT_CONTINUOUS_STEPS_DELTA,
  dataGenerateType: DataGenerateType.DATA_TYPE_RAW,
  dataStreamName: 'my_data_stream');

// Build the time range for the query: start time and end time.
ReadOptions readOptions = ReadOptions(
  dataCollectors: [dataCollector],
  startTime: DateTime.parse('2020-10-10 12:00:00'),
  endTime: DateTime.parse('2020-10-10 12:12:00'),
)..groupByTime(10000);

// Call the method with the constructed ReadOptions instance.
ReadReply readReply = await dataController.read(readOptions);
Future<SampleSet> readTodaySummation(DataType dataType) async

Reads the summary data of a specified data type of the current day. If the related data type does not support aggregation statistics, an exception will be thrown.

Parameters
ParameterTypeDescription
dataTypeDataTypeData type to be read.Currently, only the following data types are supported:
Calories: DataType.DT_CONTINUOUS_CALORIES_BURNT
Distance: DataType.DT_CONTINUOUS_DISTANCE_DELTA
Heart rate: DataType.DT_INSTANTANEOUS_HEART_RATE
Incremental step count: DataType.DT_CONTINUOUS_STEPS_DELTA
Weight: DataType.DT_INSTANTANEOUS_BODY_WEIGHT
Sleep: DataType.DT_CONTINUOUS_SLEEP
Stress: DataType.DT_INSTANTANEOUS_STRESS
Return Type
TypeDescription
Future<SampleSet>The statistical value of the data type. Calculation will be performed on all the queried data points with the start time or end time being in the specified time range, and the statistical results will be returned.
Call Example
SampleSet sampleSet = await _dataController
  .readTodaySummation(DataType.DT_CONTINUOUS_STEPS_DELTA);
Future<SampleSet> readDailySummation(DataType dataType, int startTime, int endTime) async

Reads the daily statistics of a specified data type. You can set the data type, start time, and end time to read the daily statistics in the specified period. If the related data type does not support aggregation statistics, an exception will be thrown.

Parameters
ParameterTypeDescription
dataTypeDataTypeData type to be read. Currently, only the following data types are supported:
Calories: DataType.DT_CONTINUOUS_CALORIES_BURNT
Distance: DataType.DT_CONTINUOUS_DISTANCE_DELTA
Heart rate: DataType.DT_INSTANTANEOUS_HEART_RATE
Incremental step count: DataType.DT_CONTINUOUS_STEPS_DELTA
Weight: DataType.DT_INSTANTANEOUS_BODY_WEIGHT
Sleep: DataType.DT_CONTINUOUS_SLEEP
Stress: DataType.DT_INSTANTANEOUS_STRESS
startTimeintAn 8-digit integer in the format of YYYYMMDD, for example, 20200803.
endTimeintAn 8-digit integer in the format of YYYYMMDD, for example, 20200903.
Return Type
TypeDescription
Future<SampleSet>All data points with the start time or end time being in the specified time range will be queried. The sum value of the queried data points will be returned. Different from the readTodaySummation method, the readDailySummation method can be used to query the data of multiple days, with a statistical value provided for each day.
Call Example
SampleSet sampleSet = await dataController.readDailySummation(
  DataType.DT_CONTINUOUS_STEPS_DELTA, 20201002, 20201215);
Future<void> update(UpdateOptions options) async

Updates existing data. If the update target does not exist, a new entry of data will be inserted.

Parameters
ParameterTypeDescription
optionsUpdateOptionsUpdateOptions object, used to specify the time range of the data to be updated and the updated values.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
// Build the dataCollector object
DataCollector dataCollector = DataCollector(
  dataType: DataType.DT_CONTINUOUS_STEPS_DELTA,
  dataStreamName: 'my_data_stream_name',
  dataGenerateType: DataGenerateType.DATA_TYPE_RAW);

// You can use sampleSets to add more sampling points to the sampling dataset.
SampleSet sampleSet = SampleSet(dataCollector, <SamplePoint>[
  SamplePoint(
    startTime: DateTime.parse('2020-12-12 09:00:00'),
    endTime: DateTime.parse('2020-12-12 09:05:00'),
    fieldValueOptions: FieldInt(Field.FIELD_STEPS_DELTA, 120))
  ]);

// Build a parameter object for the update.
// Note: (1) The start time of the modified object updateOptions can not be greater than the minimum
// value of the start time of all sample data points in the modified data sample set
// (2) The end time of the modified object updateOptions can not be less than the maximum value of the
// end time of all sample data points in the modified data sample set
UpdateOptions updateOptions = UpdateOptions(
  startTime: DateTime.parse('2020-12-12 08:00:00'),
  endTime: DateTime.parse('2020-12-12 09:25:00'),
  sampleSet: sampleSet);

await _dataController.update(updateOptions);

SettingsController

Provides the setting-related functions.

Method Summary

MethodReturn TypeDescription
addDataTypeFuture<DataType>Creates and adds a customized data type.
readDataTypeFuture<DataType>Reads the data type based on the data type name.
disableHiHealthFuture<void>Disables the Health Kit function, cancels user authorization, and cancels all data records. (The task takes effect in 24 hours.)
checkHealthAppAuthorizationFuture<void>Checks the user privacy authorization to Health Kit. If the authorization has not been granted, the user will be redirected to the authorization screen where they can authorize the Huawei Health app to open data to Health Kit.
getHealthAppAuthorizationFuture<bool>Checks the user privacy authorization to Health Kit.

Methods

Future<DataType> addDataType(DataTypeAddOptions options) async

Creates and adds a customized data type. The name of the created data type must be prefixed with the package name of the app Otherwise, the creation fails. The same data type can't be added more than once otherwise an exception will be thrown.

Parameters
ParameterTypeDescription
optionsDataTypeAddOptionsRequest options for creating the data type.
Return Type
TypeDescription
Future<DataType>Created data type.
Call Example
DataTypeAddOptions options = DataTypeAddOptions(
  "com.huawei.hms.flutter.health_example.myCustomDataType",
  [Field.newIntField("myIntField"), Field.FIELD_ALTITUDE]);
final DataType dataTypeResult =
  await SettingController.addDataType(options);
Future<DataType> readDataType(String dataTypeName) async

Reads the data type based on the data type name.

Parameters
ParameterTypeDescription
dataTypeNameStringName of the custom data type to read.
Return Type
TypeDescription
Future<DataType>Obtained data type.
Call Example
final DataType dataTypeResult = await SettingController.readDataType(
  "com.huawei.hms.flutter.health_example.myCustomDataType",
);
Future<void> disableHiHealth() async

Disables the Health Kit function, cancels user authorization, and cancels all data records.

Note: The task takes effect in 24 hours.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await SettingController.disableHiHealth();
Future<void> checkHealthAppAuthorization() async

Checks the user privacy authorization to Health Kit. If the authorization has not been granted, the user will be redirected to the authorization screen where they can authorize the Huawei Health app to open data to Health Kit.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await SettingController.checkHealthAppAuthorization();
Future<bool> getHealthAppAuthorization() async

Checks the user privacy authorization to Health Kit.

Return Type
TypeDescription
Future<bool>Whether the user privacy authorization has been granted to Health Kit. Returns true if Authorized, false otherwise.
Call Example
bool result = await SettingController.getHealthAppAuthorization();

ConsentsController

Provides authorization management APIs that can be used to view and revoke the granted permissions.

Method Summary

MethodReturn TypeDescription
getAppIdFuture<String>Obtains the application id from the agconnect-services.json file.
getScopesFuture<ScopeLangItem>Queries the list of permissions granted to your app.
revokeFuture<void>Revokes all permissions granted to your app.
revokeWithScopesFuture<void>Revokes certain Health Kit related permissions granted to your app.

Methods

Future<String> getAppId() async

Obtains the application id from the agconnect-services.json file.

Return Type
TypeDescription
Future<String>Application ID.
Call Example
final String appId = await ConsentsController.getAppId();
Future<ScopeLangItem> getScopes(String lang, String appId) async

Queries the list of permissions granted to your app.

Parameters
ParameterTypeDescription
langStringLanguage code. If the specified value is invalid, en-us will be used.
appIdStringID of your app.
Return Type
TypeDescription
Future<ScopeLangItem>List of permissions that have been granted to your app.
Call Example
final String appId = await ConsentsController.getAppId();
ScopeLangItem scopeLangItem =
  await ConsentsController.getScopes('en-gb', appId);
Future<void> revoke(String appId) async

Revokes all permissions granted to your app.

Parameters
ParameterTypeDescription
appIdStringID of your app.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
final String appId = await ConsentsController.getAppId();
await ConsentsController.revoke(appId);
Future<void> revokeWithScopes(String appId, List<Scope> scopes) async

Revokes certain Health Kit related permissions granted to your app.

Parameters
ParameterTypeDescription
appIdStringID of your app.
scopesList<Scope>Scopes to be revoked.
Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
final String appId = await ConsentsController.getAppId();
await ConsentsController.revokeWithScopes(appId, [
  Scope.HEALTHKIT_DISTANCE_WRITE,
  Scope.HEALTHKIT_DISTANCE_READ,
]);

HMSLogger

HMSLogger is used for sending usage analytics of Health Kit SDK's methods to improve the service quality.

HMSLogger service is enabled by default.

Method Summary

MethodReturn TypeDescription
enableLoggerFuture<void>Enables HMSLogger service.
disableLoggerFuture<void>Disables HMSLogger service.

Methods

Future<void> enableLogger() async

Enables HMS Plugin Method Analytics which is used for sending usage analytics of Health Kit SDK's methods to improve the service quality.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await HMSLogger.enableLogger();
Future<void> disableLogger() async

Disables HMS Plugin Method Analytics which is used for sending usage analytics of Health Kit SDK's methods to improve the service quality.

Return Type
TypeDescription
Future<void>Future result of an execution that returns no value.
Call Example
await HMSLogger.disableLogger();

Option Classes

Request object classes for CRUD operations. The summary of classes is described in the table below.

NameDescription
ActivityRecordInsertOptionsRequest parameter class for inserting an activity record, including the associated sampling dataset and sampling points to the platform.
ActivityRecordReadOptionsDefines the activity record read options for an ActivityRecord read process
DataTypeAddOptionsDefines the options for adding a customized data type to Health Kit.
DeleteOptionsDefines the delete options for an ActivityRecord delete process.
ReadOptionsRequest class for reading data.
UpdateOptionsRequest parameter class for updating data.
HiHealthOptionDefines the request permissions.

ActivityRecordInsertOptions

Request parameter class for inserting an activity record, including the associated sampling dataset and sampling points to the platform.

Properties

NameTypeDescription
activityRecordActivityRecordActivityRecord to be inserted.
sampleSetsList<SampleSet>Sampling datasets for the request.

Constructor Summary

ConstructorDescription
ActivityRecordInsertOptions({ActivityRecord activityRecord, List<SampleSet> sampleSets})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two ActivityRecordInsertOptions objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

ActivityRecordInsertOptions({ActivityRecord activityRecord, List<SampleSets> sampleSets})

Default constructor.

Parameters
ParameterTypeDescription
activityRecordActivityRecordActivityRecord to be inserted.
sampleSetsList<SampleSets>Sampling datasets for the request.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two ActivityRecordInsertOptions objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

ActivityRecordReadOptions

Defines the activity record read options for an ActivityRecord read process.

Properties

NameTypeDescription
activityRecordIdStringID of the activity record to be read.
activityRecordNameStringName of the activity record to be read.
startTimeDateTimeStart time.
endTimeDateTimeEnd time.
timeUnitTimeUnitTime unit.
dataTypeDataTypeDataType of the ActivityRecord to be read.

Constructor Summary

ConstructorDescription
ActivityRecordReadOptions({String activityRecordId, String activityRecordName, DateTime startTime, DateTime endTime, TimeUnit timeUnit, DataType dataType})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.

Constructors

ActivityRecordsReadOptions
ActivityRecordReadOptions({String activityRecordId, String activityRecordName, DateTime startTime, DateTime endTime, TimeUnit timeUnit, DataType dataType})

Default constructor.

Parameters

The same fields apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.

DataTypeAddOptions

Defines the options for adding a customized data type to Health Kit.

Properties

NameTypeDescription
nameStringName of the DataType. It Must be prefixed with the package name.
fieldsList<Field>Field to be added to DataType.

Constructor Summary

ConstructorDescription
DataTypeAddOptions(String name, List<Field> fields)Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two DataTypeAddOptions objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

DataTypeAddOptions(String name, List<Field> fields)

Default Constructor.

Parameters

The same fields apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two DataTypeAddOptions objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

DeleteOptions

Defines the delete options for an ActivityRecord delete process.

Properties

NameTypeDescription
deleteAllDataboolShould be set to true if all the data types are marked for deletion.
deleteAllActivityRecordsboolShould be set to true if all the activity records are marked for deletion.
activityRecordsList<ActivityRecord>List of activity records to be deleted.
dataCollectorsList<DataCollector>List of data collectors whose data is to be deleted.
dataTypesList<DataType>List of data types whose data is to be deleted.
startTimeDateTimeStart time for data to be deleted.
endTimeDateTimeEnd time for data to be deleted.
timeUnitTimeUnitTimeUnit for data to be deleted.

Constructor Summary

ConstructorDescription
DeleteOptions({DateTime startTime, DateTime endTime, List<DataType> dataTypes, List<DataCollector> dataCollectors, List<ActivityRecord> activityRecords, bool deleteAllActivityRecords, bool deleteAllData, TimeUnit timeUnit})Default constructor.

Method Summary

MethodReturn TypeDescription
setTimeIntervalvoidSets the start time and end time for data to be deleted.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two DeleteOptions objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

DeleteOptions
DeleteOptions({DateTime startTime, DateTime endTime, List<DataType> dataTypes, List<DataCollector> dataCollectors, List<ActivityRecord> activityRecords, bool deleteAllActivityRecords, bool deleteAllData, TimeUnit timeUnit})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

void setTimeInterval(DateTime startTime, DateTime endTime)

Sets the start time and end time for data to be deleted. The start time must be greater than 0, and the end time must not be earlier than the start time.

Parameters
ParameterTypeDescription
startTimeDateTimeStart Time.
endTimeDateTimeEnd Time.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two DeleteOptions objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

ReadOptions

Request class for reading data. The request can be used to specify the type of data to be read and grouped parameters. The read request requires the setting of a time range and allows data to be read in detail or summary mode.

Properties

NameTypeDescription
startTimeDateTimeStart time of the read request.
endTimeDateTimeEnd time of the read request.
timeUnitTimeUnitTime unit of the read request.
durationintDuration for grouped data.
dataCollectorsList<DataCollector>Data collectors for reading data.
dataTypesList<DataType>Data types for reading data.
pageSizeintThe maximum number of pages for the paginated query results.
allowRemoteInquiryboolAllows for query on the cloud.

Constructor Summary

ConstructorDescription
ReadOptions({DateTime startTime, DateTime endTime, TimeUnit timeUnit, int pageSize, bool allowRemoteInquiry, List<DataCollector> dataCollectors, List<DataType> dataTypes})Default Constructor.

Method Summary

MethodReturn TypeDescription
groupByTimevoidSets the group type to TYPE_TIME and sets the duration for each group.
polymerizeByDataTypevoidAdds a new data type to the grouped data and sets the type of the grouped data to be returned.
polymerizeByDataCollectorvoidAdds a new data collector to the grouped data and sets the type of the grouped data to be returned.
toMapMap<String, dynamic>Returns a map representation of the object.

Constructors

ReadOptions
ReadOptions({DateTime startTime, DateTime endTime, TimeUnit timeUnit, int pageSize, bool allowRemoteInquiry, List<DataCollector> dataCollectors, List<DataType> dataTypes})

Default constructor.

Parameters
ParameterTypeDescription
startTimeDateTimeStart time of the read request.
endTimeDateTimeEnd time of the read request.
timeUnitTimeUnitTime unit of the read request.
dataCollectorsList<DataCollector>Data collectors for reading data.
dataTypesList<DataType>Data types for reading data.
pageSizeintThe maximum number of pages for the paginated query results.
allowRemoteInquiryboolAllows for query on the cloud.

Methods

void groupByTime(int duration, {TimeUnit timeUnit = TimeUnit.MILLISECONDS})

Sets the group type to TYPE_TIME and sets the duration for each group.

Parameters
ParameterTypeDescription
durationintDuration.
timeUnitTimeUnitTime Unit.
void polymerizeByDataType(DataType inputDataType, DataType outputDataType)

Adds a new data type to the grouped data and sets the type of the grouped data to be returned.

Parameters
ParameterTypeDescription
inputDataTypeDataTypeType of data to be grouped.
outputDataTypeDataTypeType of the grouped data to be returned.
void polymerizeByDataCollector(DataCollector dataCollector, DataType outputDataType)

Adds a data collector for reading data.

Parameters
ParameterTypeDescription
dataCollectorDataCollectorData collector to add.
outputDataTypeDataTypeType of the grouped data to be returned.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.

UpdateOptions

Request parameter class for updating data for a specified period of time to the HUAWEI Health platform.

Properties

NameTypeDescription
startTimeDateTimeStart time for update request.
endTimeDateTimeEnd time for update request.
timeUnitTimeUnitTime unit of the update request.
sampleSetSampleSetSampling dataset for updating data.

Constructor Summary

ConstructorDescription
UpdateOptions({DateTime startTime, DateTime endTime,TimeUnit timeUnit=TimeUnit.MILLISECONDS, SampleSet sampleSet})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.

Constructors

UpdateOptions({DateTime startTime, DateTime endTime,TimeUnit timeUnit=TimeUnit.MILLISECONDS, SampleSet sampleSet})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.

HiHealthOption

Defines the request permissions. Permissions are defined by DataType, which determines the Health Kit scopes authorized to the signed-in HUAWEI ID.

Properties

NameTypeDescription
dataTypeDataTypeData type that the developer needs to access.
accessTypeAccessTypeAccessType option for data type. Values are AccessType.read and AccessType.write.

Constructor Summary

ConstructorDescription
HiHealthOption(DataType dataType, AccessType accessType)Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
==(equals operator)boolChecks whether two HiHealthOption objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

HiHealthOption(DataType dataType, AccessType accessType)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two HiHealthOption objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

Data Classes

Dataset classes for interacting with the data provided by Health Kit. The summary of classes is described in the table below.

NameDescription
ActivityRecordActivity record class, which records the basic information about an activity of the user.
ActivitySummaryActivity summary class.
PaceSummaryPace summary class.
DataCollectorDefines a unique data collector.
DataTypeData types defined by HUAWEI Health Kit.
FieldFields for common data types.
SamplePointSampling point class, which presents the sampled data of a specific type collected by a specific data collector at a given time or within a time range.
FieldValueOptionsAbstract base class for FieldInt, FieldLong, FieldFloat, FieldMap, FieldString, FieldValueOptions types.
SampleSetThe sampling dataset class represents the container for storing sampling points.
ScopeLangItemList of permissions that have been granted to your app.
ScopeScope constant class, which is used to apply for scopes to access Health Kit data from users.

ActivityRecord

Activity record class, which records the basic information about an activity of the user. For example, for an outdoor running activity, information including the start time, end time, activity record name, identifier, description, activity type (as defined in HiHealthActivities, and activity duration will be recorded.

Properties

NameTypeDescription
startTimeDateTimeThe start time of the activity record.
endTimeDateTimeThe end time of the activity record.
activeTimeMillisintActivity duration in milliseconds.
nameStringName of the activity record.
idStringIdentifier of the activity record.
descriptionStringDescription of the activity record.
timeZoneStringTime Zone.
activityTypeIdStringActivity type corresponding to the activity record.
activitySummaryActivitySummaryActivity summary.

Constructor Summary

ConstructorDescription
ActivityRecord({DateTime startTime, DateTime endTime, String id, String name, String description, String activityTypeId, String timeZone, int activeTimeMillis, ActivitySummary activitySummary})Default constructor.

Method Summary

MethodReturn TypeDescription
isKeepGoingboolIndicates whether an activity record is in progress. If the activity record has ended, the value false will be returned.
hasDurationTimeboolIndicates whether the activity record has durations.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two ActivityRecord objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

ActivityRecord
ActivityRecord({DateTime startTime, DateTime endTime,String id, String name, String description, String activityTypeId, String timeZone, int activeTimeMillis, ActivitySummary activitySummary})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

bool get isKeepGoing

Indicates whether an activity record is in progress. If the activity record has ended, the value false will be returned.

Return Type
TypeDescription
booltrue if activity record is in progress, false otherwise.
bool get hasDurationTime

Indicates whether the activity record has durations.

Return Type
TypeDescription
booltrue if activity record has durations false otherwise.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two ActivityRecord objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

ActivitySummary

Activity summary class.

Properties

NameTypeDescription
paceSummaryPaceSummaryPaceSummary instance.
dataSummaryList<SamplePoint>Statistical data points that consist from SamplePoints.

Constructor Summary

ConstructorDescription
ActivitySummary({PaceSummary paceSummary, @required List<SamplePoint> dataSummary})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two ActivitySummary objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

ActivitySummary({PaceSummary paceSummary, @required List<SamplePoint> dataSummary})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two ActivitySummary objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

PaceSummary

Pace summary class.

Properties

NameTypeDescription
britishPaceMapMap<String, double>Pace per mile.
britishPartTimeMapMap<String, double>Segment data table in the imperial system.
paceMapMap<String, double>Pace per kilometer.
partTimeMapMap<String, double>Segment data table in the metric system.
sportHealthPaceMapMap<String, double>Health pace records.
avgPacedoubleAverage pace.
bestPacedoubleOptimal pace.

Constructor Summary

ConstructorDescription
PaceSummary({Map<String, double> britishPaceMap, Map<String, double> britishPartTimeMap, Map<String, double> paceMap, Map<String, double> partTimeMap, Map<String, double> sportHealthPaceMap, double avgPace, double bestPace})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two PaceSummary objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

PaceSummary
PaceSummary({Map<String, double> britishPaceMap, Map<String, double> britishPartTimeMap, Map<String, double> paceMap, Map<String, double> partTimeMap, Map<String, double> sportHealthPaceMap, double avgPace, double bestPace})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two PaceSummary objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

DataCollector

Defines a unique data collector. A data collector provides the raw data collected from a phone or external device. Data from multiple data collectors can be converted or combined and therefore becomes derived data. Each sampling point must have a corresponding data collector. When a data collector is created, a unique identifier will be generated for it. The identifier consists of the data collector type, device information, package name of the app, and more.

Constants

enum DataGenerateType

DataGenerateType options.

ValueDescription
DATA_TYPE_RAWRaw data type.
DATA_TYPE_DERIVEDDerived data type.
DATA_TYPE_CLEANClean data type.
DATA_TYPE_CONVERTEDConverted data type.
DATA_TYPE_MERGEDMerged data type.
DATA_TYPE_POLYMERIZEDGrouped data type.

Properties

NameTypeDescription
nameStringThe name of the data collector. The input parameter can be null or a string of 1 to 300 characters.
dataGenerateTypeDataGenerateTypeThe type of the data collector, such as raw and derived.
dataStreamNameStringThe name of the data stream. The input parameter can be empty or a string of 1 to 300 characters.
dataStreamIdStringThe unique identifier of the data collector.
dataTypeDataTypeThe data type.
deviceIdStringThe identifier of the device.
deviceInfoDeviceInfoThe Device information.
isLocalizedboolWhether the data collector is originated from the local device. The default value is false (non-local device).
packageNameStringThe package name of the app. The input parameter can be an empty string or a string of 1 to 300 characters.

Constructor Summary

ConstructorDescription
DataCollector({String name, String dataStreamName, String dataStreamId, @required DataType dataType, @required DataGenerateType dataGenerateType, String deviceId, DeviceInfo deviceInfo, bool isLocalized, String packageName})Default constructor.

Method Summary

MethodReturn TypeDescription
getStandardByTypeStringObtains the standard type.
getDataGenerateTypeDataGenerateTypeObtains the type of the data collector.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two DataCollector objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

DataCollector
DataCollector({String name, String dataStreamName, String dataStreamId, @required DataType dataType, @required DataGenerateType dataGenerateType, String deviceId, DeviceInfo deviceInfo, bool isLocalized, String packageName})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

String getStandardByType(int type)

Obtains the standard type.

Parameters
ParameterTypeDescription
typeintInteger value of the standard.
Return Type
TypeDescription
StringStandard name.
DataGenerateType getDataGenerateType(int value)

Obtains the type of the data collector.

Parameters
ParameterTypeDescription
valueintValue of the DataGenerateType. The value should be in 0-5 range
Return Type
TypeDescription
DataGenerateTypeDataGenerateType that corresponds to integer value.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two DataCollector objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

DataType

Data types defined by HUAWEI Health Kit. Each data type has a unique name for the identification purpose and each data type has its own meaning. For example, DT_CONTINUOUS_STEPS_DELTA indicates the number of steps taken since the last reading. You can also create you own data types with the addDataType API from the SettingController module.

Constants

ConstantTypeDescription
DT_UNUSED_DATA_TYPEDataTypeDefault data type.
DT_CONTINUOUS_STEPS_DELTADataTypeSteps taken since the last reading. The value range over 1 second is (0, 10], that over 1 minute is (0,600], and that over 1 hour is (0, 36000]
DT_CONTINUOUS_STEPS_TOTALDataTypeTotal number of steps. This data type applies only to data query scenarios.
DT_INSTANTANEOUS_STEPS_RATEDataTypeNumber of steps per minute.
DT_CONTINUOUS_STEPS_RATE_STATISTICDataTypeStep cadence statistics.
DT_CONTINUOUS_ACTIVITY_SEGMENTDataTypeActivity type within a period of time.
DT_CONTINUOUS_CALORIES_CONSUMEDDataTypeCalories consumed within a period of time (unit: kcal).
DT_CONTINUOUS_CALORIES_BURNTDataTypeTotal calories burnt within a period of time. This field is mandatory, and the unit is kcal. The value range over 1 second is (0, 0.555555555555556), that over 1 minute is (0,33.333333333333333), and that over 1 hour is (0, 2000].
DT_INSTANTANEOUS_CALORIES_BMRDataTypeBasic metabolic rate per day (unit: kcal).
DT_INSTANTANEOUS_POWER_SAMPLEDataTypeInstantaneous sampling of power.
DT_INSTANTANEOUS_ACTIVITY_SAMPLEDataTypeA single activity type within a period of time.
DT_INSTANTANEOUS_HEART_RATEDataTypeHeart rate (unit: heartbeats per minute). This field is mandatory. The value range is (0, 255).
DT_INSTANTANEOUS_LOCATION_SAMPLEDataTypeLocation at a given time.
DT_INSTANTANEOUS_LOCATION_TRACEDataTypeA point on the trajectory.
DT_CONTINUOUS_DISTANCE_DELTADataTypeDistance covered since the last reading (unit: meter). This field is mandatory. The value range over 1 second is (0, 100], that over 1 minute is (0, 6000], and that over 1 hour is (0, 360000].
DT_CONTINUOUS_DISTANCE_TOTALDataTypeAccumulated distance covered (unit: meter).
DT_CONTINUOUS_CALORIES_BURNT_TOTALDataTypeTotal calories.
DT_INSTANTANEOUS_SPEEDDataTypeInstantaneous speed on the ground (unit: m/s).
DT_CONTINUOUS_BIKING_WHEEL_ROTATION_TOTALDataTypeNumber of rotations of the bicycle wheel within a period of time.
DT_INSTANTANEOUS_BIKING_WHEEL_ROTATIONDataTypeInstantaneous measurement of the rotational speed of the bicycle wheel per minute.
DT_CONTINUOUS_BIKING_PEDALING_TOTALDataTypeTotal mileage of the bicycle since the start of the count (unit: meter).
DT_INSTANTANEOUS_BIKING_PEDALING_RATEDataTypeCycling speed at a time point (unit: m/s).
DT_INSTANTANEOUS_HEIGHTDataTypeHeight (unit: meter). This field is mandatory. The value range is (0.4, 2.6).
DT_INSTANTANEOUS_BODY_WEIGHTDataTypeWeight (unit: kg). This field is mandatory. The value range is (1, 560).
DT_INSTANTANEOUS_BODY_FAT_RATEDataTypeBody fat rate.
DT_INSTANTANEOUS_NUTRITION_FACTSDataTypeNutrient intake over a meal.
DT_INSTANTANEOUS_HYDRATEDataTypeWater taken over a single drink (unit: liter).
DT_CONTINUOUS_WORKOUT_DURATIONDataTypeWorkout duration (unit: minute).
DT_CONTINUOUS_EXERCISE_INTENSITYDataTypeWorkout intensity.
DT_STATISTICS_SLEEPDataTypeSleep statistics type.
DT_CONTINUOUS_SLEEPDataTypeSleep details.
DT_INSTANTANEOUS_STRESSDataTypePressure details.
DT_INSTANTANEOUS_STRESS_STATISTICSDataTypePressure statistics type.
POLYMERIZE_CONTINUOUS_WORKOUT_DURATIONDataTypeWorkout duration over a period of time (unit: minute).
POLYMERIZE_CONTINUOUS_ACTIVITY_STATISTICSDataTypeSummarized statistics of a specific activity type within a period of time.
POLYMERIZE_CONTINUOUS_CALORIES_BMR_STATISTICSDataTypeAverage, maximum, and minimum basic metabolic rates over a period of time (unit: kcal).
POLYMERIZE_STEP_COUNT_DELTADataTypeStep increment within a period of time.
POLYMERIZE_DISTANCE_DELTADataTypeDistance increment within a period of time.
POLYMERIZE_CALORIES_CONSUMEDDataTypeTotal calories consumed.
POLYMERIZE_CALORIES_EXPENDEDDataTypeTotal calories consumed within a period of time (unit: kcal).
POLYMERIZE_CONTINUOUS_EXERCISE_INTENSITY_STATISTICSDataTypeHeartbeat intensity statistics.
POLYMERIZE_CONTINUOUS_HEART_RATE_STATISTICSDataTypeAverage, maximum, and minimum heartbeats per minute within a period of time.
POLYMERIZE_CONTINUOUS_LOCATION_BOUNDARY_RANGEDataTypeActivity boundaries within a period of time.
POLYMERIZE_CONTINUOUS_POWER_STATISTICSDataTypePower within a period of time (including the maximum, minimum, and average power in the unit of watt).
POLYMERIZE_CONTINUOUS_SPEED_STATISTICSDataTypeGround speed (including the maximum, minimum, and average speed in the unit of m/s).
POLYMERIZE_CONTINUOUS_BODY_FAT_RATE_STATISTICSDataTypeBody fat rate over a period of time (including the maximum, minimum, and average values).
POLYMERIZE_CONTINUOUS_BODY_WEIGHT_STATISTICSDataTypeWeight over a period of time (including maximum, minimum, and average values in the unit of kg).
POLYMERIZE_CONTINUOUS_HEIGHT_STATISTICSDataTypeHeight over a period of time (including maximum, minimum, and average values in the unit of meter).
POLYMERIZE_CONTINUOUS_NUTRITION_FACTS_STATISTICSDataTypeSum of nutrient intake over a period of time.
POLYMERIZE_HYDRATIONDataTypeWater intake over a period of time (unit: liter).

Properties

NameTypeDescription
nameStringName. The value must be a string of 1 to 300 characters.
packageNameStringApp package name.
scopeNameReadStringRead permission of the data type. The value can be an empty string or a string of 1 to 1000 characters.
scopeNameWriteStringWrite permission of the data type. The value can be an empty string or a string of 1 to 1000 characters.
fieldsList<Field>Attribute list.
isPolymerizedFlagboolIndicates whether it is a grouped data type.
isSelfDefinedboolWhether the data type is a customized one.

Constructor Summary

ConstructorDescription
const DataType(String name, String scopeNameRead, String scopeNameWrite, List<Field> fields, {bool isPolymerizedFlag = false, bool isSelfDefined = false, String packageName = ""})Default constructor.

Method Summary

MethodReturn TypeDescription
getMimeTypeStringAdds a header name to the type.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.

Constructors

const DataType
const DataType(String name, String scopeNameRead, String scopeNameWrite, List<Field> fields, {bool isPolymerizedFlag = false, bool isSelfDefined = false, String packageName = ""})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

String getMimeType(DataType dataType)

Adds a header name to the type.

Parameters
ParameterTypeDescription
dataTypeDataTypeData Type.
Return Type
TypeDescription
StringHeader name.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.

Field

Fields for common data types.

Constants

For all the Field Constants please visit the document for the HUAWEI Health Kit Flutter Plugin on the Huawei Developer website.

Properties

NameTypeDescription
formatintAttribute type.
nameStringField Name.
isOptionalboolIndicates whether it is optional.

Constructor Summary

ConstructorDescription
const Field(String name, int format, {bool isOptional = false})Default constructor.
const Field.newFloatField(String name)Creates an attribute that contains float values.
const Field.newIntField(String name)Creates an attribute that contains integer values.
const Field.newMapField(String name)Creates an attribute that contains mapped values.
const Field.newStringField(String name)Creates an attribute that contains string values.
const Field.newLongField(String name)Creates an attribute that contains long values. (Note: this type matches with long on Java which can contain 64 bits. Dart's integer values are already 64 bits instead of Java's 32 bits.)

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two Field objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

const Field(String name, int format, {bool isOptional = false})

Default constructor.

Parameters

The same parameters apply as in the properties table.

const Field.newFloatField(String name)

Creates an attribute that contains float values.

Parameters
ParameterTypeDescription
nameStringField name.
const Field.newIntField(String name)

Creates an attribute that contains integer values.

Parameters
ParameterTypeDescription
nameStringField name.
const Field.newMapField(String name)

Creates an attribute that contains mapped values.

Parameters
ParameterTypeDescription
nameStringField name.
const Field.newStringField(String name)

Creates an attribute that contains string values.

Parameters
ParameterTypeDescription
nameStringField name.
const Field.newLongField(String name)

Creates an attribute that contains long values.

Note: this type matches with long on java which can contain 64 bits. Dart's integer values are already 64 bits instead of Java's 32 bits.

Parameters
ParameterTypeDescription
nameStringField name.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two Field objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

SamplePoint

Sampling point class, which presents the sampled data of a specific type collected by a specific data collector at a given time or within a time range. It stores the values of each dimension of the data type at the given time (or within the time range) and the start time and end time of the sampling operation.

The sampling modes of sampling points are classified into instantaneous sampling and continuous sampling based on the definition of data types.

When setting the sampling point time, you are advised to call setSamplingTime() for instantaneous sampling data and setTimeInterval() for continuous sampling data (make sure to set a valid time duration). In addition, you can also call setTimeInterval() to set the time for instantaneous sampling data. Make sure that the passed start time and end time are the same. Otherwise, the creation will fail. The setSamplingTime() API can not be used when creating the continuous sampling point. Otherwise, the creation will fail. This API can be used to update the end time of a created continuous sampling point. After the API is called, only the end time will be updated.

Properties

NameTypeDescription
idintID of the sampling point.
startTimeDateTimeStart time.
endTimeDateTimeEnd Time.
samplingTimeDateTimeSampling timestamp.
timeUnitTimeUnitTime unit.
fieldValueOptionsFieldValueOptionsFieldValueOptions object that contains the field values that will be used for SamplePoint creation.
dataCollectorDataCollectorData collector.

Constructor Summary

ConstructorDescription
SamplePoint({int id, DateTime startTime,DateTime endTime,DateTime samplingTime, FieldValueOptions fieldValueOptions, TimeUnit timeUnit = TimeUnit.MILLISECONDS, DataCollector dataCollector})Default constructor.

Method Summary

MethodReturn TypeDescription
getInsertionTimeDateTimeObtains the insertion time of the sample point.
setTimeIntervalvoidSets the sampling timestamp of data within an interval.
setSamplingTimevoidSets the sampling timestamp of instantaneous data.
fieldValuesMap<String, dynamic>Obtains the field values that are returned from the native platform.
getDataTypeIdintObtains DataTypeId.
getDataTypeDataTypeObtains the data type of the sampling point.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two SamplePoint objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

SamplePoint
SamplePoint({int id, DateTime startTime,DateTime endTime,DateTime samplingTime, FieldValueOptions fieldValueOptions, TimeUnit timeUnit = TimeUnit.MILLISECONDS, DataCollector dataCollector})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

DateTime get getInsertionTime

Obtains the insertion time of the sample point.

Return Type
TypeDescription
DateTimeInsertion time of the sample point
void set setTimeInterval(DateTime startTime, DateTime endTime, TimeUnit timeUnit)

Sets the sampling timestamp of data within an interval.

Parameters
ParameterTypeDescription
startTimeDateTimeStart time.
endTimeDateTimeEnd time.
timeUnitTimeUnitTime unit.
void set setSamplingTime(DateTime timestamp, TimeUnit timeUni)

Sets the sampling timestamp of instantaneous data.

Parameters
ParameterTypeDescription
timeStampDateTimeTimestamp.
timeUnitTimeUnitTime unit.
Map<String, dynamic> get fieldValues

Obtains the field values that are returned from the native platform. For example, while using the AutoRecorderController API, the resulting step count data can be obtained from this field.

Return Type
TypeDescription
Map<String, dynamic>Map that contains field values.
int get getDataTypeId

Obtains DataTypeId.

Return Type
TypeDescription
intId of the data type.
DataType get getDataType

Obtains DataType.

Return Type
TypeDescription
DataTypeDataType.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two SamplePoint objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

FieldValueOptions

Abstract base class for FieldInt, FieldLong, FieldFloat, FieldMap, FieldString, FieldValueOptions types. This class contain the specified Field and the corresponding value for that field. It can be used to specify field and value that can have different types for a SamplePoint object.

Properties

NameTypeDescription
fieldFieldField type.
valuedynamicField value.

Constructor Summary

ConstructorDescription
FieldValueOptions(Field field, dynamic value)Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
==(equals operator)boolChecks whether two FieldValueOptions objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

FieldValueOptions(Field field, dynamic value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
bool ==(Object other)

Checks whether two FieldValueOptions objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

FieldInt

Derived from the FieldValuesOptions class. Sets the integer attribute value of a sampling point.

Properties

NameTypeDescription
fieldFieldField type.
valueintInteger field value.

Constructor Summary

ConstructorDescription
FieldInt(Field field, int value)Default constructor.

Method Summary

The inherited methods from the FieldValueOptions base class.

Constructors

FieldInt(Field field, int value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

The inherited methods from the FieldValueOptions base class.

FieldLong

Derived from the FieldValuesOptions class. Sets the long integer attribute value of a sampling point. Different from FieldInt, this option's value will be set as long integer in Android Platfom.

Properties

NameTypeDescription
fieldFieldField type.
valueintInteger field value to be converted as long on Android Platform.

Constructor Summary

ConstructorDescription
FieldLong(Field field, int value)Default constructor.

Method Summary

The inherited methods from the FieldValueOptions base class.

Constructors

FieldLong(Field field, int value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Please refer to methods of FieldValueOptions

FieldFloat

Derived from the FieldValuesOptions class. Sets the double-precision floating-point attribute value of a sampling point.

Properties

NameTypeDescription
fieldFieldField type.
valuedoubleFloating field value.

Constructor Summary

ConstructorDescription
FieldFloat(Field field, double value)Default constructor.

Method Summary

The inherited methods from the FieldValueOptions base class.

Constructors

FieldFloat(Field field, double value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Please refer to methods of FieldValueOptions

FieldMap

Derived from the FieldValuesOptions class. Sets the mapped attribute value of a sampling point.

Properties

NameTypeDescription
fieldFieldField type.
valueMap<String, dynamic>Mapped field value.

Constructor Summary

ConstructorDescription
FieldMap(Field field, Map<String, dynamic> value)Default constructor.

Method Summary

The inherited methods from the FieldValueOptions base class.

Constructors

FieldMap(Field field, Map<String, dynamic> value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Please refer to methods of FieldValueOptions

FieldString

Derived from the FieldValuesOptions class. Sets the string attribute value of a sampling point.

Properties

NameTypeDescription
fieldFieldField type.
valueStringString field value.

Constructor Summary

ConstructorDescription
FieldString(Field field, String value)Default constructor.

Method Summary

The inherited methods from the FieldValueOptions base class.

Constructors

FieldString(Field field, String value)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Please refer to methods of FieldValueOptions

SampleSet

The sampling dataset class represents the container for storing sampling points. The sampling points stored in a sampling dataset must be from the same data collector (but their raw data collectors can be different). This class is usually used to insert or read sampling data in batches.

Properties

NameTypeDescription
dataCollectorDataCollectorData collector.
samplePointsList<SamplePoint>A list of sampling points.

Constructor Summary

ConstructorDescription
SampleSet(DataCollector dataCollector, List<SamplePoint> samplePoints)Default constructor.

Method Summary

MethodReturn TypeDescription
getDataTypeDataTypeObtains the data type from the data collector of the SampleSet.
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two SampleSet objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

SampleSet(DataCollector dataCollector, List<SamplePoint> samplePoints)

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

DataType get getDataType

Obtains the data type from the data collector of the SampleSet.

Return Type
TypeDescription
DataTypeData Type.
Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two SampleSet objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

ScopeLangItem

List of permissions that have been granted to your app.

Properties

NameTypeDescription
url2DescMap<String, String>Mapping between the permission scope URL and description.
authTimeStringTime when the permission is granted.
appNameStringApplication name.
appIconPathStringPath to the app icon image.

Constructor Summary

ConstructorDescription
ScopeLangItem({Map<String, String> url2Desc, String authTime, String appName, String appIconPath})Default constructor.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.
==(equals operator)boolChecks whether two ScopeLangItem objects are the same.
hashCodeintReturns the hash code of the current object.

Constructors

ScopeLangItem({Map<String, String> url2Desc, String authTime, String appName, String appIconPath})

Default constructor.

Parameters

The same parameters apply as in the properties table.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.
bool ==(Object other)

Checks whether two ScopeLangItem objects are the same.

Parameters
ParameterTypeDescription
otherObjectObject to compare.
Return Type
TypeDescription
boolComparison result: true if equals, false otherwise.
int get hashCode

Returns the hash code of the current object.

Return Type
TypeDescription
intCalculated hash value.

Scope

Scope constant class, which is used to apply for scopes to access Health Kit data from users.

Constants

ConstantTypeDescription
HEALTHKIT_ACTIVITY_READStringViews the activity data (such as activity points, workout, strength, running posture, cycling, and activity duration) in HUAWEI Health Kit.
HEALTHKIT_ACTIVITY_WRITEStringStores the activity data (such as activity points, workout, strength, running posture, cycling, and activity duration) in HUAWEI Health Kit.
HEALTHKIT_BLOODGLUCOSE_READStringViews the blood glucose data in HUAWEI Health Kit.
HEALTHKIT_BLOODGLUCOSE_WRITEStringStores the blood glucose data in HUAWEI Health Kit.
HEALTHKIT_CALORIES_READStringViews the calories (including the BMR) in HUAWEI Health Kit.
HEALTHKIT_CALORIES_WRITEStringStores calories (including the BMR) in HUAWEI Health Kit.
HEALTHKIT_DISTANCE_READStringViews the distance and climbing height in HUAWEI Health Kit.
HEALTHKIT_DISTANCE_WRITEStringStores the distance and climbing height in HUAWEI Health Kit.
HEALTHKIT_HEARTRATE_READStringViews the heart rate data in HUAWEI Health Kit.
HEALTHKIT_HEARTRATE_WRITEStringStores the heart rate data in HUAWEI Health Kit.
HEALTHKIT_HEIGHTWEIGHT_READStringViews the height and weight in HUAWEI Health Kit.
HEALTHKIT_HEIGHTWEIGHT_WRITEStringStores the height and weight in HUAWEI Health Kit.
HEALTHKIT_LOCATION_READStringViews the location data (including the trajectory) in HUAWEI Health Kit.
HEALTHKIT_LOCATION_WRITEStringStores the location data (including the trajectory) in HUAWEI Health Kit.
HEALTHKIT_PULMONARY_READStringViews the pulmonary function data (e.g. VO2 Max) in HUAWEI Health Kit.
HEALTHKIT_PULMONARY_WRITEStringStores the pulmonary function data (e.g. VO2 Max) in HUAWEI Health Kit.
HEALTHKIT_SLEEP_READStringViews the sleep data in HUAWEI Health Kit.
HEALTHKIT_SLEEP_WRITEStringStores the sleep data in HUAWEI Health Kit.
HEALTHKIT_SPEED_READStringViews the speed in HUAWEI Health Kit.
HEALTHKIT_SPEED_WRITEStringStores the speed in HUAWEI Health Kit.
HEALTHKIT_STEP_READStringViews the step count in HUAWEI Health Kit.
HEALTHKIT_STEP_WRITEStringStores the step count in HUAWEI Health Kit.
HEALTHKIT_STRENGTH_READStringViews medium- and high-intensity data in HUAWEI Health Kit.
HEALTHKIT_STRENGTH_WRITEStringStores medium- and high-intensity data in HUAWEI Health Kit.
HEALTHKIT_BODYFAT_READStringViews the body fat data (such as body fat rate, BMI, muscle mass, moisture rate, visceral fat, bone salt, protein ratio, and skeletal muscle mass) in HUAWEI Health Kit.
HEALTHKIT_BODYFAT_WRITEStringStores the body fat data (such as body fat rate, BMI, muscle mass, moisture rate, visceral fat, bone salt, protein ratio, and skeletal muscle mass) in HUAWEI Health Kit.
HEALTHKIT_NUTRITION_READStringViews the nutrition data in HUAWEI Health Kit.
HEALTHKIT_NUTRITION_WRITEStringStores the nutrition data in HUAWEI Health Kit.
HEALTHKIT_BLOODPRESSURE_READStringViews the blood pressure data in HUAWEI Health Kit.
HEALTHKIT_BLOODPRESSURE_WRITEStringStores the blood pressure data in HUAWEI Health Kit.
HEALTHKIT_BODYTEMPERATURE_READStringViews the body temperature data in HUAWEI Health Kit.
HEALTHKIT_BODYTEMPERATURE_WRITEStringStores the body temperature data in HUAWEI Health Kit.
HEALTHKIT_OXYGENSTATURATION_READStringViews the blood oxygen data in HUAWEI Health Kit.
HEALTHKIT_OXYGENSTATURATION_WRITEStringStores the blood oxygen data in HUAWEI Health Kit.
HEALTHKIT_REPRODUCTIVE_READStringViews the reproductive data in HUAWEI Health Kit.
HEALTHKIT_REPRODUCTIVE_WRITEStringStores the reproductive data in HUAWEI Health Kit.
HEALTHKIT_ACTIVITY_RECORD_READStringViews the activity data (such as activity points, workout, strength, running posture, cycling, and activity duration) in HUAWEI Health Kit.
HEALTHKIT_ACTIVITY_RECORD_WRITEStringStores the activity data (such as activity points, workout, strength, running posture, cycling, and activity duration) in HUAWEI Health Kit.
HEALTHKIT_STRESS_READStringViews the stress data in HUAWEI Health Kit.
HEALTHKIT_STRESS_WRITEStringStores the stress data in HUAWEI Health Kit.

Method Summary

MethodReturn TypeDescription
getAllScopesList<Scope>Obtains all the scopes defined for the Health Kit.

Methods

List<Scope> get getAllScopes

Obtains all the scopes defined for the Health Kit.

Return Type
TypeDescription
List<Scope>List of all scopes.

Result Classes

Data reading response class. Result classes are for utilizing the Health Kit API results. The summary of classes is described in the table below.

NameDescription
ReadReplyData reading response class that defines the Read results of the DataController.read method.
AuthHuaweiIdResult class that defines a HuaweiID for the HealthAuth.signIn method.

ReadReply

Data reading response class that defines the Read results of the DataController.read method.

Properties

NameTypeDescription
groupsList<Group>All data groups.
sampleSetsList<SampleSet>All sampling datasets.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.

AuthHuaweiId

Result class that defines a HuaweiID for the HealthAuth.signIn method.

Properties

NameTypeDescription
openIdStringOpenID. The value differs for the same user in different apps. The value is unique in a single app.
photoUriStringStringProfile picture URI.
accessTokenStringAccess token.
displayNameStringNickname.
statusintUser status. 1: normal, 2: Dbank suspended, 3: deregistered, 4: All services are suspended.
genderintUser gender. -1: unknown, 0: male, 1: female, 2: secret
unionIdStringUnionID. The value is the same for the same user across all your apps.
idTokenStringID token from AppTouch ID information.
expirationTimeSecsintExpiration time in seconds.
givenNameStringGiven name.
familyNameStringFamily name.
grantedScopesintAuthorized scopes.

Method Summary

MethodReturn TypeDescription
toMapMap<String, dynamic>Returns a map representation of the object.
toStringStringReturns a string representation of the object.

Methods

Map<String, dynamic> toMap()

Returns a map representation of the object.

Return Type
TypeDescription
Map<String, dynamic>Map representation of the current object.
String toString()

Returns a string representation of the object.

Return Type
TypeDescription
StringString representation of the current object.

Constants

Constants provided by the plugin. The summary of the constants are described in the table below. For other constant types please refer to the HUAWEI Health Kit Flutter Plugin document on the HUAWEI Developer website.

NameDescription
TimeUnitOptions for specifying the time unit.
HiHealthStatusCodesFor error status codes you can refer to HiHealthStatusCodes.

enum TimeUnit

Options for specifying the time unit.

ValueDescription
NANOSECONDSNanoseconds time unit.
MICROSECONDSMicroseconds time unit.
MILLISECONDSMilliseconds time unit.
SECONDSSeconds time unit.
MINUTESMinutes time unit.
HOURSHours time unit.
DAYSDays time unit.

4. Configuration and Description

Preparing for Release

Before building a release version of your app you may need to customize the proguard-rules.pro obfuscation configuration file to prevent the HMS Core SDK from being obfuscated. Add the configurations below to exclude the HMS Core SDK from obfuscation. For more information on this topic refer to this Android developer guide.

<flutter_project>/android/app/proguard-rules.pro

-ignorewarnings
-keepattributes *Annotation*
-keepattributes Exceptions
-keepattributes InnerClasses
-keepattributes Signature
-keep class com.hianalytics.android.**{*;}
-keep class com.huawei.updatesdk.**{*;}
-keep class com.huawei.hms.**{*;}
-keep class com.huawei.hms.flutter.** { *; }

# Flutter wrapper
-keep class io.flutter.app.** { *; }
-keep class io.flutter.plugin.**  { *; }
-keep class io.flutter.util.**  { *; }
-keep class io.flutter.view.**  { *; }
-keep class io.flutter.**  { *; }
-keep class io.flutter.plugins.**  { *; }
-dontwarn io.flutter.embedding.**

<flutter_project>/android/app/build.gradle

buildTypes {
    debug {
        signingConfig signingConfigs.config
    }
    release {
        signingConfig signingConfigs.config
        // Enables code shrinking, obfuscation and optimization for release builds
        minifyEnabled true
        // Unused resources will be removed, resources defined in the res/raw/keep.xml will be kept.
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

5. Sample Project

This plugin includes a demo project in the example folder, there you can find more usage examples.

In order to successfully run the demo application the HUAWEI ID Service and the Health Kit API should be authorized for your app as described in the Applying for HUAWEI ID Service and Applying for the HUAWEI Health Kit sections. The required Health Kit permission scopes for the demo application are as follows:

  • Read/Write Body height and weight data
  • Read/Write Step count data
  • Read/Write Distance and floor change data
  • Read/Write Speed data
  • Read/Write Calories data
  • Read/Write Activity data
  • Read/Write Location data
  • Read/Write Heart rate data
  • Read/Write User activity records data

6. Questions or Issues

If you have questions about how to use HMS samples, try the following options:

  • Stack Overflow is the best place for any programming questions. Be sure to tag your question with huawei-mobile-services.
  • Github is the official repository for these plugins, You can open an issue or submit your ideas.
  • Huawei Developer Forum HMS Core Module is great for general questions, or seeking recommendations and opinions.
  • Huawei Developer Docs is place to official documentation for all HMS Core Kits, you can find detailed documentations in there.

If you run into a bug in our samples, please submit an issue to the GitHub repository.


7. Licensing and Terms

Huawei Safety Detect Kit Flutter Plugin is licensed under Apache 2.0 license

Libraries

huawei_health