构建更智能的可穿戴应用:集成 WeatherKit 与 CalendarKit

发布: (2025年12月11日 GMT+8 11:12)
5 min read
原文: Dev.to

Source: Dev.to

项目概述

  • 显示当前天气(温度、天气状况)
  • 从 CalendarKit 拉取今天的日程事件
  • 提供上下文感知的提示(例如:“在上午 10 点的会议前带把伞”)

设置

module.json5 中启用 Kit

{
  "module": {
    "requestPermissions": [
      "ohos.permission.READ_CALENDAR",
      "ohos.permission.INTERNET",
      "ohos.permission.ACCESS_INTERNET"
    ],
    "deviceType": ["wearable"],
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/MainAbility/EntryAbility.ets"
      }
    ]
  },
  "features": [
    { "name": "weather", "optional": false },
    { "name": "calendar", "optional": false }
  ]
}

.ets 文件中导入所需 Kit

import weather from '@ohos.weather';
import calendar from '@ohos.calendar';

第一步:使用 WeatherKit 获取天气数据

创建可复用的 WeatherService,根据当前位置信息获取天气(假设已获取位置权限)。

// WeatherService.ets
export class WeatherService {
  async getCurrentWeather(): Promise {
    const weatherInfo = await weather.getWeatherByLocation();
    return {
      temperature: weatherInfo.realtime?.temperature ?? '--',
      condition: weatherInfo.realtime?.text ?? 'Unknown'
    };
  }
}

第二步:使用 CalendarKit 获取今天的日程事件

通过 CalendarKit API 拉取今天的事件。

// CalendarService.ets
export class CalendarService {
  async getTodayEvents(): Promise {
    const start = new Date();
    start.setHours(0, 0, 0, 0);
    const end = new Date();
    end.setHours(23, 59, 59, 999);

    const events = await calendar.queryEvents({
      beginTime: start.getTime(),
      endTime: end.getTime()
    });

    return events.map(event =>
      `${new Date(event.beginTime).toLocaleTimeString()} - ${event.title}`
    );
  }
}

第三步:生成智能建议

ContextEngine 将天气数据和日程事件结合,生成每日建议。

// ContextEngine.ets
import { WeatherService } from './WeatherService';
import { CalendarService } from './CalendarService';

export class ContextEngine {
  private weatherService = new WeatherService();
  private calendarService = new CalendarService();

  async getDailySuggestion(): Promise {
    const weather = await this.weatherService.getCurrentWeather();
    const events = await this.calendarService.getTodayEvents();

    if (weather.condition.includes('Rain') && events.length > 0) {
      return `🌧️ Rain expected. Take an umbrella before your "${events[0]}"`;
    } else if (parseInt(weather.temperature) > 30) {
      return `🥵 It's hot today. Stay hydrated and wear light clothes.`;
    } else {
      return `✅ Weather looks good. You’re all set for your day!`;
    }
  }
}

第四步:在智能手表 UI 上展示所有内容

一个简易的 ArkUI 页面展示天气信息、日程事件以及智能建议。

// pages/PlannerPage.ets
import { ContextEngine } from '../services/ContextEngine';

@Entry
@Component
struct PlannerPage {
  @State temperature: string = '--';
  @State condition: string = 'Loading...';
  @State events: string[] = [];
  @State suggestion: string = 'Analyzing...';

  private contextEngine = new ContextEngine();

  async aboutToAppear() {
    const weather = await this.contextEngine.weatherService.getCurrentWeather();
    const events = await this.contextEngine.calendarService.getTodayEvents();
    const smartSuggestion = await this.contextEngine.getDailySuggestion();

    this.temperature = weather.temperature;
    this.condition = weather.condition;
    this.events = events;
    this.suggestion = smartSuggestion;
  }

  build() {
    Column({ space: 10 }) {
      Text(`🌡️ ${this.temperature}° - ${this.condition}`)
        .fontSize(20)
        .fontWeight(FontWeight.Bold)

      Text('📅 Today’s Events:')
        .fontSize(18)
        .fontWeight(FontWeight.Medium)

      ForEach(this.events, (event: string) => {
        Text(event).fontSize(14)
      }, item => item)

      Divider()

      Text(`🧠 Suggestion:`).fontSize(18).fontWeight(FontWeight.Medium)
      Text(this.suggestion).fontSize(16).fontColor(Color.Blue)
    }
    .padding(20)
  }
}

输出预览

手表上的示例界面:

🌡️ 22° — Light Rain
📅 Today’s Events:
09:00 AM - Team Stand‑up
14:30 PM - Project Review
🧠 Suggestion:
🌧️ Rain expected. Take an umbrella before your "09:00 AM - Team Stand‑up"

最后思考

HarmonyOS 可穿戴设备的功能远不止运动追踪。通过结合 WeatherKit 与 CalendarKit,你可以提供深度个性化、实时帮助用户的体验。

想进一步提升?

  • 使用 LocationKit 提升定位精度。
  • 添加 BackgroundTaskKit 定期刷新数据。
  • 扩展至多天预报或循环事件。

结论

Smart Day Planner 应用展示了开发者如何在 HarmonyOS 可穿戴设备上利用 WeatherKit 与 CalendarKit,打造真正的上下文感知与智能用户体验。通过动态组合:

  • 实时天气状况
  • 今日日程事件
  • 基于逻辑的上下文建议

手表从被动配件转变为主动助理。此类集成可用于:

  • 健康类应用(根据天气调整补水提醒)
  • 健身类应用(在暴雨天推荐室内锻炼)
  • 生产力工具(提供穿衣或通勤建议)
  • 智能衣橱应用(依据日程和天气推荐穿搭)

在这些核心 Kit 的基础上继续构建,开发者能够在不同情境下扩展逻辑,提供深度个性化的 HarmonyOS 体验。

参考资料

Back to Blog

相关文章

阅读更多 »

2025年开发 fintech 应用的成本

Fintech 已经从小众走向主流。到 2025 年,用户期望即时 onboarding、实时支付、智能分析以及银行级安全成为默认配置……