目录

管理运动记录

应用集成Health Service Kit后,通过调用HMSHealthKit中的接口来操作用户的运动记录数据。使用前请先确认应用是否已拥有运动记录数据的操作权限:

具体接口如下:

将运动记录写入Health Service Kit

写入的运动记录数据的开始时间和结束时间均需大于2014年1月1号对应的UNIX时间戳。

  1. 创建一个指定活动类型、起止时间、活动统计信息、时区和其他必要信息的ActivityRecord。
  2. 使用ActivityRecord和可选的采样集或聚合采样点数据,创建一个ActivityRecordInsertOptions。
  3. 使用addActivityRecord方法将ActivityRecordInsertOptions插入Health Service Kit 。

    将运动记录写入Health Service Kit示例代码如下:
    import {HMSHealthKit, HMSHealthKitDataType, HMSHealthKitDeviceType, HMSHealthKitActivityType, DeviceInfo, DataCollector, Value, SamplePoint, SampleSet, PaceSummary, ActivityFeature, ActivitySummary, ActivityRecord, ActivityRecordInsertOptions} from '@hw-hmscore/hms-js-health'
    // 步骤1:创建一个指定活动类型、起止时间、活动统计信息、时区和其他必要信息的ActivityRecord
    // 根据设备生产商、设备模型编号、设备uuid、设备类型构造设备信息
    let deviceInfo = new DeviceInfo("manufacturer", "modelName", "uuid", HMSHealthKitDeviceType.TYPE_PHONE);
    // 根据设备信息、应用包名、数据类型构造数据采集器
    let dataCollector = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_ACTIVITY_FEATURE_JUMPING_ROPE);
    // 根据数据类型和数据字段的对应关系,构造跳绳运动特征统计数据类型的字段值
    const valuesActivityFeature = []
    let valueSkipNum = new Value("skip_num", "150");
    let valueStumbingNum = new Value("stumbling_rope", "0");
    let valueMaxSkipping = new Value("max_skipping_times", "1");
    let valueDoubleShake = new Value("double_shake", "0");
    let valueTripleShake = new Value("triple_shake", "0");
    valuesActivityFeature.push(valueSkipNum);
    valuesActivityFeature.push(valueStumbingNum);
    valuesActivityFeature.push(valueMaxSkipping);
    valuesActivityFeature.push(valueDoubleShake);
    valuesActivityFeature.push(valueTripleShake);
    
    // 根据字段值数组、开始时间、结束时间和元数据创建samplePoint
    let samplePoint = new SamplePoint(valuesActivityFeature, "1624774020000", "1624774320000", "here is customized text");
    // 根据数据源和samplePoints创建需要插入的数据采样集表示活动特征数据
    let activityFeature = new ActivityFeature(dataCollector, samplePoint);
    
    // 创建跳绳速度统计数据信息
    let dataCollectorJumpRope = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_CONTINUOUS_SKIP_SPEED_STATISTICS);
    let valueAvg = new Value("avg", "40");
    let valueMax = new Value("max", "60");
    let valueMin = new Value("min", "20");
    const valueJumpRopeSummary = [];
    valueJumpRopeSummary.push(valueAvg);
    valueJumpRopeSummary.push(valueMax);
    valueJumpRopeSummary.push(valueMin);
    let samplePointSkipSummary = new SamplePoint(valueJumpRopeSummary, "1624774020000", "1624774320000", "here is customized text");
    const samplePoints = [];
    samplePoints.push(samplePointSkipSummary);
    let sampleSetJumpRope = new SampleSet(dataCollectorJumpRope, samplePoints);
    // 创建卡路里统计数据信息
    let dataCollectorCaloresTotal = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL);
    let valueCaloresTotal = new Value("calories_total", "180");
    const valueCalories = [];
    valueCalories.push(valueCaloresTotal);
    let samplePointCaloresTotal = new SamplePoint(valueCalories, "1624774020000", "1624774320000", "here is customized text");
    const samplePointsCaloresTotal = [];
    samplePointsCaloresTotal.push(samplePointCaloresTotal);
    let sampleSetCalories = new SampleSet(dataCollectorCaloresTotal, samplePointsCaloresTotal);
    
    let sampleSets = [];
    sampleSets.push(sampleSetJumpRope);
    sampleSets.push(sampleSetCalories);
    
    // 基于创建特征值、统计数据集合、paceSummary构建activitySummary
    let activitySummary = new ActivitySummary(activityFeature, sampleSets, null);
    // 创建运动心率明细数据源
    let dataCollectorHeartRate = new DataCollector(deviceInfo, "com.health.demo", HMSHealthKitDataType.DT_INSTANTANEOUS_EXERCISE_HEART_RATE);
    const valuesHeartRates = []
    let valueHeartRate = new Value("bpm", "120");
    valuesHeartRates.push(valueHeartRate)
    
    let samplePointHeartRate = new SamplePoint(valuesHeartRates, "1624774020000", "1624774320000", "here is customized text");
    const samplePointsHeartRate = []
    samplePointsHeartRate.push(samplePointHeartRate);
    // 运动记录关联的详情数据采样集
    let sampleSet = new SampleSet(dataCollectorHeartRate, samplePointsHeartRate);
    const sampleSetLists = []
    sampleSetLists.push(sampleSet);
    
    let activityRecord = new ActivityRecord("mysession1", "1624774020000", "1624774320000", HMSHealthKitActivityType.JUMPING_ROPE, "here", activitySummary, "+0800", "here is customized text", deviceInfo);
    // 步骤2:使用ActivityRecord和可选的采样集或聚合采样点数据,创建一个ActivityRecordInsertOptions
    let activityRecordInsertOptions = new ActivityRecordInsertOptions(activityRecord, sampleSetLists);
    
    // 步骤3:使用addActivityRecord方法将ActivityRecordInsertOptions插入Health Service Kit
    HMSHealthKit.addActivityRecord(activityRecordInsertOptions).then((result) => {
        // 调用成功
        console.info("addActivityRecord success: " + JSON.stringify(result))
    }).catch((error) => {
        // 调用失败
        console.error("addActivityRecord error: " + JSON.stringify(error));
    })

删除Health Service Kit的运动记录

  1. 删除的运动记录数据的开始时间和结束时间均需大于2014年1月1号对应的UNIX时间戳。
  2. 删除运动记录数据时,若activityRecordIds不为空则根据activityRecordIds删除,否则根据起止时间删除。
  1. 根据activityRecordIds或起止时间创建一个ActivityRecordDeleteOptions。
  2. 使用deleteActivityRecord方法将满足ActivityRecordDeleteOptions的运动记录数据从Health Service Kit中删除 。

    删除Health Service Kit的运动记录示例代码如下:

    import {HMSHealthKit, HMSHealthKitDataType, ActivityRecordDeleteOptions} from '@hw-hmscore/hms-js-health'
    // 步骤1:根据activityRecordIds或起止时间创建一个ActivityRecordDeleteOptions
    const subDataTypes = []
    // 构建需要删除的子数据类型的数组
    subDataTypes.push(HMSHealthKitDataType.DT_INSTANTANEOUS_HEART_RATE)
    
    const activityRecordIds = []
    // 此处填写acitivityRecordId,不携带activityRecordId可以注释下一行
    activityRecordIds.push("mysession1")
    
    // 基于时间等条件创建删除参数deleteOptions
    let deleteOption = new ActivityRecordDeleteOptions("1624774020000", "1624774320000", subDataTypes, activityRecordIds, "true")
    
    // 步骤2:使用deleteActivityRecord方法将满足ActivityRecordDeleteOptions的运动记录数据从Health Service Kit中删除 
    HMSHealthKit.deleteActivityRecord(deleteOption).then((result) => {
        // 调用成功
        console.info("deleteActivityRecord success: " + JSON.stringify(result))
    }).catch((error) => {
        // 调用失败
        console.error("addActivityRecord error: " + JSON.stringify(error))
    })

读取Health Service Kit的运动记录

  1. 调用查询运动记录数据接口,接口参数中的起止时间均需大于2014年1月1号对应的UNIX时间戳。
  2. 调用查询运动健康数据的运动记录数据接口,接口参数中的开始时间和结束时间之间的时间跨度不允许超过10天。
  3. ActivityRecordReadOptions实例中的setDataTypeNameList参数携带具体的数据类型可从可开放的锻炼记录数据类型中获取,如果不携带,可能读取不到华为运动健康App上的运动记录中的明细数据。
  1. 要获取符合某些条件的运动记录列表,先要创建一个ActivityRecordReadOptions实例。
  2. 使用getActivityRecord方法获取运动记录数据。

    查询Health Service Kit的运动记录示例代码如下:

    import {HMSHealthKit, HMSHealthKitDataType, ActivityRecordReadOptions} from '@hw-hmscore/hms-js-health'
    // 步骤1:创建一个ActivityRecordReadOptions实例
    const dataTypeNameList = []
    // 创建需要读取的运动记录关联的详情数据
    dataTypeNameList.push(HMSHealthKitDataType.DT_INSTANTANEOUS_EXERCISE_HEART_RATE)
    // 基于起止时间、详情数据集合,创建读取运动记录的参数
    let readOption = new ActivityRecordReadOptions("1624774020000", "1624774320000", dataTypeNameList)
    // 步骤2:使用getActivityRecord方法获取运动记录数据
    HMSHealthKit.getActivityRecord(readOption).then((result) => {
        // 调用成功
        console.info("getActivityRecord success: " + JSON.stringify(result))
    }).catch((error) => {
        // 调用失败
        console.error("getActivityRecord error: " + JSON.stringify(error));
    })

创建允许后台运行的运动记录

在用户的锻炼过程中,您的应用需要保持后台运行,请创建允许后台运行的运动记录。

  • 为保证您的应用不被系统冻结,在调用beginActivityRecord创建允许后台运行的运动记录后,需开启系统的前台Service保证应用运行。
  • 目前支持WATCH 3/4系列智能表,且系统需为HarmonyOS 3.0.0及以上版本。

[h2]FA JavaScript端

  1. 启动允许后台运行的ActivityRecord。

    应用使用beginActivityRecord方法启动允许后台运行的运动记录,申请允许后台运行10分钟,并在调用成功后,调用PA启动系统前台Service,示例如下:

    import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
    
    // 调用PA的类型,0:Ability; 1:Internal Ability
    const ABILITY_TYPE_EXTERNAL = 0;
    // 启动前台Service消息码
    const MESSAGE_CODE_START = 1001;
    // 停止前台Service消息码
    const MESSAGE_CODE_STOP = 1002;
    export default {
        async beginActivityRecord() {
            // 设备信息
            let deviceInfo = new DeviceInfo("manufacturer", "modelName", "uuid", HMSHealthKitDeviceType.TYPE_SMART_WATCH);
    
            // 创建一个指定活动ID、开始时间、时区和其他必要信息的ActivityRecord
            let activityRecord = new ActivityRecord("mysession1", "1624774020000", "0", HMSHealthKitActivityType.YOGA, "desc", null, "+0800", "here is customized text", deviceInfo);
            // 构建应用运动记录运行中展示的页面,编程中需替换成自身应用包名、页面
            var componentInfo = new ComponentInfo("com.huawei.ohos.healthkit.demo", "pages", "Harmony")
            // 调用HMSHealthKit.beginActivityRecord接口启动保活活动记录
            HMSHealthKit.beginActivityRecord(activityRecord, componentInfo, (result) => {
                console.info("beginActivityRecord callback:" + new Date() + " " + JSON.stringify(result))
                // 若保活超时取消或被其他三方应用抢占,回调需处理停止前台Service
                if (result.data != "0") {
                    this.stopKeepBackground();
                }
            }, this.$app.$def.hmsData.eventCallbackMap).then((result) => {
                console.info("beginActivityRecord -> success :" + JSON.stringify(result))
                // 调用成功时,调用JAVA PA前台Service
                this.startKeepBackground();
            }).catch((error) => {
                // 调用失败回调处理
                console.error("beginActivityRecord -> Error : " + JSON.stringify(error));
            });
        },
    
        // 调用PA,启动前台service
        startKeepBackground() {
            console.info("workout startKeepBackground begin")
            // 设置JAVA PA action信息,编程中需替换成自身应用的信息
            var action = {};
            action.bundleName = 'com.huawei.ohos.healthkit.demo';
            action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
            action.messageCode = MESSAGE_CODE_START;
            action.abilityType = ABILITY_TYPE_EXTERNAL;
            action.syncOption = 0;
    
            FeatureAbility.callAbility(action);
            console.info("workout startOngoing done")
        },
        // 调用JAVA PA,停止前台service
        stopKeepBackground() {
            console.info("workout stopKeepBackground begin")
            // 设置JAVA PA action信息,编程中需替换成自身应用的信息
            var action = {};
            action.bundleName = 'com.huawei.ohos.healthkit.demo';
            action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
            action.messageCode = MESSAGE_CODE_STOP;
            action.abilityType = ABILITY_TYPE_EXTERNAL;
    
            // 调用相应action的PA能力
            FeatureAbility.callAbility(action);
            console.info("workout stopKeepBackground done")
        },
    }

    上面的代码片段中用到this.$app.$def.hmsData.eventCallbackMap为全局事件回调集合,定义方法请参见初始化模块。

  2. 每临近10分钟(小于10分钟)续申请后台保活。

    应用使用continueActivityRecord方法续申请允许后台保活10分钟,示例如下:

    用户锻炼过程中,每临近10分钟(小于10分钟)需重复使用continueActivityRecord方法续申请允许后台保活,否则您的应用将会被终止运行。

    import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
    
    export default {
        async continueActivityRecord () {
            // 调用HMSHealthKit.continueActivityRecord方法为指定运动记录续申请允许后台保活,入参为ActivityRecord的ID字符串
            HMSHealthKit.continueActivityRecord("mysession1").then((result) => {
                // 调用成功处理
                console.info("continueActivityRecord -> success :" + JSON.stringify(result))
            }).catch((error) => {
                // 调用失败回调处理
                console.error("continueActivityRecord -> Error : " + JSON.stringify(error));
            });
        },
    }

  3. 停止ActivityRecord。

    应用中使用endActivityRecord方法停止指定的运动记录,并停止前台Service,退出运行后台运行状态,示例如下:

    import {HMSHealthKit, DeviceInfo, ActivityRecord, ComponentInfo, HMSHealthKitActivityType, HMSHealthKitDeviceType} from '@hw-hmscore/hms-js-health'
    
    // 停止前台Service消息码
    const MESSAGE_CODE_STOP = 1002;
    
    export default {
        async endActivityRecord () {
            // 调用HMSHealthKit.endActivityRecord方法为停止指定运动记录,入参为ActivityRecord的ID字符串
            HMSHealthKit.endActivityRecord("mysession1").then((result) => {
                console.info("endActivityRecord -> success :" + JSON.stringify(result))
                // 调用成功时,调用JAVA PA停止前台Service
                this.stopKeepBackground();
            }).catch((error) => {
                // 调用失败回调处理
                console.error("endActivityRecord -> Error : " + JSON.stringify(error));
            });
        },
        // 调用JAVA PA,停止前台service
        stopKeepBackground() {
            console.info("workout stopKeepBackground begin")
            // 设置JAVA PA action信息,编程中需替换成自身应用的信息
            var action = {};
            action.bundleName = 'com.huawei.ohos.healthkit.demo';
            action.abilityName = 'com.huawei.ohos.healthkit.demo.KeepBackgroundAbility';
            action.messageCode = MESSAGE_CODE_STOP;
            action.abilityType = ABILITY_TYPE_EXTERNAL;
    
            // 调用相应action的PA能力
            FeatureAbility.callAbility(action);
            console.info("workout stopKeepBackground done")
        },
    }

[h2]PA端(Ability方式)

  1. 在java目录下新建一个Service Ability,文件命名为KeepBackgroundAbility.java,示例如下:

    package com.huawei.ohos.healthkit.demo;
    
    // ohos相关接口包
    import ohos.aafwk.ability.Ability;
    import ohos.aafwk.content.Intent;
    import ohos.event.notification.NotificationRequest;
    import ohos.rpc.IRemoteObject;
    import ohos.hiviewdfx.HiLog;
    import ohos.hiviewdfx.HiLogLabel;
    import ohos.rpc.IRemoteBroker;
    import ohos.rpc.RemoteObject;
    import ohos.rpc.MessageParcel;
    import ohos.rpc.MessageOption;
    
    public class KeepBackgroundAbility extends Ability {
        // 定义日志标签
        private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "KeepBackgroundAbility");
        // 定义绑定通知的notificationId
        public static final int NOTIFICATION_ID = 1005;
        // RemoteObject对象,供FA向PA发送消息
        private MyRemote remote = new MyRemote();
    
        // FA在请求PA服务时会调用Ability.connectAbility连接PA,连接成功后,需要在onConnect返回一个remote对象
        @Override
        protected IRemoteObject onConnect(Intent intent) {
            super.onConnect(intent);
            return remote.asObject();
        }
    
        class MyRemote extends RemoteObject implements IRemoteBroker {
            // 启动前台Service消息码
            private static final int START = 1001;
            // 停止前台Service消息码
            private static final int STOP = 1002;
    
            MyRemote() {
                super("MyService_MyRemote");
            }
    
            @Override
            public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
                switch (code) {
                    case START: {
                        // 为前台Service创建通知
                        sendNotification();
                        HiLog.info(LABEL_LOG, "onRemoteRequest START");
                        break;
                    }
                    case STOP: {
                        // 取消前台Service通知
                        cancelNotification();
                        HiLog.info(LABEL_LOG, "onRemoteRequest EXIT");
                        break;
                    }
                    default: {
                        return false;
                    }
                }
                return true;
            }
    
            @Override
            public IRemoteObject asObject() {
                return this;
            }
        }
    
        @Override
        public void onStop() {
            super.onStop();
            cancelNotification();
        }
    
        @Override
        public void onCommand(Intent intent, boolean restart, int startId) {
            super.onCommand(intent, restart, startId);
        }
    
        @Override
        public void onDisconnect(Intent intent) {
            super.onDisconnect(intent);
        }
    
        // 创建通知,并调用keepBackgroundRunning()将Service与通知绑定
        private void sendNotification() {
            // 创建通知,其中NOTIFICATION_ID常量为notificationId
            NotificationRequest request = new NotificationRequest(NOTIFICATION_ID);
            NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();
            content.setTitle("Demo").setText("doing workout");
            NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
            request.setContent(notificationContent);
    
            // 绑定通知,NOTIFICATION_ID常量为创建通知时传入的notificationId
            keepBackgroundRunning(NOTIFICATION_ID, request);
        }
    
        // 取消通知
        private void cancelNotification() {
            cancelBackgroundRunning();
        }
    }

  2. 在配置文件中,“module > abilities”字段下添加前台Service的配置,backgroundModes需配置成“dataTransfer”,同时在配置文件中申明ohos.permission.KEEP_BACKGROUND_RUNNING权限,示例如下:

    {
      "backgroundModes": [
        "dataTransfer"
      ],
      "name": "com.huawei.ohos.healthkit.demo.KeepBackgroundAbility",
      "type": "service",
      "visible": true
    }