在 HarmonyOS 服务卡片中访问应用数据
1 分•作者: flfljh•7 个月前
# 在 HarmonyOS 服务卡片中访问应用数据
### (1) 创建服务卡片
创建基于 ArkTS 的卡片后,项目将生成以下与卡片相关的文件:
- 卡片生命周期管理文件 (`EntryFormAbility.ets`)
- 卡片 UI 文件 (`WidgetCard.ets`)
- 卡片配置文件 (`form_config.json`)
### (2) 配置 module.json5
参考字段文档:
```
"extensionAbilities": [
{
"name": "EntryFormAbility",
"srcEntry": "./ets/entryformability/EntryFormAbility.ets",
"label": "$string:EntryFormAbility_label",
"description": "$string:EntryFormAbility_desc",
"type": "form",
"metadata": [
{
"name": "ohos.extension.form",
"resource": "$profile:form_config"
}
]
}
]
```
### (3) 特定于卡片的配置
配置位于 `resources/base/profile/form_config.json` 中。
参考字段文档:
### (4) UI 开发和参数处理
卡片 UI 代码位于 `ets/widget/` 中。参数接收逻辑:
```
let storageUpdateByMsg = new LocalStorage();
@Entry(storageUpdateByMsg)
@Component
struct WidgetCard {
@LocalStorageProp('diffExamDay') diffExamDay: number = -1;
}
```
### (5) 卡片生命周期和数据传递
- 初始化逻辑在 `EntryFormAbility.onAddForm` 中(例如,将卡片 ID 传递给 WidgetCard)
- 更新在 `onUpdateForm` 钩子中处理
### (6) 在卡片初始化期间访问应用数据
#### 6.1 通知应用更新卡片数据
```
postCardAction(this, {
action: "call",
abilityName: "EntryAbility",
params: {
method: "upDiffExamDay",
formId: this.formId,
},
});
```
*时序问题解决方案:*
监视 `formId` 的变化,而不是使用 `aboutToAppear()`:
```
@LocalStorageProp('formId') @Watch('updateFormId') formId:string = '';
updateFormId() {
postCardAction(this, {
action: 'call',
abilityName: 'EntryAbility',
params: {
method: 'upDiffExamDay',
formId: this.formId
}
});
}
```
#### 6.2 应用端数据处理
在 `EntryAbility.onCreate` 中:
```
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.callee.on('upDiffExamDay', upDiffExamDayCall);
}
const upDiffExamDayCall = (data: rpc.MessageSequence): MyParcelable => {
let params: Record<string, string> = JSON.parse(data.readString());
if (params.formId) {
PreferencesUtil.putSync('formId', params.formId)
const diffExamDay = UserCacheManager.getDiffExamDay();
diffExamDay === -1
? getHomePageData(params.formId) // 如果不可用则获取数据
: Utils.updateDiffExamDay(params.formId); // 直接更新卡片
}
return new MyParcelable(1, 'success');
};
```
*更新卡片数据:*
```
// 导入所需模块
import { formBindingData, formProvider } from '@kit.FormKit';
updateDiffExamDay(formId: string) {
const diffExamDay = UserCacheManager.getDiffExamDay();
let formMsg = formBindingData.createFormBindingData({
'diffExamDay': diffExamDay
});
formProvider.updateForm(formId, formMsg)
.then(() => console.log('Update success'))
.catch((error) => console.error('Update failed:', error));
}
```
查看原文
# Accessing App Data in HarmonyOS Service Widgets<p>### (1) Creating a Service Widget<p>After creating an ArkTS-based widget, the project will generate the following widget-related files:<p>- Widget lifecycle management file (`EntryFormAbility.ets`)
- Widget UI file (`WidgetCard.ets`)
- Widget configuration file (`form_config.json`)<p>### (2) Configuring module.json5<p>Reference documentation for fields:<p>```
"extensionAbilities": [
{
"name": "EntryFormAbility",
"srcEntry": "./ets/entryformability/EntryFormAbility.ets",
"label": "$string:EntryFormAbility_label",
"description": "$string:EntryFormAbility_desc",
"type": "form",
"metadata": [
{
"name": "ohos.extension.form",
"resource": "$profile:form_config"
}
]
}
]
```<p>### (3) Widget-Specific Configuration<p>Configuration resides in `resources/base/profile/form_config.json`.
Reference documentation for fields:<p>### (4) UI Development and Parameter Handling<p>Widget UI code is located in `ets/widget/`. Parameter reception logic:<p>```
let storageUpdateByMsg = new LocalStorage();<p>@Entry(storageUpdateByMsg)
@Component
struct WidgetCard {
@LocalStorageProp('diffExamDay') diffExamDay: number = -1;
}
```<p>### (5) Widget Lifecycle and Data Passing<p>- Initialization logic in `EntryFormAbility.onAddForm` (e.g., passing widget ID to WidgetCard)
- Updates handled in `onUpdateForm` hook<p>### (6) Accessing App Data During Widget Initialization<p>#### 6.1 Notifying App to Update Widget Data<p>```
postCardAction(this, {
action: "call",
abilityName: "EntryAbility",
params: {
method: "upDiffExamDay",
formId: this.formId,
},
});
```<p>*Timing Issue Solution:*
Monitor `formId` changes instead of using `aboutToAppear()`:<p>```
@LocalStorageProp('formId') @Watch('updateFormId') formId:string = '';<p>updateFormId() {
postCardAction(this, {
action: 'call',
abilityName: 'EntryAbility',
params: {
method: 'upDiffExamDay',
formId: this.formId
}
});
}
```<p>#### 6.2 App-Side Data Handling<p>In `EntryAbility.onCreate`:<p>```
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
this.callee.on('upDiffExamDay', upDiffExamDayCall);
}<p>const upDiffExamDayCall = (data: rpc.MessageSequence): MyParcelable => {
let params: Record<string, string> = JSON.parse(data.readString());
if (params.formId) {
PreferencesUtil.putSync('formId', params.formId)
const diffExamDay = UserCacheManager.getDiffExamDay();<p><pre><code> diffExamDay === -1
? getHomePageData(params.formId) // Fetch data if unavailable
: Utils.updateDiffExamDay(params.formId); // Update widget directly
}
return new MyParcelable(1, 'success');</code></pre>
};
```<p>*Updating Widget Data:*<p>```
// Import required modules
import { formBindingData, formProvider } from '@kit.FormKit';<p>updateDiffExamDay(formId: string) {
const diffExamDay = UserCacheManager.getDiffExamDay();
let formMsg = formBindingData.createFormBindingData({
'diffExamDay': diffExamDay
});<p><pre><code> formProvider.updateForm(formId, formMsg)
.then(() => console.log('Update success'))
.catch((error) => console.error('Update failed:', error));</code></pre>
}
```