HarmonyOS鸿蒙Next中如何给应用增加桌面卡片
HarmonyOS鸿蒙Next中如何给应用增加桌面卡片 想给自己做的APP加入桌面卡片,可以显示当时日期和时间,点击后可以打开应用的page1页面,如何实现呢?
参考Form Kit的开发文档~
快速链接:Form Kit
更多关于HarmonyOS鸿蒙Next中如何给应用增加桌面卡片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,为应用增加桌面卡片需使用ArkTS开发。首先,在工程目录的entry/src/main/ets/entryability下创建FormAbility,并在module.json5配置文件中声明卡片。然后,在resources/base/profile/目录下定义卡片配置文件,指定卡片名称、尺寸和布局。卡片UI通过ArkUI组件构建,数据更新在FormExtensionAbility中管理。开发完成后,通过IDE编译生成HAP包,安装到设备即可在桌面上添加卡片。
在HarmonyOS Next中,为应用添加桌面卡片(服务卡片)主要涉及ArkTS/ArkUI开发。以下是实现一个显示日期和时间、点击跳转至应用内特定页面的卡片的核心步骤:
1. 创建卡片FormExtensionAbility
在entry/src/main/ets/下创建FormAbility目录,并新建FormAbility.ts作为卡片的入口。
import formInfo from '@ohos.app.form.formInfo';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class FormAbility extends FormExtensionAbility {
// 创建卡片
onAddForm(want) {
let formData = {};
// 初始数据:日期时间
formData["date"] = this.getCurrentDateTime();
return formData;
}
// 更新卡片
onFormEvent(formId, message) {
// 处理卡片事件,如点击跳转
let formData = {};
formData["date"] = this.getCurrentDateTime();
this.formProvider.updateForm(formId, formData);
}
private getCurrentDateTime(): string {
const now = new Date();
return now.toLocaleDateString() + ' ' + now.toLocaleTimeString();
}
}
2. 配置卡片信息
在entry/src/main/resources/base/profile/目录下的form_config.json中配置卡片:
{
"forms": [
{
"name": "widget",
"description": "这是一个显示日期时间的卡片",
"src": "./ets/widget/pages/WidgetCard.ets",
"uiSyntax": "arkts",
"window": {
"designWidth": 720,
"autoDesignWidth": true
},
"colorMode": "auto",
"isDefault": true,
"updateEnabled": true,
"scheduledUpdateTime": "10:30",
"updateDuration": 1,
"defaultDimension": "2*2",
"supportDimensions": ["2*2"]
}
]
}
3. 设计卡片UI
在entry/src/main/ets/widget/pages/下创建WidgetCard.ets,定义卡片布局:
@Entry
@Component
struct WidgetCard {
@LocalStorageProp('date') date: string = '';
build() {
Column() {
Text(this.date)
.fontSize(20)
.textAlign(TextAlign.Center)
.margin(10)
}
.width('100%')
.height('100%')
.onClick(() => {
// 点击卡片跳转到应用的page1页面
postCardAction(this, {
"action": "router",
"abilityName": "com.example.app.MainAbility",
"params": {
"targetPage": "page1"
}
});
})
}
}
4. 声明卡片权限与入口
在entry/src/main/module.json5中注册FormExtensionAbility并申请卡片权限:
{
"module": {
"abilities": [
{
"name": "FormAbility",
"type": "form",
"description": "$string:FormAbility_desc",
"srcEntry": "./ets/FormAbility/FormAbility.ets",
"formsEnabled": true,
"forms": [
{
"name": "widget",
"description": "$string:widget_desc",
"src": "./ets/widget/pages/WidgetCard.ets",
"window": {
"designWidth": 720
},
"isDefault": true,
"colorMode": "auto",
"supportDimensions": ["2*2"]
}
]
}
]
}
}
5. 实现跳转逻辑
在应用主Ability中处理卡片跳转参数,导航到page1页面。确保page1页面已在路由中配置。
关键点:
- 卡片数据通过
FormExtensionAbility管理,UI通过ArkTS组件定义。 - 使用
postCardAction实现卡片点击跳转,需在module.json5中配置对应Ability的路由。 - 卡片支持定时更新(通过
form_config.json中的scheduledUpdateTime和updateDuration设置),也可主动触发更新。
完成以上步骤后,编译应用,安装到设备即可在桌面上添加该卡片。卡片会显示当前日期时间,点击跳转到应用的page1页面。

