Building a HarmonyOS 6 Service Card: From App Preview to Desktop Widget
This tutorial walks through creating a HarmonyOS 6 service card called PocketNote, covering configuration, data binding, form provider lifecycle, card UI with button actions, and the app entry point for adding the card to the system desktop, with debugging tips and a live demo on API 24 simulator.
Introduction
A good-looking green block inside a notes app does not mean the desktop widget is done. The system desktop (host) renders the widget, the provider supplies data, and button actions must route back through the widget mechanism. This exercise connects all pieces: add a "Pocket Phrase" card, return to the system desktop, and change the text twice.
The app keeps a preview area to show what will be added; the actual working widget on the desktop is the page specified in the configuration. The following sections separate these roles and examine the provider, widget, and add entry point file by file.
Host, Provider, and Widget Page
From the system desktop backwards: the host finds the widget definition and provider via configuration; the provider supplies bound data; the widget page subscribes to those fields and sends actions. The app page additionally initiates the add request. All four roles collaborate in the same project; the green preview block in the ordinary page covers only a small part.
Starting from an API 24 Empty Ability, keep the entry module, then create entryformability, widget/pages, and common directories. Place form_config in profile, add the corresponding extension ability and widget metadata in the module config. Existing EntryAbility, page config, and string resources must stay — do not replace the whole module config with a fragment just to add one widget field.
The in-app preview helps check color and layout, but only through the system add entry, seeing an independent widget on the desktop, and clicking its button to change content, is the full chain verified. That is why both app-page code and desktop recordings are provided — they prove different stages.
Widget Registration Files
form_config.json
Defines the widget spec, default widget, layout path, and dynamic type. This example supports 2×2 and 2×4, defaults to 2×2; periodic update is disabled, content updates are triggered by user clicks, so no resident timer is needed.
{
"forms": [
{
"name": "PocketNote",
"displayName": "$string:form_name",
"description": "$string:form_desc",
"src": "./ets/widget/pages/NoteCard.ets",
"uiSyntax": "arkts",
"window": {
"designWidth": 360,
"autoDesignWidth": true
},
"colorMode": "auto",
"isDefault": true,
"updateEnabled": false,
"defaultDimension": "2*2",
"supportDimensions": ["2*2", "2*4"],
"isDynamic": true
}
]
}module.json5
The module's extensionAbilities declares a form type and references the above config via metadata. The complete file keeps the ordinary page entry and the widget extension together.
{
"module": {
"name": "entry",
"type": "entry",
"description": "$string:module_desc",
"mainElement": "EntryAbility",
"deviceTypes": ["phone", "2in1"],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:main_pages",
"abilities": [
{
"name": "EntryAbility",
"srcEntry": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:layered_image",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startIcon",
"startWindowBackground": "$color:start_window_background",
"exported": true,
"skills": [
{
"entities": ["entity.system.home"],
"actions": ["ohos.want.action.home"]
}
]
}
],
"extensionAbilities": [
{
"name": "EntryFormAbility",
"srcEntrance": "./ets/entryformability/EntryFormAbility.ets",
"type": "form",
"exported": true,
"metadata": [
{
"name": "ohos.extension.form",
"resource": "$profile:form_config"
}
]
}
]
}
}Display name and description need corresponding string resources. The example adds two entries; when merging into an existing project, keep original resources like the entry label, not just the new widget's two strings.
{
"string": [
{
"name": "form_name",
"value": "桌边一句"
},
{
"name": "form_desc",
"value": "一张可以从桌面使用的手记卡片"
}
]
}Definition Name and Spec Mapping
PocketNote is the widget definition name, NoteCard.ets is the UI source file, EntryFormAbility is the provider ability name. The add request must align the definition name with module info; the config's src must point to the actual widget file. These three names do not have to be identical strings; each field must point to its correct object.
defaultDimension selects default 2×2, supportDimensions declares support for 2×2 and 2×4. This round only adds and operates the default spec; writing another spec in config does not mean its layout is verified. designWidth and autoDesignWidth participate in design-size arrangement; they cannot replace the real widget area allocated by the host.
updateEnabled disables timed updates in config; this does not prevent active updateForm via button messages. isDynamic relates to widget content updates. Understanding the difference avoids thinking that disabling timed updates means no interaction should change content.
displayName and description reference form_name and form_desc; they must be merged into the existing string array. If the add entry shows an abnormal name, check both ability config and whether these two resources exist. Do not copy only the profile file and miss its dependent resources, then blame the widget source for host display issues.
Initial Binding Data and Provider
NoteData
Stores the phrase and count, placed in common/NoteData.ets. The two field names are exactly what the widget UI reads; keep them consistent on data updates.
export class NoteData {
line: string = '今天只做一件小事';
count: number = 0;
}EntryFormAbility
The provider returns initial data in onAddForm. When the widget receives a click message, onFormEvent gets the specific formId, then uses updateForm to update that widget instance. Updating is not assigning to a Text in the app preview; it passes bound data to the system widget mechanism.
import { FormExtensionAbility, formBindingData, formProvider } from '@kit.FormKit';
import { Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { NoteData } from '../common/NoteData';
export default class EntryFormAbility extends FormExtensionAbility {
private counts: Map<string, number> = new Map();
onAddForm(want: Want): formBindingData.FormBindingData {
hilog.info(0xD001, 'P6Form110', 'Desktop note added');
return formBindingData.createFormBindingData(new NoteData());
}
onFormEvent(formId: string, message: string): void {
const count = (this.counts.get(formId) ?? 0) + 1;
this.counts.set(formId, count);
const data = new NoteData();
data.count = count;
data.line = ['慢一点,也在往前走', '给今天留一点空白', '先把这一件事做好'][count % 3];
formProvider.updateForm(formId, formBindingData.createFormBindingData(data))
.then(() => { hilog.info(0xD001, 'P6Form110', 'Widget updated %{public}d', count); });
}
onRemoveForm(formId: string): void { this.counts.delete(formId); }
}Count is stored per formId in a Map, so multiple widget instances maintain separate counts within the same provider process. Deleting a widget cleans its record. This count is not persisted; process restart would lose it — a separate persistence design is needed for long-term history.
Ordinary page state variables do not automatically cross into the widget process. Even if both sides call the field line, updates must go through bound data, then the widget subscribes. For debugging, temporarily keep a distinctly different phrase and a counter so every message yields an observable result; just changing background color makes it harder to judge if an update arrived.
Dynamic widgets have their own component capability scope; do not assume a full app page can be copied in wholesale. This example uses only basic text, rows/columns, and a button, sending one lightweight action back to the provider. Before adding complex drawing or interactions, check the current SDK's widget component constraints to decide what stays in the app.
Widget Button message Action
The widget page lives in widget/pages/NoteCard.ets. LocalStorageProp subscribes to line and count; after the provider updates bound data, the UI reads the new fields. The button sends a message action via postCardAction; the only message operation here is "next phrase".
@Entry
@Component
struct NoteCard {
@LocalStorageProp('line') line: string = '今天只做一件小事';
@LocalStorageProp('count') count: number = 0;
build() {
Column({ space: 12 }) {
Text('桌边一句').fontSize(14).fontColor('#587557').width('100%')
Text(this.line).fontSize(24).fontWeight(FontWeight.Bold).layoutWeight(1).width('100%')
Row() {
Text('换过 ' + this.count + ' 次').fontSize(12).fontColor('#587557').layoutWeight(1)
Button('换一句').fontSize(14).height(34).backgroundColor('#587557')
.onClick(() => { postCardAction(this, { action: 'message', params: { operation: 'next' } }); })
}.width('100%')
}.width('100%').height('100%').padding(20).backgroundColor('#E6EBCF')
}
}The provider currently treats all received widget messages as "change phrase". If later adding "favorite" or "open detail" buttons, parse operation and branch explicitly; do not let all messages fall into the same update method. Get one action flowing from desktop to provider first, then incrementally add action types — easier to locate where the chain breaks.
Updating Data by formId
On first add, onAddForm creates NoteData and wraps it as FormBindingData. NoteCard reads line and count via LocalStorageProp; keys match data fields. The provider does not manipulate the widget's Text directly; it sends data, and the UI displays per fields.
The button uses a message action, sending the operation to provider's onFormEvent. The callback receives formId identifying the widget instance; the Map also keys by it, so multiple instances of the same definition do not share a single counter just because the name is the same.
onFormEvent(formId: string, message: string): void {
const count = (this.counts.get(formId) ?? 0) + 1;
this.counts.set(formId, count);
const data = new NoteData();
data.count = count;
data.line = ['慢一点,也在往前走', '给今天留一点空白', '先把这一件事做好'][count % 3];
formProvider.updateForm(formId, formBindingData.createFormBindingData(data))
.then(() => { hilog.info(0xD001, 'P6Form110', 'Widget updated %{public}d', count); });
}
onRemoveForm(formId: string): void { this.counts.delete(formId); }After computing count, a new NoteData is created and updateForm is called. The update target is the formId from this callback, not the widget name. The widget receives the new line and count; both text and counter change together — no need to guess which local state caused a screen "flash".
Currently only the "change phrase" action exists, so the example does not branch on message's operation. If adding favorite, refresh, etc., parse and identify the action first, then enter corresponding logic; do not treat all messages as incrementing count. The Map is only in-provider process memory; service restart recovery needs a separate persistence design.
App Add Entry
The main page's preview container has id notePreview; AddFormMenuItem uses it to capture the add-time snapshot. The Want specifies provider, module, widget name, and dimension. The preview snapshot can keep a similar style to the real layout, but subsequent data updates still follow the widget layout and bound fields.
import { AddFormMenuItem } from '@kit.ArkUI';
import { formBindingData } from '@kit.FormKit';
import { NoteData } from '../common/NoteData';
@Entry
@Component
struct Index {
@State status: string = '把这一句留到桌面';
@Builder
addMenu() {
Menu() {
AddFormMenuItem({
bundleName: 'com.aasd23.p6desktopnote',
abilityName: 'EntryFormAbility',
parameters: {
'ohos.extra.param.key.form_dimension': 2,
'ohos.extra.param.key.form_name': 'PocketNote',
'ohos.extra.param.key.module_name': 'entry'
}
}, 'notePreview', {
formBindingData: formBindingData.createFormBindingData(new NoteData()),
style: { options: { content: '添加桌边一句' } },
callback: (error, id) => {
this.status = error && error.code ? '添加失败:' + error.code : '卡片已添加,回桌面看看';
}
})
}
}
build() {
Column({ space: 24 }) {
Text('桌面便笺工作室').fontSize(32).fontWeight(FontWeight.Bold)
Text('应用内预览').fontSize(14).fontColor('#587557')
Column({ space: 20 }) {
Text('桌边一句').fontSize(16).width('100%').fontColor('#587557')
Text('今天只做一件小事').fontSize(30).fontWeight(FontWeight.Bold).layoutWeight(1)
Text('添加后,可在卡片上换一句').fontSize(14).fontColor('#587557')
}.id('notePreview').width(290).height(290).padding(24).backgroundColor('#E6EBCF').borderRadius(20)
Button('添加到桌面').id('addMenu').backgroundColor('#587557').bindMenu(this.addMenu)
Text(this.status).id('status').fontSize(16).fontColor('#587557')
}.width('100%').height('100%').justifyContent(FlexAlign.Center).padding(24).backgroundColor('#F7F7EC')
}
}The add result updates via callback. On success, go back to the desktop to confirm the widget actually appears; if an error code returns, first verify spec, name, and extension registration — do not just change button text to "added". The error feedback is kept so the call result and desktop phenomenon can be viewed together.
System Desktop Run Record
This demo uses HarmonyOS 6.1.1, API 24 on a 2-in-1 simulator. It shows adding the widget from the app, returning to the system desktop, and clicking "Change Phrase". First click shows "给今天留一点空白", count becomes 1; second click shows "先把这一件事做好", count becomes 2. Finally returning to the app, the preview remains the add-entry preview, not faking the desktop state.
This distinction matters. The app preview changing normally only proves the ordinary page state works; the widget on the system desktop actually receiving updates covers the host, provider, and bound data path. The animated recording therefore keeps the desktop operation, not just a screenshot of a green block.
If the widget appears but text does not update, check sequentially: does the button send message? Does the provider receive formId? Does updateForm succeed? Do field names match LocalStorageProp? If the widget does not appear at all, check config and add result first. These two symptoms map to different locations; no need to modify all files at once.
When integrating a real notes app later, data fetching and error handling should also go into the provider. The system may reclaim the process, the widget may be deleted; after async fetch returns, confirm the target is still valid and handle update failure. The current example uses local short phrases to narrow the verification scope, letting the basic desktop communication process be directly reproduced.
Event Chain and Instance Cleanup
Troubleshooting can follow four stations: did the add request succeed? Did the widget appear on desktop? Did initial data display? Did the provider update after click? A normal app preview only proves the UI file works in the current app page; if the desktop is blank, still check widget registration, provider, and field data — do not start by tweaking the preview layout.
During two consecutive desktop clicks, this round showed "给今天留一点空白" then "先把这一件事做好", count from 1 to 2. Phrase order comes from count modulo; count comes from real callbacks. If count grows but phrase unchanged, check if line was sent with new data; if both unchanged, check whether the message reached the provider and updateForm's target ID.
The example logs success callbacks but does not categorize all update failures on the widget. Further refinement should leave clear logs and recovery strategies for update failures; do not announce update complete in the UI just because updateForm returned a Promise. The desktop recording is the evidence, not a line of code saying "updateForm was called".
When a widget is removed, onRemoveForm cleans the corresponding Map entry, avoiding stale records for non-existent instances. This step does not affect other widgets, nor does it delete any global widget definition. Keeping definition, instance, and data as three separate layers makes adding specs or multiple instances easier to manage later.
Summary
A service widget is not simply moving a piece of UI from the app to the desktop. Configuration declares what it is; the extension provides data; the widget declares how to display and send actions; the app provides the add entry. Align these files, and a desktop click has a clear destination.
Next steps: integrate real notes, adjust information density per spec, add data persistence. Basic directory and spec configuration can refer to Huawei's "Creating Service Widgets" guide; lifecycle and provider implementation can be cross-referenced with the "Widget Lifecycle Guide".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
