1# Widget Development 2 3 4## Widget Overview 5 6A service widget (also called widget) is a set of UI components that display important information or operations specific to an application. It provides users with direct access to a desired application service, without the need to open the application first. 7 8A widget usually appears as a part of the UI of another application (which currently can only be a system application) and provides basic interactive features such as opening a UI page or sending a message. 9 10Before you get started, it would be helpful if you have a basic understanding of the following concepts: 11 12- Widget host: an application that displays the widget content and controls the widget location. 13 14- Widget Manager: a resident agent that provides widget management features such as periodic widget updates. 15 16- Widget provider: an atomic service that provides the widget content to display and controls how widget components are laid out and how they interact with users. 17 18 19## Working Principles 20 21Figure 1 shows the working principles of the widget framework. 22 23**Figure 1** Widget framework working principles in the FA model 24![form-extension](figures/form-extension.png) 25 26The widget host consists of the following modules: 27 28- Widget usage: provides operations such as creating, deleting, or updating a widget. 29 30- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. 31 32The Widget Manager consists of the following modules: 33 34- Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. 35 36- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. 37 38- Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. 39 40- Object manager: manages RPC objects of the widget host. It is used to verify requests from the widget host and process callbacks after the widget update. 41 42- Communication adapter: communicates with the widget host and provider through RPCs. 43 44The widget provider consists of the following modules: 45 46- Widget service: implemented by the widget provider developer to process requests on widget creation, update, and deletion, and to provide corresponding widget services. 47 48- Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. 49 50- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. 51 52> **NOTE** 53> 54> You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. 55 56 57## Available APIs 58 59The **FormAbility** has the following APIs. 60 61| API| Description| 62| -------- | -------- | 63| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| 64| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| 65| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated.| 66| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| 67| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| 68| onDestroy(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| 69| onAcquireFormState?(want: Want): formInfo.FormState | Called to instruct the widget provider to receive the status query result of a widget.| 70| onShare?(formId: string): {[key: string]: any} | Called by the widget provider to receive shared widget data.| 71 72The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). 73 74 75| API| Description| 76| -------- | -------- | 77| setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void;| Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result.| 78| setFormNextRefreshTime(formId: string, minute: number): Promise<void>;| Sets the next refresh time for a widget. This API uses a promise to return the result.| 79| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.| 80| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.| 81 82 83The **FormBindingData** class has the following APIs. For details, see [FormBindingData](../reference/apis/js-apis-app-form-formBindingData.md). 84 85 86| API| Description| 87| -------- | -------- | 88| createFormBindingData(obj?: Object \ string): FormBindingData| | Creates a **FormBindingData** object.| 89 90 91## How to Develop 92 93The widget provider development based on the [FA model](fa-model-development-overview.md) involves the following key steps: 94 95- [Implementing Widget Lifecycle Callbacks](#implementing-widget-lifecycle-callbacks): Develop the **FormAbility** lifecycle callback functions. 96 97- [Configuring the Widget Configuration File](#configuring-the-widget-configuration-file): Configure the application configuration file **config.json**. 98 99- [Persistently Storing Widget Data](#persistently-storing-widget-data): Perform persistent management on widget information. 100 101- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. 102 103- [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. 104 105- [Developing Widget Events](#developing-widget-events): Add the router and message events for a widget. 106 107 108### Implementing Widget Lifecycle Callbacks 109 110To create a widget in the FA model, implement the widget lifecycle callbacks. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). 111 1121. Import related modules to **form.ts**. 113 114 ```ts 115 import formBindingData from '@ohos.app.form.formBindingData'; 116 import formInfo from '@ohos.app.form.formInfo'; 117 import formProvider from '@ohos.app.form.formProvider'; 118 import dataStorage from '@ohos.data.storage'; 119 ``` 120 1212. Implement the widget lifecycle callbacks in **form.ts**. 122 123 ```ts 124 export default { 125 onCreate(want) { 126 console.info('FormAbility onCreate'); 127 // Called when the widget is created. The widget provider should return the widget data binding class. 128 let obj = { 129 "title": "titleOnCreate", 130 "detail": "detailOnCreate" 131 }; 132 let formData = formBindingData.createFormBindingData(obj); 133 return formData; 134 }, 135 onCastToNormal(formId) { 136 // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. 137 console.info('FormAbility onCastToNormal'); 138 }, 139 onUpdate(formId) { 140 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 141 console.info('FormAbility onUpdate'); 142 let obj = { 143 "title": "titleOnUpdate", 144 "detail": "detailOnUpdate" 145 }; 146 let formData = formBindingData.createFormBindingData(obj); 147 formProvider.updateForm(formId, formData).catch((error) => { 148 console.info('FormAbility updateForm, error:' + JSON.stringify(error)); 149 }); 150 }, 151 onVisibilityChange(newStatus) { 152 // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. This callback takes effect only for system applications. 153 console.info('FormAbility onVisibilityChange'); 154 }, 155 onEvent(formId, message) { 156 // If the widget supports event triggering, override this method and implement the trigger. 157 console.info('FormAbility onEvent'); 158 }, 159 onDestroy(formId) { 160 // Delete widget data. 161 console.info('FormAbility onDestroy'); 162 }, 163 onAcquireFormState(want) { 164 console.info('FormAbility onAcquireFormState'); 165 return formInfo.FormState.READY; 166 }, 167 } 168 ``` 169 170> **NOTE** 171> 172> FormAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. 173 174### Configuring the Widget Configuration File 175 176The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need. 177 178- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows: 179 | Name| Description| Data Type| Initial Value Allowed| 180 | -------- | -------- | -------- | -------- | 181 | name | Name of a JavaScript component. The default value is **default**.| String| No| 182 | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array| No| 183 | window | Window-related configurations.| Object| Yes| 184 | type | Type of the JavaScript component. The value can be:<br>**normal**: indicates an application instance.<br>**form**: indicates a widget instance.| String| Yes (initial value: **normal**)| 185 | mode | Development mode of the JavaScript component.| Object| Yes (initial value: left empty)| 186 187 Example configuration: 188 189 190 ```json 191 "js": [{ 192 "name": "widget", 193 "pages": ["pages/index/index"], 194 "window": { 195 "designWidth": 720, 196 "autoDesignWidth": true 197 }, 198 "type": "form" 199 }] 200 ``` 201 202- The **abilities** module in the **config.json** file corresponds to **FormAbility** of the widget. The internal structure is described as follows: 203 | Name| Description| Data Type| Initial Value Allowed| 204 | -------- | -------- | -------- | -------- | 205 | name | Class name of a widget. The value is a string with a maximum of 127 bytes.| String| No| 206 | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| 207 | isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean| No| 208 | type | Type of the widget. The value can be:<br>**JS**: indicates a JavaScript-programmed widget.| String| No| 209 | colorMode | Color mode of the widget.<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String| Yes (initial value: **auto**)| 210 | supportDimensions | Grid styles supported by the widget.<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No| 211 | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| 212 | updateEnabled | Whether the widget can be updated periodically.<br>**true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.<br>**false**: The widget cannot be updated periodically.| Boolean| No| 213 | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| 214 | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.<br>**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| 215 | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| 216 | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| 217 | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes.| String| No| 218 | metaData | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| 219 | customizeData | Custom information about the widget.| Object array| Yes (initial value: left empty)| 220 221 Example configuration: 222 223 224 ```json 225 "abilities": [{ 226 "name": "FormAbility", 227 "description": "This is a FormAbility", 228 "formsEnabled": true, 229 "icon": "$media:icon", 230 "label": "$string:form_FormAbility_label", 231 "srcPath": "FormAbility", 232 "type": "service", 233 "srcLanguage": "ets", 234 "formsEnabled": true, 235 "formConfigAbility": "ability://com.example.entry.MainAbility", 236 "forms": [{ 237 "colorMode": "auto", 238 "defaultDimension": "2*2", 239 "description": "This is a widget.", 240 "formVisibleNotify": true, 241 "isDefault": true, 242 "jsComponentName": "widget", 243 "name": "widget", 244 "scheduledUpdateTime": "10:30", 245 "supportDimensions": ["2*2"], 246 "type": "JS", 247 "updateEnabled": true 248 }] 249 }] 250 ``` 251 252 253### Persistently Storing Widget Data 254 255A widget provider is usually started when it is needed to provide information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. 256 257 258```ts 259const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; 260async function storeFormInfo(formId: string, formName: string, tempFlag: boolean) { 261 // Only the widget ID (formId), widget name (formName), and whether the widget is a temporary one (tempFlag) are persistently stored. 262 let formInfo = { 263 "formName": formName, 264 "tempFlag": tempFlag, 265 "updateCount": 0 266 }; 267 try { 268 const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); 269 // Put the widget information. 270 await storage.put(formId, JSON.stringify(formInfo)); 271 console.info(`storeFormInfo, put form info successfully, formId: ${formId}`); 272 await storage.flush(); 273 } catch (err) { 274 console.error(`failed to storeFormInfo, err: ${JSON.stringify(err)}`); 275 } 276} 277 278// ... 279 onCreate(want) { 280 console.info('FormAbility onCreate'); 281 282 let formId = want.parameters["ohos.extra.param.key.form_identity"]; 283 let formName = want.parameters["ohos.extra.param.key.form_name"]; 284 let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; 285 // Persistently store widget data for subsequent use, such as instance acquisition and update. 286 // Implement this API based on project requirements. 287 storeFormInfo(formId, formName, tempFlag); 288 289 let obj = { 290 "title": "titleOnCreate", 291 "detail": "detailOnCreate" 292 }; 293 let formData = formBindingData.createFormBindingData(obj); 294 return formData; 295 } 296// ... 297``` 298 299You should override **onDestroy** to implement widget data deletion. 300 301 302```ts 303const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; 304async function deleteFormInfo(formId: string) { 305 try { 306 const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); 307 // Delete the widget information. 308 await storage.delete(formId); 309 console.info(`deleteFormInfo, del form info successfully, formId: ${formId}`); 310 await storage.flush(); 311 } catch (err) { 312 console.error(`failed to deleteFormInfo, err: ${JSON.stringify(err)}`); 313 } 314} 315 316// ... 317 onDestroy(formId) { 318 console.info('FormAbility onDestroy'); 319 // Delete the persistent widget instance data. 320 // Implement this API based on project requirements. 321 deleteFormInfo(formId); 322 } 323// ... 324``` 325 326For details about how to implement persistent data storage, see [Application Data Persistence Overview](../database/app-data-persistence-overview.md). 327 328The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. 329 330- Normal widget: a widget persistently used by the widget host 331 332- Temporary widget: a widget temporarily used by the widget host 333 334Data of a temporary widget will be deleted on the Widget Manager if the widget framework is killed and restarted. The widget provider, however, is not notified of the deletion and still keeps the data. Therefore, the widget provider needs to clear the data of temporary widgets proactively if the data has been kept for a long period of time. If the widget host has converted a temporary widget into a normal one, the widget provider should change the widget data from temporary storage to persistent storage. Otherwise, the widget data may be deleted by mistake. 335 336 337### Updating Widget Data 338 339When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm()** to update the widget. 340 341 342```ts 343onUpdate(formId) { 344 // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host. 345 console.info('FormAbility onUpdate'); 346 let obj = { 347 "title": "titleOnUpdate", 348 "detail": "detailOnUpdate" 349 }; 350 let formData = formBindingData.createFormBindingData(obj); 351 // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged. 352 formProvider.updateForm(formId, formData).catch((error) => { 353 console.info('FormAbility updateForm, error:' + JSON.stringify(error)); 354 }); 355} 356``` 357 358 359### Developing the Widget UI Page 360 361You can use the web-like paradigm (HML+CSS+JSON) to develop JS widget pages. This section describes how to develop a page shown below. 362 363![widget-development-fa](figures/widget-development-fa.png) 364 365> **NOTE** 366> 367> In the FA model, only the JavaScript-based web-like development paradigm is supported when developing the widget UI. 368 369- HML: uses web-like paradigm components to describe the widget page information. 370 371 ```html 372 <div class="container"> 373 <stack> 374 <div class="container-img"> 375 <image src="/common/widget.png" class="bg-img"></image> 376 </div> 377 <div class="container-inner"> 378 <text class="title">{{title}}</text> 379 <text class="detail_text" onclick="routerEvent">{{detail}}</text> 380 </div> 381 </stack> 382 </div> 383 ``` 384 385- CSS: defines style information about the web-like paradigm components in HML. 386 387 ```css 388 .container { 389 flex-direction: column; 390 justify-content: center; 391 align-items: center; 392 } 393 394 .bg-img { 395 flex-shrink: 0; 396 height: 100%; 397 } 398 399 .container-inner { 400 flex-direction: column; 401 justify-content: flex-end; 402 align-items: flex-start; 403 height: 100%; 404 width: 100%; 405 padding: 12px; 406 } 407 408 .title { 409 font-size: 19px; 410 font-weight: bold; 411 color: white; 412 text-overflow: ellipsis; 413 max-lines: 1; 414 } 415 416 .detail_text { 417 font-size: 16px; 418 color: white; 419 opacity: 0.66; 420 text-overflow: ellipsis; 421 max-lines: 1; 422 margin-top: 6px; 423 } 424 ``` 425 426- JSON: defines data and event interaction on the widget UI page. 427 428 ```json 429 { 430 "data": { 431 "title": "TitleDefault", 432 "detail": "TextDefault" 433 }, 434 "actions": { 435 "routerEvent": { 436 "action": "router", 437 "abilityName": "com.example.entry.MainAbility", 438 "params": { 439 "message": "add detail" 440 } 441 } 442 } 443 } 444 ``` 445 446 447### Developing Widget Events 448 449You can set router and message events for components on a widget. The router event applies to ability redirection, and the message event applies to custom click events. The key steps are as follows: 450 4511. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file. 452 4532. Set the router event. 454 - **action**: **"router"**, which indicates a router event. 455 - **abilityName**: name of the ability to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name created by DevEco Studio in the FA model is com.example.entry.MainAbility. 456 - **params**: custom parameters passed to the target ability. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target ability. For example, in the lifecycle function **onCreate** of the MainAbility in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field. 457 4583. Set the message event. 459 - **action**: **"message"**, which indicates a message event. 460 - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**. 461 462The following is an example: 463 464- HML file: 465 466 ```html 467 <div class="container"> 468 <stack> 469 <div class="container-img"> 470 <image src="/common/widget.png" class="bg-img"></image> 471 </div> 472 <div class="container-inner"> 473 <text class="title" onclick="routerEvent">{{title}}</text> 474 <text class="detail_text" onclick="messageEvent">{{detail}}</text> 475 </div> 476 </stack> 477 </div> 478 ``` 479 480- CSS file: 481 482 ```css 483 .container { 484 flex-direction: column; 485 justify-content: center; 486 align-items: center; 487 } 488 489 .bg-img { 490 flex-shrink: 0; 491 height: 100%; 492 } 493 494 .container-inner { 495 flex-direction: column; 496 justify-content: flex-end; 497 align-items: flex-start; 498 height: 100%; 499 width: 100%; 500 padding: 12px; 501 } 502 503 .title { 504 font-size: 19px; 505 font-weight: bold; 506 color: white; 507 text-overflow: ellipsis; 508 max-lines: 1; 509 } 510 511 .detail_text { 512 font-size: 16px; 513 color: white; 514 opacity: 0.66; 515 text-overflow: ellipsis; 516 max-lines: 1; 517 margin-top: 6px; 518 } 519 ``` 520 521- JSON file: 522 523 ```json 524 { 525 "data": { 526 "title": "TitleDefault", 527 "detail": "TextDefault" 528 }, 529 "actions": { 530 "routerEvent": { 531 "action": "router", 532 "abilityName": "com.example.entry.MainAbility", 533 "params": { 534 "message": "add detail" 535 } 536 }, 537 "messageEvent": { 538 "action": "message", 539 "params": { 540 "message": "add detail" 541 } 542 } 543 } 544 } 545 ``` 546