应用集成Health Service Kit后,通过调用HMSHealthKit中的接口来操作用户的运动记录数据。使用前请先确认应用是否已拥有运动记录数据的操作权限:
具体接口如下:
写入的运动记录数据的开始时间和结束时间均需大于2014年1月1号对应的UNIX时间戳。
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的运动记录示例代码如下:
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的运动记录示例代码如下:
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方法启动允许后台运行的运动记录,申请允许后台运行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")
},
} 应用使用continueActivityRecord方法续申请允许后台保活10分钟,示例如下:
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));
});
},
} 应用中使用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")
},
} 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();
}
} {
"backgroundModes": [
"dataTransfer"
],
"name": "com.huawei.ohos.healthkit.demo.KeepBackgroundAbility",
"type": "service",
"visible": true
}