运动健康采样数据
========

#### 场景介绍

运动健康采样数据(SamplePoint)，表示在某时刻（或一段时间）采集到的特定数据类型的样本，由时间、样本值及采样的数据源组成，支持保存、读取和删除等操作。

#### 接口说明

| 接口名 | 描述 |
| :-- | :-- |
| [saveData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoresavedata)(sampleData: [SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)\[\] | [SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)): Promise<void> | 保存运动健康采样数据，入参为单个[SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)或[SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)数组。 |
| [readData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstorereaddata)<T extends [SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)\>(request: [SamplePointReadRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepointreadrequest)): Promise<T\[\]> | 查询运动健康采样数据，通过[SamplePointReadRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepointreadrequest)设置查询条件，可按数据类型，字段、时间范围等条件查询。 |
| [deleteData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoredeletedata-3)(samplePoint: [SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint) | [SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)\[\]): Promise<void> | 删除运动健康采样数据，按入参删除指定的采样数据，可传入单个[SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)或[SamplePoint](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepoint)数组。 |
| [deleteData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoredeletedata)(request: [SamplePointDeleteRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepointdeleterequest) | [SamplePointDeleteRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepointdeleterequest)\[\]): Promise<void> | 删除运动健康采样数据，按[SamplePointDeleteRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#samplepointdeleterequest)条件删除，可设置数据类型、时间范围、数据源等删除条件。 |
| [aggregateData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoreaggregatedata)<T extends [AggregateResult](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#aggregateresult)\>(request: [AggregateRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#aggregaterequest) | [AggregateRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#aggregaterequest)\[\]): Promise<T\[\]> | 聚合查询运动健康采样数据，通过[AggregateRequest](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#aggregaterequest)设置查询的数据类型、聚合策略。 |

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/fc/v3/ul9WY7GsR5a_X80jLihRFA/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073612Z&HW-CC-Expire=86400&HW-CC-Sign=259084F6928E0C929A4F9A5EC65C5894E49C293773C5B60B6628658D61F89B9E)

aggregateData接口读取今日日常活动数据，数据上报存在延时，读取实时日常活动数据建议使用[读取实时三环数据](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-three-ring-read)接口。

#### 开发前检查

*   完成[申请运动健康服务](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-apply)与[配置Client ID](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-configuration-client-id)。
    
*   接口首次调用前，需先使用[init](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoreinit)方法进行初始化。
    
*   需先通过[用户授权](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-add-permissions#用户授权)接口引导用户授权，用户授权对应数据类型权限后，才有权限调用接口操作相关数据类型数据。
    
*   错误码请参考[ArkTS API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/errorcode-healthservice)，常见问题请参考[Health Service Kit常见问题](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-faqs)。
    

#### 开发步骤

#### \[h2\]保存用户的运动健康数据

1.  导入运动健康服务功能模块及相关公共模块。
    
    import { healthStore } from '@kit.HealthServiceKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
2.  获取dataSourceId，参考[管理数据源](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/health-datasource-manage)，插入一个新的数据源或读取已有数据源。
    
3.  创建运动健康采样数据。
    
    let samplePoint: healthStore.samplePointHelper.bodyTemperature.Model = {
      dataType: healthStore.samplePointHelper.bodyTemperature.DATA\_TYPE,
      startTime: 1698633801000,
      endTime: 1698633801000,
      localDate: '10/30/2023',
      timeZone: '+0800',
      modifiedTime: 1698633801000,
      // insertDataSource插入数据源接口返回的dataSourceId，或读取已有数据源的dataSourceId
      dataSourceId: 'xxx',
      fields: {
        bodyTemperature: 39
      }
    }
    
4.  调用[saveData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoresavedata)方法执行保存数据请求，并处理返回结果。
    
    try {
      await healthStore.saveData(samplePoint);
      hilog.info(0x0000, 'testTag', 'Succeeded in saving data.');
    } catch (err) {
      hilog.error(0x0000, 'testTag', \`Failed to save data. Code: ${err.code}, message: ${err.message}\`);
    }
    

#### \[h2\]读取用户的运动健康数据

1.  导入运动健康服务功能模块及相关公共模块。
    
    import { healthStore } from '@kit.HealthServiceKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
2.  创建查询请求。
    
    let samplePointReadRequest: healthStore.SamplePointReadRequest = {
      samplePointDataType: healthStore.samplePointHelper.bodyTemperature.DATA\_TYPE,
      startTime: 1698633801000,
      endTime: 1698633801000,
      fields: {
        bodyTemperature: 39
      }
    }
    
3.  调用[readData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstorereaddata)方法执行查询请求，并处理返回结果。
    
    try {
      let samplePoints = await healthStore.readData(samplePointReadRequest);
      samplePoints.forEach((samplePoint) => {
        hilog.info(0x0000, 'testTag', \`Succeeded in reading data, the bodyTemperature is ${samplePoint.fields.bodyTemperature}.\`);
      });
    } catch (err) {
      hilog.error(0x0000, 'testTag', \`Failed to read data. Code: ${err.code}, message: ${err.message}\`);
    }
    

#### \[h2\]删除指定的运动健康采样数据

1.  导入运动健康服务功能模块及相关公共模块。
    
    import { healthStore } from '@kit.HealthServiceKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
2.  查询待删除的运动健康采样数据。
    
    let samplePointReadRequest: healthStore.SamplePointReadRequest = {
      samplePointDataType: healthStore.samplePointHelper.bodyTemperature.DATA\_TYPE,
      startTime: 1698633801000,
      endTime: 1698633801000
    }
    let samplePoints: healthStore.SamplePoint\[\] = await healthStore.readData(samplePointReadRequest);
    
3.  调用[deleteData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoredeletedata-3)方法执行删除请求，并处理返回结果。
    
    try {
      for (let index = 0; index < samplePoints.length; index++) {
        const samplePoint = samplePoints\[index\];
        await healthStore.deleteData(samplePoint);
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in deleting data.');
    } catch (err) {
      hilog.error(0x0000, 'testTag', \`Failed to delete data. Code: ${err.code}, message: ${err.message}\`);
    }
    

#### \[h2\]根据请求删除用户运动健康数据

1.  导入运动健康服务功能模块及相关公共模块。
    
    import { healthStore } from '@kit.HealthServiceKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
2.  创建删除请求。
    
    let samplePointDeleteRequest: healthStore.SamplePointDeleteRequest = {
      dataType: healthStore.samplePointHelper.bodyTemperature.DATA\_TYPE,
      startTime: 1698633801000,
      endTime: 1698633801000
    }
    
3.  调用[deleteData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoredeletedata-3)方法执行删除请求，并处理返回结果。
    
    try {
      await healthStore.deleteData(samplePointDeleteRequest);
      hilog.info(0x0000, 'testTag', 'Succeeded in deleting data.');
    } catch (err) {
      hilog.error(0x0000, 'testTag', \`Failed to delete data. Code: ${err.code}, message: ${err.message}\`);
    }
    

#### \[h2\]聚合查询

1.  导入运动健康服务功能模块及相关公共模块。
    
    import { healthStore } from '@kit.HealthServiceKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
    
2.  创建聚合查询请求。
    
    let aggregateRequest: healthStore.AggregateRequest<healthStore.samplePointHelper.dailyActivities.AggregateFields> = {
      dataType: healthStore.samplePointHelper.dailyActivities.DATA\_TYPE,
      metrics: {
        step: \['sum'\],
        calorie: \['sum'\],
        distance: \['sum'\],
        climbHighAltitude:\['sum'\],
        isIntensity: \['sum'\],
        isStand: \['sum'\]
     },
      groupBy: {
        unitType: healthStore.GroupUnitType.DAY
      },
      startLocalDate: '10/30/2023',
      endLocalDate: '10/30/2023'
    }
    
3.  调用[aggregateData](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/health-api-healthstore#healthstoreaggregatedata)方法执行查询请求，并处理返回结果。
    
    try {
      const aggregateResults = await healthStore.aggregateData<healthStore.samplePointHelper.dailyActivities.AggregateResult>(aggregateRequest);
      hilog.info(0x0000, 'testTag', 'Succeeded in reading data.');
      aggregateResults.forEach((aggregateResult) => {
        hilog.info(0x0000, 'testTag', \`the start time is ${aggregateResult.startTime}.\`);
        hilog.info(0x0000, 'testTag', \`the end time is ${aggregateResult.endTime}.\`);
        Object.keys(aggregateResult.fields).forEach((fieldName) => {
          hilog.info(0x0000, 'testTag', \`the sum of ${fieldName} is ${aggregateResult.fields\[fieldName\].sum}.\`);
        });
      });
    } catch (err) {
      hilog.error(0x0000, 'testTag', \`Failed to read data. Code: ${err.code}, message: ${err.message}\`);
    }