在这里插入图片描述

每日一句正能量

接纳福祸的交替,才能拥抱生活的完整。
生活不是一条直线,而是起伏的波浪。只想要福、不想要祸,等于否定了一半的现实。当你不再抗拒“坏的部分”,反而能看到每一段经历都在塑造完整的你。

一、前言:当AI健康管家常驻手腕边缘

在快节奏的现代生活中,健康管理往往被忽视。传统的健康监测应用需要用户主动打开查看,数据分散在不同设备中,缺乏统一的健康洞察。当用户久坐办公时,没有人提醒起身活动;当心率异常时,没有即时预警;当睡眠质量下降时,没有改善建议。

HarmonyOS 6(API 23)带来的悬浮导航(Floating Navigation)沉浸光感(Immersive Lighting)能力,让我们有机会打造一个常驻屏幕边缘的AI健康管家——它像一位专业的健康顾问,在你日常使用时静静悬浮在屏幕角落,实时监测生命体征;它通过光效反馈健康状态,在久坐时以琥珀色光效温柔提醒,在心率异常时以红色脉冲紧急警示,在达成运动目标时以绿色光效为你喝彩。

核心创新点:

  • 💓 生命体征悬浮监测:胶囊形态常驻显示心率/血氧/压力,支持跨应用健康追踪
  • 💡 健康状态光感:通过设备边框光效颜色变化,反映实时健康状态
  • 🤖 多模态健康智能体:支持语音健康咨询、症状自查、用药提醒
  • 🏃 情境感知运动:自动识别运动状态,动态调整监测频率与提醒策略

二、应用场景设计

2.1 场景一:久坐提醒

用户连续办公2小时未起身,悬浮胶囊边框泛起琥珀色呼吸光效,轻点展开显示"已久坐2小时,建议起身活动5分钟",并提供简单的办公室拉伸动画指导。

2.2 场景二:心率异常预警

用户会议中情绪激动,心率持续超过100bpm。设备四周边框泛起红色脉冲光效,悬浮窗自动展开显示心率趋势图,智能体语音建议"检测到心率偏高,建议深呼吸放松",并引导进行1分钟呼吸训练。

2.3 场景三:睡眠优化建议

清晨醒来,AI智能体分析昨晚睡眠数据,在悬浮窗推送"深度睡眠不足,建议今晚22:30前放下手机,卧室温度调至24℃"。边框泛起柔和的紫色光效,表示"睡眠优化模式"。

三、技术架构

┌─────────────────────────────────────────────────────────────┐
│         HarmonyOS Health Monitoring Companion Agent         │
├─────────────┬─────────────┬─────────────┬───────────────────┤
│  悬浮窗UI   │  沉浸光感   │  智能体引擎  │   健康数据模块     │
│  FloatUI    │  Lighting   │  AI Engine  │   HealthDataHub │
├─────────────┴─────────────┴─────────────┴───────────────────┤
│                    健康感知层(Health Sensing)                │
│   心率监测 │ 血氧检测 │ 压力分析 │ 睡眠追踪 │ 运动识别        │
├─────────────────────────────────────────────────────────────┤
│              HarmonyOS 6 (API 23) 系统服务层                 │
│   悬浮导航 │ 光感服务 │ 智能体框架 │ 传感器服务 │ 健康服务      │
└─────────────────────────────────────────────────────────────┘

四、核心代码实现

4.1 健康数据感知引擎(HealthDataEngine)

这是整个系统的"健康之眼",通过传感器与健康服务实时采集生命体征数据。

// engine/HealthDataEngine.ets
import { sensor } from '@kit.SensorServiceKit';
import { health } from '@kit.HealthServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

export interface HealthContext {
  heartRate: number;              // 心率 bpm
  bloodOxygen: number;            // 血氧饱和度 %
  stressLevel: number;            // 压力指数 0-100
  stepCount: number;              // 今日步数
  calories: number;               // 今日消耗卡路里
  sleepQuality: SleepQuality;     // 睡眠质量
  sedentaryTime: number;          // 连续久坐时间(分钟)
  activityLevel: ActivityLevel;   // 活动等级
  abnormalAlerts: HealthAlert[];  // 异常告警
  lastUpdate: number;             // 最后更新时间
}

export interface SleepQuality {
  score: number;                  // 睡眠评分 0-100
  deepSleep: number;              // 深睡时长(分钟)
  lightSleep: number;             // 浅睡时长(分钟)
  remSleep: number;               // REM时长(分钟)
  awakeTimes: number;             // 醒来次数
}

export enum ActivityLevel {
  SEDENTARY = 'sedentary',       // 久坐
  LIGHT = 'light',               // 轻度活动
  MODERATE = 'moderate',         // 中度活动
  VIGOROUS = 'vigorous'          // 剧烈活动
}

export interface HealthAlert {
  type: 'heart_rate' | 'blood_oxygen' | 'stress' | 'sedentary' | 'sleep';
  level: 'info' | 'warning' | 'critical';
  message: string;
  suggestion: string;
  timestamp: number;
}

export class HealthDataEngine {
  private sensorManager: sensor.SensorManager | null = null;
  private healthClient: health.HealthClient | null = null;
  private contextCallbacks: Array<(context: HealthContext) => void> = [];
  private currentContext: HealthContext | null = null;
  private updateInterval: number = 0;
  private heartRateHistory: number[] = [];
  private lastActivityTime: number = Date.now();

  /**
   * 初始化健康数据感知
   * 亮点:多传感器融合 + 健康服务深度集成
   */
  async init(): Promise<void> {
    try {
      // 申请健康数据权限
      const hasPermission = await this.requestHealthPermission();
      if (!hasPermission) {
        console.warn('[HealthData] 健康数据权限未授予');
        return;
      }

      // 初始化传感器管理器
      this.sensorManager = sensor.getSensorManager();

      // 初始化健康服务客户端
      this.healthClient = health.getHealthClient();

      // 注册心率传感器监听
      this.registerHeartRateSensor();

      // 注册加速度计用于活动检测
      this.registerActivitySensor();

      // 启动定时刷新(每5秒)
      this.updateInterval = setInterval(() => this.refreshHealthData(), 5000);

      // 首次数据加载
      await this.refreshHealthData();

      console.info('[HealthData] 健康数据感知引擎初始化完成');
    } catch (err) {
      console.error(`[HealthData] 初始化失败: ${JSON.stringify(err)}`);
    }
  }

  /**
   * 注册心率传感器
   */
  private registerHeartRateSensor(): void {
    this.sensorManager?.on(sensor.SensorId.SENSOR_TYPE_HEART_RATE, (data) => {
      if (data.heartRate > 0) {
        this.heartRateHistory.push(data.heartRate);
        // 保留最近30个数据点
        if (this.heartRateHistory.length > 30) {
          this.heartRateHistory.shift();
        }
      }
    });
  }

  /**
   * 注册活动检测传感器
   */
  private registerActivitySensor(): void {
    this.sensorManager?.on(sensor.SensorId.SENSOR_TYPE_ACCELEROMETER, (data) => {
      const magnitude = Math.sqrt(data.x * data.x + data.y * data.y + data.z * data.z);
      
      // 检测活动
      if (magnitude > 15) {
        this.lastActivityTime = Date.now();
      }
    });
  }

  /**
   * 刷新健康数据
   */
  private async refreshHealthData(): Promise<void> {
    try {
      // 获取今日步数
      const steps = await this.healthClient?.readData({
        dataType: health.DataType.DT_CONTINUOUS_STEPS_TOTAL,
        timeRange: {
          startTime: this.getTodayStart(),
          endTime: Date.now()
        }
      }) || 0;

      // 获取今日卡路里
      const calories = await this.healthClient?.readData({
        dataType: health.DataType.DT_CONTINUOUS_CALORIES_BURNT_TOTAL,
        timeRange: {
          startTime: this.getTodayStart(),
          endTime: Date.now()
        }
      }) || 0;

      // 获取血氧(如有传感器)
      const bloodOxygen = await this.readBloodOxygen();

      // 获取压力指数
      const stress = await this.estimateStressLevel();

      // 计算久坐时间
      const sedentaryTime = this.calculateSedentaryTime();

      // 判断活动等级
      const activityLevel = this.detectActivityLevel(steps, sedentaryTime);

      // 获取睡眠数据
      const sleepQuality = await this.readSleepData();

      // 检测异常
      const alerts = this.detectAbnormalities();

      // 计算平均心率
      const avgHeartRate = this.heartRateHistory.length > 0
        ? Math.round(this.heartRateHistory.reduce((a, b) => a + b, 0) / this.heartRateHistory.length)
        : 75;

      const context: HealthContext = {
        heartRate: avgHeartRate,
        bloodOxygen,
        stressLevel: stress,
        stepCount: steps as number,
        calories: calories as number,
        sleepQuality,
        sedentaryTime,
        activityLevel,
        abnormalAlerts: alerts,
        lastUpdate: Date.now()
      };

      this.currentContext = context;
      this.contextCallbacks.forEach(cb => cb(context));

    } catch (err) {
      console.error(`[HealthData] 刷新失败: ${JSON.stringify(err)}`);
    }
  }

  /**
   * 读取血氧
   */
  private async readBloodOxygen(): Promise<number> {
    try {
      const data = await this.healthClient?.readData({
        dataType: health.DataType.DT_INSTANTANEOUS_SPO2,
        timeRange: { startTime: Date.now() - 60000, endTime: Date.now() }
      });
      return (data as any)?.value || 98;
    } catch {
      return 98; // 默认值
    }
  }

  /**
   * 估算压力指数
   * 基于心率变异性(HRV)简化计算
   */
  private async estimateStressLevel(): Promise<number> {
    if (this.heartRateHistory.length < 5) return 30;

    // 计算心率变异性(简化:标准差)
    const mean = this.heartRateHistory.reduce((a, b) => a + b, 0) / this.heartRateHistory.length;
    const variance = this.heartRateHistory.reduce((sq, n) => sq + Math.pow(n - mean, 2), 0) / this.heartRateHistory.length;
    const stdDev = Math.sqrt(variance);

    // HRV越低,压力越高
    const hrvScore = Math.min(stdDev * 10, 100);
    const stress = Math.max(100 - hrvScore, 0);

    return Math.round(stress);
  }

  /**
   * 计算久坐时间
   */
  private calculateSedentaryTime(): number {
    const inactiveDuration = (Date.now() - this.lastActivityTime) / 60000;
    return Math.round(inactiveDuration);
  }

  /**
   * 检测活动等级
   */
  private detectActivityLevel(steps: number, sedentaryMinutes: number): ActivityLevel {
    if (sedentaryMinutes > 60) return ActivityLevel.SEDENTARY;
    
    const hourlySteps = steps / (new Date().getHours() || 1);
    if (hourlySteps < 500) return ActivityLevel.LIGHT;
    if (hourlySteps < 1000) return ActivityLevel.MODERATE;
    return ActivityLevel.VIGOROUS;
  }

  /**
   * 读取睡眠数据
   */
  private async readSleepQuality(): Promise<<SleepQuality> {
    try {
      const sleepData = await this.healthClient?.readData({
        dataType: health.DataType.DT_SLEEP,
        timeRange: {
          startTime: this.getYesterdayStart(),
          endTime: this.getTodayStart()
        }
      }) as any;

      return {
        score: sleepData?.score || 75,
        deepSleep: sleepData?.deepSleepTime || 90,
        lightSleep: sleepData?.lightSleepTime || 240,
        remSleep: sleepData?.remSleepTime || 60,
        awakeTimes: sleepData?.awakeTimes || 2
      };
    } catch {
      return { score: 75, deepSleep: 90, lightSleep: 240, remSleep: 60, awakeTimes: 2 };
    }
  }

  /**
   * 检测健康异常
   */
  private detectAbnormalities(): HealthAlert[] {
    const alerts: HealthAlert[] = [];
    const hr = this.heartRateHistory.length > 0 ? this.heartRateHistory[this.heartRateHistory.length - 1] : 75;

    // 心率异常
    if (hr > 120) {
      alerts.push({
        type: 'heart_rate',
        level: 'warning',
        message: `心率偏高: ${hr}bpm`,
        suggestion: '建议深呼吸放松,如持续偏高请就医',
        timestamp: Date.now()
      });
    } else if (hr < 50) {
      alerts.push({
        type: 'heart_rate',
        level: 'warning',
        message: `心率偏低: ${hr}bpm`,
        suggestion: '如感到不适请就医检查',
        timestamp: Date.now()
      });
    }

    // 久坐提醒
    const sedentary = this.calculateSedentaryTime();
    if (sedentary > 60) {
      alerts.push({
        type: 'sedentary',
        level: 'info',
        message: `已久坐${sedentary}分钟`,
        suggestion: '建议起身活动5分钟,做简单拉伸',
        timestamp: Date.now()
      });
    }

    return alerts;
  }

  private getTodayStart(): number {
    const now = new Date();
    return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  }

  private getYesterdayStart(): number {
    return this.getTodayStart() - 24 * 3600 * 1000;
  }

  onContextChange(callback: (context: HealthContext) => void): void {
    this.contextCallbacks.push(callback);
  }

  getCurrentContext(): HealthContext | null {
    return this.currentContext;
  }

  destroy(): void {
    clearInterval(this.updateInterval);
    this.sensorManager?.off(sensor.SensorId.SENSOR_TYPE_HEART_RATE);
    this.sensorManager?.off(sensor.SensorId.SENSOR_TYPE_ACCELEROMETER);
  }
}

4.2 沉浸光感健康状态反馈(HealthLightingController)

光效是健康状态的"情绪化延伸",让用户无需看屏幕就能感知身体状况。

// lighting/HealthLightingController.ets
import { lighting } from '@kit.ArkUI';
import { ActivityLevel, HealthAlert } from '../engine/HealthDataEngine';

export class HealthLightingController {
  private currentMode: string = 'normal';
  private alertQueue: HealthAlert[] = [];

  /**
   * 初始化健康光感
   * 设计哲学:光效应成为健康的"情绪晴雨表"
   */
  async init(): Promise<void> {
    if (!lighting.isImmersiveLightSupported()) {
      console.warn('[HealthLight] 设备不支持沉浸光感');
      return;
    }

    // 初始状态:柔和白色,表示健康监测就绪
    await this.setLightEffect({
      type: 'solid',
      position: 'bottom_edge',
      color: '#E0E0E0',
      brightness: 15,
      duration: 0
    });

    console.info('[HealthLight] 健康光感初始化完成');
  }

  /**
   * 根据健康状态更新光效
   */
  async updateByHealth(context: {
    heartRate: number;
    stressLevel: number;
    activityLevel: ActivityLevel;
    sedentaryTime: number;
    alerts: HealthAlert[];
  }): Promise<void> {
    // 异常告警最高优先级
    const criticalAlert = context.alerts.find(a => a.level === 'critical');
    if (criticalAlert) {
      await this.setCriticalAlert(criticalAlert);
      return;
    }

    const warningAlert = context.alerts.find(a => a.level === 'warning');
    if (warningAlert) {
      await this.setWarningAlert(warningAlert);
      return;
    }

    // 久坐提醒
    if (context.sedentaryTime > 60) {
      await this.setSedentaryReminder(context.sedentaryTime);
      return;
    }

    // 活动等级光效
    await this.setActivityLighting(context.activityLevel, context.heartRate, context.stressLevel);
  }

  /**
   * 严重健康告警
   */
  private async setCriticalAlert(alert: HealthAlert): Promise<void> {
    await lighting.setImmersiveLight({
      type: 'flashing',
      position: 'all_edges',
      color: '#FF1744',
      brightness: 80,
      duration: 0,
      flashCount: -1,
      frequency: 500
    });
  }

  /**
   * 警告级健康提醒
   */
  private async setWarningAlert(alert: HealthAlert): Promise<void> {
    const colors: Record<string, string> = {
      'heart_rate': '#FF9100',
      'blood_oxygen': '#FF9100',
      'stress': '#FFD600',
      'sedentary': '#FFD600',
      'sleep': '#448AFF'
    };

    await lighting.setImmersiveLight({
      type: 'breathing',
      position: 'all_edges',
      color: colors[alert.type] || '#FF9100',
      brightness: 50,
      duration: 0,
      frequency: 1500
    });
  }

  /**
   * 久坐提醒光效
   */
  private async setSedentaryReminder(minutes: number): Promise<void> {
    // 久坐时间越长,光效越明显
    const intensity = Math.min((minutes - 60) / 60, 1); // 60-120分钟渐变

    await lighting.setImmersiveLight({
      type: 'wave',
      position: 'bottom_edge',
      color: '#FF9100',
      brightness: 30 + intensity * 30,
      duration: 0,
      direction: 'alternate',
      speed: 'slow'
    });
  }

  /**
   * 活动等级光效
   */
  private async setActivityLighting(
    level: ActivityLevel,
    heartRate: number,
    stress: number
  ): Promise<void> {
    const effects: Record<<ActivityLevel, lighting.LightEffect> = {
      [ActivityLevel.SEDENTARY]: {
        type: 'solid',
        position: 'bottom_edge',
        color: '#9E9E9E',
        brightness: 15,
        duration: 0
      },
      [ActivityLevel.LIGHT]: {
        type: 'breathing',
        position: 'bottom_edge',
        color: '#69F0AE',
        brightness: 25,
        duration: 0,
        frequency: 3000
      },
      [ActivityLevel.MODERATE]: {
        type: 'breathing',
        position: 'all_edges',
        color: '#00E676',
        brightness: 35,
        duration: 0,
        frequency: 2000
      },
      [ActivityLevel.VIGOROUS]: {
        type: 'flashing',
        position: 'all_edges',
        color: '#FF1744',
        brightness: 45,
        duration: 0,
        flashCount: -1,
        frequency: 1000
      }
    };

    await lighting.setImmersiveLight(effects[level]);
  }

  /**
   * 运动目标达成庆祝
   */
  async celebrateGoal(goalType: string): Promise<void> {
    const colors = ['#00E676', '#00B0FF', '#2979FF', '#7C4DFF', '#F50057', '#FF9100'];
    
    for (const color of colors) {
      await lighting.setImmersiveLight({
        type: 'solid',
        position: 'all_edges',
        color: color,
        brightness: 50,
        duration: 150
      });
      await new Promise(resolve => setTimeout(resolve, 150));
    }

    await this.reset();
  }

  /**
   * 睡眠模式光效
   */
  async setSleepMode(): Promise<void> {
    await lighting.setImmersiveLight({
      type: 'solid',
      position: 'bottom_edge',
      color: '#4A148C',
      brightness: 5,
      duration: 0
    });
  }

  /**
   * 呼吸训练引导光效
   */
  async breathingGuide(phase: 'inhale' | 'hold' | 'exhale'): Promise<void> {
    const effects: Record<string, lighting.LightEffect> = {
      'inhale': {
        type: 'breathing',
        position: 'all_edges',
        color: '#00E676',
        brightness: 60,
        duration: 4000,
        frequency: 4000
      },
      'hold': {
        type: 'solid',
        position: 'all_edges',
        color: '#FFD600',
        brightness: 50,
        duration: 2000
      },
      'exhale': {
        type: 'breathing',
        position: 'all_edges',
        color: '#448AFF',
        brightness: 30,
        duration: 6000,
        frequency: 6000
      }
    };

    await lighting.setImmersiveLight(effects[phase]);
  }

  async reset(): Promise<void> {
    await lighting.resetImmersiveLight();
  }
}

4.3 健康智能体引擎(HealthAgentEngine)

这是系统的"健康大脑",负责分析健康数据、生成建议、提供健康咨询。

// agent/HealthAgentEngine.ets
import { ai } from '@kit.AiKit';
import { HealthContext, SleepQuality, ActivityLevel } from '../engine/HealthDataEngine';

export interface HealthSuggestion {
  type: 'activity' | 'sleep' | 'nutrition' | 'stress' | 'checkup';
  title: string;
  description: string;
  priority: 'high' | 'medium' | 'low';
  actions: string[];
  expectedBenefit: string;
}

export interface HealthConsultation {
  question: string;
  answer: string;
  relatedMetrics: string[];
  disclaimer: string;
}

export class HealthAgentEngine {
  private agent: ai.AgentSession | null = null;
  private userProfile: UserHealthProfile | null = null;

  /**
   * 初始化健康智能体
   * 加载健康知识库
   */
  async init(): Promise<void> {
    const model = await ai.createModel({
      modelId: 'harmonyos-health-v1',
      type: ai.ModelType.LOCAL,
      capabilities: ['health_analysis', 'symptom_check', 'wellness_coaching']
    });

    this.agent = await ai.createAgentSession({
      model: model,
      systemPrompt: `你是一位专业的健康管理师,精通运动医学、营养学和心理健康。
        请基于用户的健康数据,提供:
        1. 个性化的健康建议
        2. 运动计划推荐
        3. 睡眠质量改善方案
        4. 压力管理技巧
        5. 症状初步评估(非诊断)
        
        回答要求:
        - 建议必须具体可执行
        - 强调预防而非治疗
        - 涉及医疗建议时添加免责声明
        - 使用中文回答,语气亲切鼓励`
    });

    console.info('[HealthAgent] 健康智能体初始化完成');
  }

  /**
   * 生成健康建议
   */
  async generateSuggestions(context: HealthContext): Promise<<HealthSuggestion[]> {
    if (!this.agent) return [];

    const suggestions: HealthSuggestion[] = [];

    // 基于规则快速生成
    const ruleBased = this.generateRuleBasedSuggestions(context);
    suggestions.push(...ruleBased);

    // AI深度分析
    const aiSuggestions = await this.generateAISuggestions(context);
    suggestions.push(...aiSuggestions);

    return suggestions.sort((a, b) => {
      const priorityOrder = { high: 0, medium: 1, low: 2 };
      return priorityOrder[a.priority] - priorityOrder[b.priority];
    });
  }

  /**
   * 基于规则的建议
   */
  private generateRuleBasedSuggestions(context: HealthContext): HealthSuggestion[] {
    const suggestions: HealthSuggestion[] = [];

    // 久坐提醒
    if (context.sedentaryTime > 60) {
      suggestions.push({
        type: 'activity',
        title: '久坐提醒',
        description: `您已连续久坐${context.sedentaryTime}分钟,建议起身活动`,
        priority: context.sedentaryTime > 120 ? 'high' : 'medium',
        actions: [
          '起身走动5分钟',
          '做颈部拉伸运动',
          '远眺放松眼睛'
        ],
        expectedBenefit: '缓解肌肉紧张,促进血液循环'
      });
    }

    // 心率异常
    if (context.heartRate > 100) {
      suggestions.push({
        type: 'stress',
        title: '心率偏高',
        description: `当前心率${context.heartRate}bpm,高于正常静息范围`,
        priority: 'high',
        actions: [
          '进行1分钟深呼吸练习',
          '暂时停下手中工作',
          '如持续偏高请就医'
        ],
        expectedBenefit: '降低交感神经兴奋,恢复心率平稳'
      });
    }

    // 睡眠不足
    if (context.sleepQuality.score < 60) {
      suggestions.push({
        type: 'sleep',
        title: '睡眠质量改善',
        description: `昨晚睡眠评分${context.sleepQuality.score}分,深度睡眠仅${context.sleepQuality.deepSleep}分钟`,
        priority: 'medium',
        actions: [
          '今晚22:30前放下手机',
          '卧室温度调至24℃',
          '睡前进行10分钟冥想'
        ],
        expectedBenefit: '提升深度睡眠比例,改善日间精力'
      });
    }

    // 运动不足
    if (context.stepCount < 5000 && new Date().getHours() > 18) {
      suggestions.push({
        type: 'activity',
        title: '今日运动不足',
        description: `今日步数${context.stepCount},距离目标还有差距`,
        priority: 'low',
        actions: [
          '饭后散步20分钟',
          '做一组深蹲练习',
          '爬楼梯代替电梯'
        ],
        expectedBenefit: '提升基础代谢,改善心肺功能'
      });
    }

    return suggestions;
  }

  /**
   * AI深度健康分析
   */
  private async generateAISuggestions(context: HealthContext): Promise<<HealthSuggestion[]> {
    const prompt = `请基于以下健康数据生成深度建议:
      
      当前状态:
      - 心率:${context.heartRate}bpm
      - 血氧:${context.bloodOxygen}%
      - 压力指数:${context.stressLevel}/100
      - 今日步数:${context.stepCount}
      - 连续久坐:${context.sedentaryTime}分钟
      - 睡眠评分:${context.sleepQuality.score}/100
      - 活动等级:${context.activityLevel}
      
      请生成2-3条个性化的健康洞察和建议。`;

    const result = await this.agent!.invoke({
      input: { question: prompt },
      options: { maxTokens: 512, temperature: 0.4 }
    });

    return this.parseAISuggestions(result);
  }

  /**
   * 健康咨询问答
   */
  async healthConsultation(question: string, context: HealthContext): Promise<<HealthConsultation> {
    if (!this.agent) {
      return {
        question,
        answer: '智能体未初始化,请稍后重试',
        relatedMetrics: [],
        disclaimer: '本回答仅供参考,不构成医疗建议'
      };
    }

    const prompt = `用户健康咨询:${question}
      
      用户当前健康数据:
      - 心率:${context.heartRate}bpm
      - 血氧:${context.bloodOxygen}%
      - 压力:${context.stressLevel}/100
      - 今日步数:${context.stepCount}
      - 睡眠评分:${context.sleepQuality.score}
      
      请给出专业但易懂的健康建议,必须包含免责声明。`;

    const result = await this.agent!.invoke({
      input: { question: prompt },
      options: { maxTokens: 512, temperature: 0.3 }
    });

    return {
      question,
      answer: result.data?.answer || '抱歉,我无法回答这个问题',
      relatedMetrics: result.data?.relatedMetrics || [],
      disclaimer: '本回答仅供参考,不能替代专业医疗诊断。如有不适请及时就医。'
    };
  }

  /**
   * 生成呼吸训练指导
   */
  async generateBreathingGuide(stressLevel: number): Promise<<{
    inhale: number;
    hold: number;
    exhale: number;
    cycles: number;
  }> {
    // 根据压力等级调整呼吸节奏
    if (stressLevel > 70) {
      return { inhale: 4, hold: 2, exhale: 6, cycles: 5 }; // 快速缓解
    } else if (stressLevel > 40) {
      return { inhale: 4, hold: 4, exhale: 6, cycles: 3 }; // 标准节奏
    }
    return { inhale: 4, hold: 7, exhale: 8, cycles: 3 }; // 深度放松
  }

  /**
   * 生成运动计划
   */
  async generateWorkoutPlan(context: HealthContext): Promise<<{
    type: string;
    duration: number;
    intensity: string;
    exercises: string[];
    calories: number;
  }> {
    const prompt = `基于用户当前状态生成运动计划:
      活动等级:${context.activityLevel}
      心率:${context.heartRate}bpm
      今日步数:${context.stepCount}
      连续久坐:${context.sedentaryTime}分钟
      
      请生成一个适合当前状态的运动计划。`;

    const result = await this.agent!.invoke({
      input: { question: prompt },
      options: { maxTokens: 256, temperature: 0.4 }
    });

    return result.data?.workout || {
      type: '轻度有氧运动',
      duration: 20,
      intensity: '低',
      exercises: ['快走', '拉伸'],
      calories: 100
    };
  }

  private parseAISuggestions(result: ai.ModelOutput): HealthSuggestion[] {
    const data = result.data || {};
    return (data.suggestions || []).map((s: any) => ({
      type: s.type || 'activity',
      title: s.title,
      description: s.description,
      priority: s.priority || 'medium',
      actions: s.actions || [],
      expectedBenefit: s.expectedBenefit || ''
    }));
  }

  destroy(): void {
    this.agent?.destroy();
  }
}

interface UserHealthProfile {
  age: number;
  gender: string;
  height: number;
  weight: number;
  medicalConditions: string[];
  fitnessGoal: string;
}

4.4 悬浮窗健康面板(HealthFloatWindow)

// float/HealthFloatWindow.ets
import { window } from '@kit.ArkUI';
import { emitter } from '@kit.BasicServicesKit';
import { HealthContext } from '../engine/HealthDataEngine';
import { HealthSuggestion } from '../agent/HealthAgentEngine';

export class HealthFloatWindow {
  private floatWin: window.Window | null = null;
  private currentLevel: 'capsule' | 'panel' = 'capsule';

  async create(): Promise<void> {
    const option: window.WindowOption = {
      name: 'HealthCompanion',
      windowType: window.WindowType.TYPE_FLOAT,
      ctx: getContext(this)
    };

    this.floatWin = await window.createWindow(getContext(this), option);
    
    // 胶囊形态:显示核心健康指标
    await this.floatWin.resize({ width: 110, height: 90 });
    await this.floatWin.moveWindowTo({ x: 940, y: 120 });
    await this.floatWin.setWindowTouchable(true);
    await this.floatWin.setUIContent('pages/HealthCapsulePage');
    await this.floatWin.showWindow();
  }

  async expandToPanel(context: HealthContext, suggestions: HealthSuggestion[]): Promise<void> {
    if (!this.floatWin) return;
    
    this.currentLevel = 'panel';
    await this.floatWin.resize({ width: 440, height: 760 });
    await this.floatWin.moveWindowTo({ x: 560, y: 60 });
    await this.floatWin.setUIContent('pages/HealthPanelPage');
    
    emitter.emit('showHealthPanel', { data: { context, suggestions } });
  }

  async autoExpandOnAlert(context: HealthContext): Promise<void> {
    if (!this.floatWin || this.currentLevel !== 'capsule') return;
    
    const hasCritical = context.abnormalAlerts.some(a => a.level === 'critical');
    const hasWarning = context.abnormalAlerts.some(a => a.level === 'warning');
    
    if (hasCritical || hasWarning) {
      const suggestions = []; // 实际应获取建议
      await this.expandToPanel(context, suggestions);
    }
  }

  async collapseToCapsule(): Promise<void> {
    if (!this.floatWin) return;
    
    this.currentLevel = 'capsule';
    await this.floatWin.resize({ width: 110, height: 90 });
    await this.floatWin.moveWindowTo({ x: 940, y: 120 });
    await this.floatWin.setUIContent('pages/HealthCapsulePage');
  }

  destroy(): void {
    this.floatWin?.destroyWindow();
  }
}

4.5 健康胶囊页面(HealthCapsulePage)

// pages/HealthCapsulePage.ets
import { emitter } from '@kit.BasicServicesKit';
import { ActivityLevel } from '../engine/HealthDataEngine';

@Entry
@Component
struct HealthCapsulePage {
  @State heartRate: number = 75;
  @State stepCount: number = 0;
  @State activityLevel: ActivityLevel = ActivityLevel.SEDENTARY;
  @State hasAlert: boolean = false;
  @State alertLevel: string = 'normal';

  private activityEmojis: Record<<ActivityLevel, string> = {
    [ActivityLevel.SEDENTARY]: '🪑',
    [ActivityLevel.LIGHT]: '🚶',
    [ActivityLevel.MODERATE]: '🏃',
    [ActivityLevel.VIGOROUS]: '🔥'
  };

  aboutToAppear() {
    emitter.on('updateHealthContext', (event) => {
      const ctx = event.data;
      this.heartRate = ctx?.heartRate || 75;
      this.stepCount = ctx?.stepCount || 0;
      this.activityLevel = ctx?.activityLevel || ActivityLevel.SEDENTARY;
      this.hasAlert = ctx?.abnormalAlerts?.length > 0;
      this.alertLevel = ctx?.abnormalAlerts?.[0]?.level || 'normal';
    });
  }

  build() {
    Stack() {
      // 告警脉冲
      if (this.hasAlert) {
        Circle()
          .width(120)
          .height(120)
          .fill(this.alertLevel === 'critical' ? '#FF1744' : '#FF9100')
          .opacity(0.2)
          .animation({
            duration: this.alertLevel === 'critical' ? 500 : 1000,
            iterations: -1,
            curve: Curve.EaseInOut,
            playMode: PlayMode.Alternate
          })
      }

      Column() {
        // 心率
        Row() {
          Text('💓')
            .fontSize(16)
          Text(`${this.heartRate}`)
            .fontSize(22)
            .fontWeight(FontWeight.Bold)
            .fontColor('#333')
            .margin({ left: 4 })
        }

        // 步数
        Text(`${this.formatSteps(this.stepCount)}`)
          .fontSize(12)
          .fontColor('#666')
          .margin({ top: 2 })

        // 活动状态
        Text(this.activityEmojis[this.activityLevel])
          .fontSize(16)
          .margin({ top: 2 })
      }
      .width(110)
      .height(90)
      .justifyContent(FlexAlign.Center)
      .backgroundColor('rgba(255, 255, 255, 0.95)')
      .borderRadius(20)
      .shadow({ radius: 12, color: 'rgba(0,0,0,0.12)' })
      .gesture(
        GestureGroup(GestureMode.Sequence,
          TapGesture({ count: 1 })
            .onAction(() => emitter.emit('expandToPanel')),
          LongPressGesture({ duration: 800 })
            .onAction(() => emitter.emit('startBreathingExercise'))
        )
      )
    }
    .width('100%')
    .height('100%')
    .align(Alignment.Center)
  }

  private formatSteps(steps: number): string {
    if (steps >= 10000) return `${(steps / 10000).toFixed(1)}万步`;
    return `${steps}`;
  }
}

4.6 健康面板页面(HealthPanelPage)

// pages/HealthPanelPage.ets
import { emitter } from '@kit.BasicServicesKit';
import { HealthContext, ActivityLevel } from '../engine/HealthDataEngine';
import { HealthSuggestion } from '../agent/HealthAgentEngine';

@Entry
@Component
struct HealthPanelPage {
  @State context: HealthContext | null = null;
  @State suggestions: HealthSuggestion[] = [];
  @State selectedTab: string = 'overview';
  @State isBreathing: boolean = false;
  @State breathingPhase: string = 'inhale';

  private tabs: string[] = ['overview', 'heart', 'sleep', 'activity'];

  aboutToAppear() {
    emitter.on('showHealthPanel', (event) => {
      this.context = event.data?.context;
      this.suggestions = event.data?.suggestions || [];
    });
  }

  build() {
    Column() {
      // 顶部标题栏
      Row() {
        Text('💓 健康伴侣')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .layoutWeight(1)
        
        Button('收起')
          .fontSize(12)
          .backgroundColor('#f0f0f0')
          .fontColor('#333')
          .onClick(() => emitter.emit('collapseToCapsule'))
      }
      .width('100%')
      .padding(16)

      // Tab切换
      Row() {
        ForEach(this.tabs, (tab: string) => {
          Button(this.getTabName(tab))
            .fontSize(12)
            .backgroundColor(this.selectedTab === tab ? '#2979FF' : '#f0f0f0')
            .fontColor(this.selectedTab === tab ? '#FFF' : '#666')
            .margin({ right: 8 })
            .onClick(() => this.selectedTab = tab)
        })
      }
      .width('100%')
      .margin({ bottom: 12 })

      // 内容区
      if (this.selectedTab === 'overview') {
        this.OverviewTab()
      } else if (this.selectedTab === 'heart') {
        this.HeartTab()
      } else if (this.selectedTab === 'sleep') {
        this.SleepTab()
      } else {
        this.ActivityTab()
      }

      // 智能建议
      if (this.suggestions.length > 0) {
        Text('💡 AI健康建议')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .width('100%')
          .margin({ top: 12, bottom: 8 })

        List() {
          ForEach(this.suggestions, (suggestion: HealthSuggestion) => {
            ListItem() {
              Column() {
                Row() {
                  Text(this.getSuggestionIcon(suggestion.type))
                    .fontSize(18)
                  
                  Text(suggestion.title)
                    .fontSize(14)
                    .fontWeight(FontWeight.Medium)
                    .layoutWeight(1)
                    .margin({ left: 8 })
                  
                  Text(suggestion.priority === 'high' ? '紧急' : suggestion.priority === 'medium' ? '重要' : '提示')
                    .fontSize(10)
                    .fontColor('#FFF')
                    .backgroundColor(
                      suggestion.priority === 'high' ? '#FF1744' :
                      suggestion.priority === 'medium' ? '#FF9100' : '#00C853'
                    )
                    .padding({ left: 6, right: 6, top: 2, bottom: 2 })
                    .borderRadius(4)
                }
                .width('100%')

                Text(suggestion.description)
                  .fontSize(12)
                  .fontColor('#666')
                  .width('100%')
                  .margin({ top: 4 })

                Column() {
                  ForEach(suggestion.actions, (action: string) => {
                    Text(`${action}`)
                      .fontSize(11)
                      .fontColor('#2979FF')
                      .width('100%')
                      .margin({ top: 2 })
                  })
                }
                .margin({ top: 6 })
                .padding(8)
                .backgroundColor('#E3F2FD')
                .borderRadius(6)
              }
              .padding(12)
              .backgroundColor('#fff')
              .borderRadius(8)
              .margin({ bottom: 8 })
              .shadow({ radius: 4, color: 'rgba(0,0,0,0.05)' })
            }
          })
        }
        .width('100%')
        .layoutWeight(1)
      }

      // 呼吸训练按钮
      Button(this.isBreathing ? '停止呼吸训练' : '🫁 开始呼吸训练')
        .fontSize(14)
        .backgroundColor(this.isBreathing ? '#FFEBEE' : '#E8F5E9')
        .fontColor(this.isBreathing ? '#C62828' : '#2E7D32')
        .width('100%')
        .margin({ top: 8 })
        .onClick(() => this.toggleBreathing())
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .backgroundColor('#FFF')
    .borderRadius(16)
  }

  @Builder
  OverviewTab() {
    Column() {
      // 核心指标卡片
      Row() {
        Column() {
          Text('💓')
            .fontSize(24)
          Text(`${this.context?.heartRate || 75}`)
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .fontColor(
              (this.context?.heartRate || 75) > 100 ? '#FF1744' :
              (this.context?.heartRate || 75) < 60 ? '#FF9100' : '#00C853'
            )
          Text('心率')
            .fontSize(12)
            .fontColor('#999')
        }
        .layoutWeight(1)

        Column() {
          Text('🩸')
            .fontSize(24)
          Text(`${this.context?.bloodOxygen || 98}%`)
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .fontColor(
              (this.context?.bloodOxygen || 98) < 95 ? '#FF1744' : '#00C853'
            )
          Text('血氧')
            .fontSize(12)
            .fontColor('#999')
        }
        .layoutWeight(1)

        Column() {
          Text('😰')
            .fontSize(24)
          Text(`${this.context?.stressLevel || 30}`)
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .fontColor(
              (this.context?.stressLevel || 30) > 70 ? '#FF1744' :
              (this.context?.stressLevel || 30) > 40 ? '#FF9100' : '#00C853'
            )
          Text('压力')
            .fontSize(12)
            .fontColor('#999')
        }
        .layoutWeight(1)
      }
      .width('100%')
      .padding(12)
      .backgroundColor('#f8f9fa')
      .borderRadius(12)
      .margin({ bottom: 12 })
    }
  }

  @Builder
  HeartTab() {
    Column() {
      Text('心率趋势')
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .width('100%')

      // 简化心率图
      Row() {
        ForEach([72, 75, 78, 82, 80, 76, 74, 75, 77, 79], (hr: number, index: number) => {
          Column() {
            Column()
              .width(6)
              .height(hr)
              .backgroundColor(hr > 80 ? '#FF1744' : '#2979FF')
              .borderRadius(3)
          }
          .layoutWeight(1)
          .alignItems(HorizontalAlign.Center)
        })
      }
      .width('100%')
      .height(120)
      .margin({ top: 8 })

      // 心率区间
      Row() {
        Text('静息: 60-70')
          .fontSize(12)
          .fontColor('#00C853')
        
        Text('燃脂: 110-130')
          .fontSize(12)
          .fontColor('#FFD600')
        
        Text('有氧: 130-150')
          .fontSize(12)
          .fontColor('#FF9100')
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceAround)
      .margin({ top: 8 })
    }
  }

  @Builder
  SleepTab() {
    Column() {
      Text(`睡眠评分: ${this.context?.sleepQuality.score || 75}/100`)
        .fontSize(18)
        .fontWeight(FontWeight.Bold)
        .width('100%')

      // 睡眠阶段分布
      Row() {
        Column() {
          Text('深睡')
            .fontSize(12)
            .fontColor('#666')
          Text(`${this.context?.sleepQuality.deepSleep || 90}min`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .fontColor('#4A148C')
          Column()
            .width(40)
            .height((this.context?.sleepQuality.deepSleep || 90) / 2)
            .backgroundColor('#4A148C')
            .borderRadius(4)
            .margin({ top: 4 })
        }
        .layoutWeight(1)

        Column() {
          Text('浅睡')
            .fontSize(12)
            .fontColor('#666')
          Text(`${this.context?.sleepQuality.lightSleep || 240}min`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .fontColor('#7C4DFF')
          Column()
            .width(40)
            .height((this.context?.sleepQuality.lightSleep || 240) / 5)
            .backgroundColor('#7C4DFF')
            .borderRadius(4)
            .margin({ top: 4 })
        }
        .layoutWeight(1)

        Column() {
          Text('REM')
            .fontSize(12)
            .fontColor('#666')
          Text(`${this.context?.sleepQuality.remSleep || 60}min`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .fontColor('#B388FF')
          Column()
            .width(40)
            .height((this.context?.sleepQuality.remSleep || 60))
            .backgroundColor('#B388FF')
            .borderRadius(4)
            .margin({ top: 4 })
        }
        .layoutWeight(1)
      }
      .width('100%')
      .margin({ top: 12 })
    }
  }

  @Builder
  ActivityTab() {
    Column() {
      // 步数圆环
      Stack() {
        Circle()
          .width(120)
          .height(120)
          .fill('none')
          .stroke('#E0E0E0')
          .strokeWidth(8)
        
        Circle()
          .width(120)
          .height(120)
          .fill('none')
          .stroke('#2979FF')
          .strokeWidth(8)
          .strokeDashArray([
            2 * Math.PI * 60 * ((this.context?.stepCount || 0) / 10000),
            2 * Math.PI * 60
          ])
          .strokeLineCap(LineCapStyle.Round)
          .animation({ duration: 1000 })

        Column() {
          Text(`${this.context?.stepCount || 0}`)
            .fontSize(28)
            .fontWeight(FontWeight.Bold)
            .fontColor('#2979FF')
          Text('/10000步')
            .fontSize(12)
            .fontColor('#999')
        }
      }
      .width(120)
      .height(120)
      .margin({ top: 12 })

      // 卡路里
      Text(`今日消耗: ${this.context?.calories || 0}kcal`)
        .fontSize(14)
        .fontColor('#666')
        .margin({ top: 12 })
    }
    .width('100%')
  }

  private getTabName(tab: string): string {
    const names: Record<string, string> = {
      'overview': '概览',
      'heart': '心率',
      'sleep': '睡眠',
      'activity': '运动'
    };
    return names[tab] || tab;
  }

  private getSuggestionIcon(type: string): string {
    const icons: Record<string, string> = {
      'activity': '🏃',
      'sleep': '😴',
      'nutrition': '🥗',
      'stress': '🧘',
      'checkup': '🏥'
    };
    return icons[type] || '💡';
  }

  private async toggleBreathing() {
    this.isBreathing = !this.isBreathing;
    if (this.isBreathing) {
      emitter.emit('startBreathingExercise');
    } else {
      emitter.emit('stopBreathingExercise');
    }
  }
}

4.7 主入口与系统集成(Index.ets)

// Index.ets
import { HealthDataEngine, ActivityLevel } from './engine/HealthDataEngine';
import { HealthLightingController } from './lighting/HealthLightingController';
import { HealthFloatWindow } from './float/HealthFloatWindow';
import { HealthAgentEngine } from './agent/HealthAgentEngine';
import { emitter } from '@kit.BasicServicesKit';

@Entry
@Component
struct HealthCompanionApp {
  private healthEngine: HealthDataEngine = new HealthDataEngine();
  private lightController: HealthLightingController = new HealthLightingController();
  private floatWindow: HealthFloatWindow = new HealthFloatWindow();
  private agentEngine: HealthAgentEngine = new HealthAgentEngine();
  private breathingInterval: number = 0;

  aboutToAppear() {
    this.initSystem();
  }

  aboutToDisappear() {
    this.healthEngine.destroy();
    this.lightController.reset();
    this.floatWindow.destroy();
    this.agentEngine.destroy();
    clearInterval(this.breathingInterval);
  }

  async initSystem() {
    // 1. 初始化沉浸光感
    await this.lightController.init();

    // 2. 初始化悬浮窗
    await this.floatWindow.create();

    // 3. 初始化智能体引擎
    await this.agentEngine.init();

    // 4. 初始化健康数据引擎
    await this.healthEngine.init();

    // 当健康数据变化时,更新光效和悬浮窗
    this.healthEngine.onContextChange(async (context) => {
      // 更新光效
      await this.lightController.updateByHealth({
        heartRate: context.heartRate,
        stressLevel: context.stressLevel,
        activityLevel: context.activityLevel,
        sedentaryTime: context.sedentaryTime,
        alerts: context.abnormalAlerts
      });
      
      // 异常自动展开
      await this.floatWindow.autoExpandOnAlert(context);
      
      // 生成建议
      const suggestions = await this.agentEngine.generateSuggestions(context);
      
      // 更新悬浮窗
      emitter.emit('updateHealthContext', { data: context });

      // 步数目标达成庆祝
      if (context.stepCount >= 10000 && context.stepCount < 10100) {
        await this.lightController.celebrateGoal('steps');
      }
    });

    // 5. 设置事件监听
    this.setupEventListeners();
  }

  private setupEventListeners() {
    emitter.on('expandToPanel', async () => {
      const context = this.healthEngine.getCurrentContext();
      if (context) {
        const suggestions = await this.agentEngine.generateSuggestions(context);
        await this.floatWindow.expandToPanel(context, suggestions);
      }
    });

    emitter.on('collapseToCapsule', async () => {
      await this.floatWindow.collapseToCapsule();
    });

    emitter.on('startBreathingExercise', async () => {
      const context = this.healthEngine.getCurrentContext();
      if (context) {
        const guide = await this.agentEngine.generateBreathingGuide(context.stressLevel);
        this.startBreathingCycle(guide);
      }
    });

    emitter.on('stopBreathingExercise', () => {
      clearInterval(this.breathingInterval);
      this.lightController.reset();
    });
  }

  private async startBreathingCycle(guide: { inhale: number; hold: number; exhale: number; cycles: number }) {
    let cycle = 0;
    
    const runCycle = async () => {
      if (cycle >= guide.cycles) {
        clearInterval(this.breathingInterval);
        await this.lightController.reset();
        return;
      }

      // 吸气
      await this.lightController.breathingGuide('inhale');
      await new Promise(r => setTimeout(r, guide.inhale * 1000));

      // 屏息
      await this.lightController.breathingGuide('hold');
      await new Promise(r => setTimeout(r, guide.hold * 1000));

      // 呼气
      await this.lightController.breathingGuide('exhale');
      await new Promise(r => setTimeout(r, guide.exhale * 1000));

      cycle++;
    };

    runCycle();
    this.breathingInterval = setInterval(runCycle, (guide.inhale + guide.hold + guide.exhale) * 1000);
  }

  build() {
    Column() {
      Text('💓 HarmonyOS健康监测伴侣')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 8 })
      
      Text('AI智能体正在守护您的健康...')
        .fontSize(14)
        .fontColor('#666')
      
      Text('悬浮窗常驻显示,光效反馈健康状态')
        .fontSize(12)
        .fontColor('#999')
        .margin({ top: 4 })
        .textAlign(TextAlign.Center)

      // 今日健康统计
      Column() {
        Text('📊 今日健康')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .margin({ bottom: 12 })

        Row() {
          Column() {
            Text('8,520')
              .fontSize(28)
              .fontWeight(FontWeight.Bold)
              .fontColor('#2979FF')
            Text('步数')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)

          Column() {
            Text('75')
              .fontSize(28)
              .fontWeight(FontWeight.Bold)
              .fontColor('#00C853')
            Text('心率')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)

          Column() {
            Text('82')
              .fontSize(28)
              .fontWeight(FontWeight.Bold)
              .fontColor('#7C4DFF')
            Text('睡眠分')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)
        }
        .width('100%')
      }
      .width('90%')
      .padding(20)
      .backgroundColor('#f8f9fa')
      .borderRadius(12)
      .margin({ top: 32 })

      // 当前状态
      Row() {
        Text('系统状态:')
          .fontSize(14)
          .fontColor('#666')
        
        Text('🟢 监测中')
          .fontSize(14)
          .fontColor('#00C853')
          .fontWeight(FontWeight.Medium)
      }
      .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

五、配置文件

// module.json5
{
  "module": {
    "name": "HealthCompanion",
    "type": "entry",
    "description": "鸿蒙智能体健康监测伴侣",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet", "2in1"],
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "健康监测伴侣主入口",
        "icon": "$media:layered_image",
        "label": "AI健康伴侣",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.SYSTEM_FLOAT_WINDOW",
        "reason": "需要悬浮窗权限以常驻显示健康状态"
      },
      {
        "name": "ohos.permission.ACCESS_SENSORS",
        "reason": "读取心率、加速度等传感器数据"
      },
      {
        "name": "ohos.permission.READ_HEALTH_DATA",
        "reason": "读取健康服务中的历史数据"
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "连接云端智能体服务"
      },
      {
        "name": "ohos.permission.ACCESS_AI_MODEL",
        "reason": "使用端侧AI模型进行健康分析"
      },
      {
        "name": "ohos.permission.MICROPHONE",
        "reason": "支持语音健康咨询"
      }
    ]
  }
}

六、效果展示与使用场景

6.1 典型健康场景

场景A:久坐提醒

白领小张连续办公2小时,悬浮胶囊边框泛起琥珀色波浪光效。轻点展开显示"已久坐120分钟,建议起身活动"。AI智能体推荐3个办公室拉伸动作,小张跟随完成5分钟活动后,光效恢复为绿色呼吸,表示"活动达标"。

场景B:心率异常

会议中李总情绪激动,心率持续110bpm。设备四周边框泛起红色脉冲光效,悬浮窗自动展开显示心率趋势。智能体语音建议"检测到心率偏高,建议进行1分钟呼吸训练",并引导吸气4秒-屏息4秒-呼气6秒的节律,边框光效同步变化辅助呼吸。

场景C:睡眠优化

清晨醒来,AI分析昨晚睡眠数据:深度睡眠仅60分钟。悬浮窗推送"深度睡眠不足,建议今晚22:30前放下手机,卧室温度调至24℃"。边框泛起柔和紫色光效表示"睡眠优化模式"。用户一键设置睡眠提醒,智能体生成个性化助眠方案。

6.2 光效语义设计

健康状态 光效表现 健康提示
健康正常 底部绿色慢呼吸 状态良好,保持
轻度活动 底部翠绿呼吸 继续活动
中度活动 全边框绿色呼吸 运动达标
剧烈运动 全边框红色快闪 注意心率
久坐提醒 底部琥珀波浪 起身活动
心率偏高 全边框橙色呼吸 深呼吸放松
心率异常 全边框红色快闪 立即关注
睡眠模式 底部紫色微光 助眠模式
呼吸训练 全边框随呼吸变化 跟随光效呼吸

七、性能与隐私优化

7.1 传感器策略

// 传感器优化策略
const sensorStrategy = {
  // 采样频率:根据活动状态动态调整
  samplingRate: {
    resting: 5000,    // 静息:5秒
    active: 1000,     // 活动:1秒
    exercising: 500   // 运动:0.5秒
  },
  
  // 数据聚合
  aggregation: {
    heartRate: 'avg',   // 心率取平均
    steps: 'sum',       // 步数累加
    calories: 'sum'    // 卡路里累加
  },
  
  // 本地缓存
  cache: {
    enabled: true,
    maxPoints: 1000,    // 最多缓存1000个数据点
    syncInterval: 300000 // 5分钟同步一次
  }
};

7.2 隐私保护

  • 数据本地优先:健康数据优先本地处理,敏感数据不上云
  • 脱敏传输:必须上传时进行数据脱敏和加密
  • 用户授权:每项健康数据独立授权,可随时撤销
  • 匿名分析:群体健康分析完全匿名化处理

八、总结与展望

本文展示了如何基于HarmonyOS 6(API 23)的悬浮导航沉浸光感能力,构建一个鸿蒙智能体驱动的沉浸式健康监测伴侣。与传统健康应用不同,它具备三个核心创新:

  1. 常驻感知:悬浮窗常驻屏幕边缘,健康状态随时可见,光效即时反馈
  2. 情境智能:AI智能体自动识别活动状态,动态调整监测频率与提醒策略
  3. 多模态交互:视觉(悬浮窗)+ 光感(边框)+ 听觉(语音)+ 触觉(震动)协同健康管理

未来演进方向:

  • 多设备协同:手机悬浮窗 + 手表实时监测 + 体脂秤数据同步
  • 预测性健康:基于AI预测潜在健康风险,提前干预
  • 家庭健康管理:家庭成员健康数据共享,异常互相提醒
  • 医疗级对接:与医院系统对接,实现远程健康监护

HarmonyOS 6的智能体框架和系统级交互创新,正在让"AI健康管家常驻身边"成为现实。对于关注健康的用户而言,这不仅是一个监测工具,更是一位24小时在线、懂身体、懂习惯、懂关怀的智能健康伙伴。


转载自:https://blog.csdn.net/u014727709/article/details/161420103
欢迎 👍点赞✍评论⭐收藏,欢迎指正

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐