PythonIDE Docs
中文
简体中文

health

HealthKit 授权、查询和体重写入。

HealthKit 健康数据:申请授权、读取步数/心率/睡眠等,写入体重样本。

边界:健康数据非常敏感。只请求当前功能需要的类型(如 stepsheart_rate),不要一次申请全部。查询结果只做展示,不做医疗诊断;不要把明细写入 storage

#模块概览

说明
导入import health
适合做什么步数/心率/睡眠仪表盘、体重记录、血压汇总
调用时机授权和读取放在按钮回调;不要在 body() 里读 HealthKit
推荐顺序is_available()request_authorization(read=[...]) → 查询
类型名用文档列出的 snake_case 类型名;时间范围用 Unix timestamp

#快速开始

下面脚本申请权限并读取最近 24 小时步数与心率:

python
import time
import health

if not health.is_available():
    print("当前设备不支持 HealthKit")
else:
    ok = health.request_authorization(read=["steps", "heart_rate"])
    if ok:
        end = time.time()
        start = end - 86400
        print("步数:", health.query_steps(start=start, end=end))
        print("心率:", health.query_heart_rate(start=start, end=end))
    else:
        print("用户未授权读取健康数据")

#AppUI 示例

授权和读取放在按钮回调;空结果展示明确状态。

python
import appui
import health

state = appui.State(
    status="未读取",
    steps="—",
    heart_rate="—",
    sleep="—",
)


def refresh_dashboard():
    if not health.is_available():
        state.batch_update(
            status="设备不支持 HealthKit",
            steps="—",
            heart_rate="—",
            sleep="—",
        )
        return

    read_types = ["steps", "heart_rate", "sleep"]
    if not health.request_authorization(read=read_types):
        state.batch_update(
            status="未授权读取健康数据",
            steps="—",
            heart_rate="—",
            sleep="—",
        )
        return

    steps = int(health.query_steps() or 0)
    heart_records = health.query_heart_rate() or []
    sleep_records = health.query_sleep() or []

    state.batch_update(
        status="最近 24 小时步数 · 7 天睡眠",
        steps=f"{steps:,}",
        heart_rate=f"{len(heart_records)} 条记录",
        sleep=f"{len(sleep_records)} 条记录",
    )


def body():
    return appui.NavigationStack(
        appui.Form([
            appui.Section("今日概览", [
                appui.LabeledContent("步数", value=state.steps),
                appui.LabeledContent("心率", value=state.heart_rate),
                appui.LabeledContent("睡眠", value=state.sleep),
            ]),
            appui.Section("操作", [
                appui.Button("刷新健康数据", action=refresh_dashboard)
                .button_style("bordered_prominent"),
                appui.Text(state.status).foreground_color("secondaryLabel"),
            ], footer="仅展示数据,不做诊断;真机 + 健康 App 有数据时效果最好。"),
        ]).navigation_title("健康")
    )


appui.run(body, state=state)

#API 参考

#速查

API作用
is_available()设备是否支持 HealthKit
request_authorization(read, write)申请读写权限 → bool
authorization_status(type_id)查询某类型授权状态
query_steps(start, end)步数(默认最近 24h)
query_heart_rate(start, end)心率记录列表
query_sleep(start, end)睡眠数据(默认最近 7 天)
query_weight(limit) / save_weight(kg)读取 / 写入体重
query_blood_pressure(start, end)血压记录(默认 30 天)
summarize_blood_pressure(records)血压统计汇总

#授权

python
import health

if health.is_available():
    ok = health.request_authorization(
        read=["steps", "heart_rate"],
        write=["weight"],
    )
    status = health.authorization_status("steps")

常用授权类型:stepsheart_rateweightsleepworkoutblood_pressure_systolicblood_pressure_diastolicdistancecalories

血压授权推荐使用组件类型:

python
health.request_authorization(
    read=["blood_pressure_systolic", "blood_pressure_diastolic"]
)

blood_pressure 只作为兼容简写,会在运行时展开为收缩压和舒张压组件;不要把任意 HealthKit 原始标识符传给 request_authorization

注意:只申请当前页面需要的类型,用户更容易接受。

#读取数据

query_steps(start=None, end=None) — 返回步数整数,默认最近 24 小时。

query_heart_rate(start, end) — 返回 [{value, start, end}, ...],单位 bpm。

query_sleep(start, end) — 睡眠分析记录,默认最近 7 天。

query_weight(limit=10) — 最近体重 [{value, date}, ...],单位 kg。

query_workouts(limit=20) — 最近锻炼记录。

query_quantity(type_id, start, end, unit) — 通用数量查询。

python
import time

end = time.time()
start = end - 86400
steps = health.query_steps(start=start, end=end)

#写入

save_weight(kg, timestamp=None) — 保存体重样本到 HealthKit。

python
health.save_weight(70.5)

需先在 request_authorizationwrite 中包含 weight

#血压汇总

python
records = health.query_blood_pressure()
summary = health.summarize_blood_pressure(records)
# count, latest, systolic/diastolic avg/min/max — 不做诊断

#常见错误

错误写法后果修正
read=["step_count"]read=["HKQuantityTypeIdentifier..."]类型名错误,授权会返回 False使用文档列出的 snake_case 类型
read=["blood_pressure"] 依赖组合别名不同系统对血压组合授权表现不一致使用 blood_pressure_systolic + blood_pressure_diastolic
一次申请所有权限用户易拒绝只申请当前需要的类型
健康明细写入 storage敏感数据扩散只展示汇总
对异常值做诊断结论误导用户仅展示原始/统计数据

#相关文档

文档用途
permission统一权限查询(HealthKit 用本模块授权)
storage非敏感偏好存储
原生能力入口MiniApp 场景配方

#健康仪表盘配方

python
import appui
import health


def body():
    return appui.Form([
        appui.Section("健康", [
            appui.Text("在授权后读取步数等指标并绑定到 State"),
        ])
    ])

预期效果:打开健康数据展示页;未授权时提示用户去系统设置授权。

#预期效果

运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。