外观
service.health
约 815 字大约 3 分钟
2026-07-15
健康数据服务。小米/openvela 2026 大赛文档已公开采样族的完整参数:getRecentSamples、subscribeSample、unsubscribeSample,大赛分支范围是心率、血氧和压力。较早的 dev 实现与出货固件可能只注册心率;固件中还存在两个未进入公开指南的便捷成员。
import health from '@service.health'Manifest
Feature 与健康权限必须同时声明。后台持续订阅还要加入 config.background.features:
{
"deviceTypeList": ["watch"],
"features": [
{ "name": "service.health" }
],
"permissions": [
{ "name": "hapjs.permission.HEALTH" }
],
"config": {
"background": {
"features": ["service.health"]
}
}
}只声明 Feature 不声明权限会被健康数据权限管控拒绝;只声明权限则无法加载模块。
数据类型
| 常量 | 值 | value 类型/单位 |
|---|---|---|
health.DATA_TYPES.HEART_RATE | 0 | Integer,bpm |
health.DATA_TYPES.SPO2 | 6 | Integer,百分比 |
health.DATA_TYPES.STRESS | 9 | Integer,压力值 |
上表是 dev-ai-contest-2026 第一方指南的契约。公开 dev 分支的 health.jidl 目前只定义 HEART_RATE = 0,其 C++ 实现也只映射 algo_heartrate。因此必须读取设备实际导出的 health.DATA_TYPES,不能在旧系统上仅凭数值 6/9 假定血氧和压力已接入。
Sample 结构统一为:
interface Sample {
timeStamp: number // 毫秒级 epoch 时间戳
value: number
}大赛模拟器中三类数据都是 1 Hz;指南给出的真机压力数据约 60 秒一次。不要用模拟器频率推定其他出货固件的功耗或采样周期。
health.getRecentSamples(options)
interface GetRecentSamplesOptions {
dataTypes: number[]
success?: (items: RecentSample[]) => void
fail?: (data: object, code: number) => void
complete?: () => void
}
interface RecentSample {
dataType: number
data: Sample
}
getRecentSamples(options: GetRecentSamplesOptions): Promise<RecentSample[]>同一个方法同时支持 Promise 和 options 回调。dataTypes 必须是非空数组。
health.getRecentSamples({
dataTypes: [
health.DATA_TYPES.HEART_RATE,
health.DATA_TYPES.SPO2,
health.DATA_TYPES.STRESS
]
}).then(items => {
for (const item of items) {
console.log(item.dataType, item.data.timeStamp, item.data.value)
}
}).catch(error => console.error(error))只返回能够查询到的类型。没有缓存或请求类型均不可用时返回空数组并走 success;不支持的类型会被跳过,不会令整个请求报 203。
health.subscribeSample(options)
subscribeSample(options: {
dataType: number
callback: (sample: Sample) => void
fail?: (data: object, code: number) => void
}): voidhealth.subscribeSample({
dataType: health.DATA_TYPES.HEART_RATE,
callback(sample) {
console.log(`heart rate=${sample.value}, time=${sample.timeStamp}`)
},
fail(data, code) {
if (code === 203) console.log('当前固件不支持此数据类型')
}
})该方法不返回订阅 ID;每种类型以 dataType 标识。未支持的类型会走 fail,错误码为 203。
health.unsubscribeSample(options)
unsubscribeSample(options: { dataType: number }): voidonDestroy() {
health.unsubscribeSample({
dataType: health.DATA_TYPES.HEART_RATE
})
}声明 config.background.features 后,应用进入后台仍会收到订阅回调。无需在 onShow/onHide 重复订阅;不再使用时必须取消,避免后台功耗与重复回调。
错误码
| code | 含义 |
|---|---|
200 | 通用/系统错误 |
202 | 参数错误,例如 dataTypes 缺失或为空 |
203 | 当前数据类型不支持 |
固件扩展成员
| 方法 | 说明 |
|---|---|
health.getHr() | 读取当前/最近心率的旧便捷入口 |
health.getTodayCalorie() | 读取今日活动卡路里相关数据 |
这两个成员没有进入公开指南,旧 JIDL 也没有定义可用的返回对象或回调契约。普通应用应使用采样族;卡路里接口在公开版本中尚未开放。
机型可用性
| 数据类型 | Xiaomi Smart Band 10 Pro | Xiaomi Watch S4 41mm |
|---|---|---|
| 心率 | ✅ | ✅ |
| 血氧 | △ | △ |
| 压力 | △ | △ |