IT评测·应用市场-qidao123.com技术社区

标题: 鸿蒙元服务-开发一个简单的气候应用 [打印本页]

作者: 惊雷无声    时间: 2024-12-15 03:45
标题: 鸿蒙元服务-开发一个简单的气候应用
随着鸿蒙生态的不断美满,HarmonyOS 为开发者提供了全场景、多设备联动的本事。其中“元服务” (Service Widget 或 Ability Card) 是 HarmonyOS 特有的轻量级服务形态,可通过卡片的形式将应用的核心功能无缝呈现在多种设备上。此次,我们将以“简单气候应用”为例,展示如何利用鸿蒙元服务特性开发一款可在手机、平板、聪明屏等多种终端以卡片形式展示气候信息的应用。

一、实现目标

我们的最终目标是实现一个气候查询卡片,用户无需进入完整应用界面,就能在主屏卡片中实时查看当前都会的气候状况、温度以及气候图标。
核心功能点:

二、开发环境预备

1. 开发工具安装


2. 项目初始化

打开 DevEco Studio:
创建完毕后,DevEco Studio 将自动天生基础的目录布局。
3. 元服务(Service Widget)配置

在鸿蒙中,元服务通常以 Ability 的形式存在,并通过 config.json 或 module.json5 等配置文件来声明。我们必要在项目标 module.json5 中添加元服务相干的配置。
示例配置(请根据实际版本和目录布局微调):
  1. {
  2.   "module": {
  3.     "type": "entry",
  4.     "name": "entry",
  5.     "abilities": [
  6.       {
  7.         "name": "WeatherServiceAbility",
  8.         "type": "service",
  9.         "skills": [],
  10.         "forms": [
  11.           {
  12.             "name": "WeatherWidget",
  13.             "description": "Display simple weather info",
  14.             "dimensions": [
  15.               {
  16.                 "id": 1,
  17.                 "width": 2,
  18.                 "height": 2
  19.               }
  20.             ],
  21.             "defaultDimension": 1,
  22.             "jsComponent": true
  23.           }
  24.         ]
  25.       }
  26.     ]
  27.   }
  28. }
复制代码
这里声明了一个 Service Ability(WeatherServiceAbility)和对应的一项元服务卡片(WeatherWidget)。

三、代码实现

1. 数据来源与网络请求

气候数据可以通过公开的气候 API 获取,如 OpenWeatherMap(需注册获取 API Key)。为简化演示,这里假定我们有一个简单的 API 调用函数。
在 entry/src/main/js/default/common/utils/weatherRequest.js 文件中编写:
  1. import fetch from '@ohos.net.fetch';
  2. const API_URL = "https://api.openweathermap.org/data/2.5/weather?q=Beijing&units=metric&appid=YOUR_API_KEY";
  3. export async function getWeatherInfo() {
  4.     try {
  5.         const response = await fetch.fetch(API_URL);
  6.         const json = await response.json();
  7.         return {
  8.             city: json.name,
  9.             temp: Math.round(json.main.temp),
  10.             description: json.weather[0].description,
  11.             icon: json.weather[0].icon
  12.         };
  13.     } catch (e) {
  14.         console.error("Failed to fetch weather:", e);
  15.         return null;
  16.     }
  17. }
复制代码
2. 卡片布局编写

在鸿蒙中,元服务卡片利用 Declarative UI 或 XML 布局。以 Declarative UI 为例,在 entry/src/main/js/default/pages/CardForm.js 中:
  1. import { getWeatherInfo } from '../common/utils/weatherRequest.js'
  2. export default {
  3.     data: {
  4.         city: "Loading...",
  5.         temp: "--",
  6.         description: "N/A",
  7.         iconUrl: ""
  8.     },
  9.     onInit() {
  10.         this.loadWeather();
  11.     },
  12.     async loadWeather() {
  13.         const info = await getWeatherInfo();
  14.         if(info) {
  15.             this.city = info.city;
  16.             this.temp = info.temp + "°C";
  17.             this.description = info.description;
  18.             // 使用OpenWeatherMap的图标链接
  19.             this.iconUrl = `http://openweathermap.org/img/wn/${info.icon}@2x.png`;
  20.         }
  21.     },
  22.     refresh() {
  23.         this.loadWeather();
  24.     }
  25. }
复制代码
对应的 UI 布局文件(entry/src/main/js/default/pages/CardForm.hml)示例:
  1. <template>
  2.   <div class="container">
  3.     <div class="city">{{city}}</div>
  4.     <image src="{{iconUrl}}" class="icon"/>
  5.     <div class="temp">{{temp}}</div>
  6.     <div class="desc">{{description}}</div>
  7.     <button class="refresh-btn" @click="refresh">刷新</button>
  8.   </div>
  9. </template>
复制代码
样式文件(CardForm.css)简单示例:
  1. .container {
  2.   flex-direction: column;
  3.   justify-content: center;
  4.   align-items: center;
  5. }
  6. .city {
  7.   font-size: 24px;
  8.   margin-bottom: 10px;
  9. }
  10. .temp {
  11.   font-size: 40px;
  12.   font-weight: bold;
  13.   margin-top: 10px;
  14. }
  15. .desc {
  16.   font-size: 18px;
  17.   margin-top: 5px;
  18. }
  19. .icon {
  20.   width: 50px;
  21.   height: 50px;
  22.   margin: 10px;
  23. }
  24. .refresh-btn {
  25.   margin-top: 15px;
  26.   padding: 10px;
  27.   background-color: #5B8FF9;
  28.   color: #ffffff;
  29.   border-radius: 5px;
  30. }
复制代码
3. Ability 与 Card 关联

在 entry/src/main/js/default/app.js 中注册卡片路由:
  1. export default {
  2.     onCreate() {
  3.         console.info('Application onCreate');
  4.     },
  5.     onDestroy() {
  6.         console.info('Application onDestroy');
  7.     }
  8. }
复制代码
在 entry/src/main/js/default/ability/WeatherServiceAbility.js 中,创建 service ability 并注册卡片数据源:
  1. import Ability from '@ohos.application.Ability'
  2. export default class WeatherServiceAbility extends Ability {
  3.     onCreate(want, launchParam) {
  4.         console.info('WeatherServiceAbility onCreate');
  5.     }
  6.     onRequestForm(formId, formParams) {
  7.         console.info('WeatherServiceAbility onRequestForm');
  8.         // 返回卡片页面
  9.         return {
  10.             template: 'CardForm'
  11.         };
  12.     }
  13. }
复制代码
确保在 module.json5 配置中已指定 WeatherServiceAbility 所提供的卡片模板为 CardForm。

四、调试与摆设

1. 模拟器调试

DevEco Studio 提供 HarmonyOS 模拟器大概可以连接鸿蒙设备。点击运行按钮选择合适的设备即可摆设运行。
成功后,在主屏添加卡片,在可用卡片列表中应能看到 “SimpleWeather” 的卡片,添加后显示实时气候信息。
2. 真机调试

将鸿蒙手机或平板通过 USB 连接到开发电脑,开启开发者模式。在 DevEco Studio 中选择目标设备为真实硬件,摆设运行。

五、常见问题与解决方案



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4