fa-formability.md 20.4 KB
Newer Older
W
wusongqing 已提交
1
# FA Widget Development
W
wusongqing 已提交
2 3

## Widget Overview
G
Gloria 已提交
4
A 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.
W
wusongqing 已提交
5

G
Gloria 已提交
6
A 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.  
W
wusongqing 已提交
7

G
Gloria 已提交
8 9 10 11
Before you get started, it would be helpful if you have a basic understanding of the following concepts:
- 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.
- Widget host: an application that displays the widget content and controls the widget location.
- Widget Manager: a resident agent that provides widget management features such as periodic widget updates.
W
wusongqing 已提交
12

W
wusongqing 已提交
13 14
> **NOTE**
>
G
Gloria 已提交
15
> The widget host and provider do not need to be running all the time. The Widget Manager will start the widget provider to obtain widget information when a widget is added, deleted, or updated.
W
wusongqing 已提交
16

G
Gloria 已提交
17
You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager.
W
wusongqing 已提交
18

G
Gloria 已提交
19
The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components.
W
wusongqing 已提交
20

W
wusongqing 已提交
21
## Development Overview
W
wusongqing 已提交
22

G
Gloria 已提交
23
Carry out the following operations to develop the widget provider based on the [FA model](fa-brief.md):
W
wusongqing 已提交
24

G
Gloria 已提交
25 26 27 28
1. Implement lifecycle callbacks by using the **LifecycleForm** APIs.
2. Create a **FormBindingData** instance.
3. Update a widget by using the **FormProvider** APIs.
4. Develop the widget UI pages.
W
wusongqing 已提交
29 30 31

## Available APIs

G
Gloria 已提交
32
The table below describes the **LifecycleForm** APIs, which represent the lifecycle callbacks of a widget (known as a **Form** instance).
W
wusongqing 已提交
33

W
wusongqing 已提交
34
**Table 1** LifecycleForm APIs
W
wusongqing 已提交
35 36 37

| API                                                      | Description                                        |
| :----------------------------------------------------------- | :------------------------------------------- |
G
Gloria 已提交
38
| onCreate(want: Want): formBindingData.FormBindingData        | Called to notify the widget provider that a widget has been created.          |
W
wusongqing 已提交
39 40
| onCastToNormal(formId: string): void                         | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void                               | Called to notify the widget provider that a widget has been updated.          |
W
wusongqing 已提交
41
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.        |
W
wusongqing 已提交
42
| onEvent(formId: string, message: string): void               | Called to instruct the widget provider to receive and process a widget event.      |
G
Gloria 已提交
43 44
| onDestroy(formId: string): void                              | Called to notify the widget provider that a widget has been destroyed.          |
| onAcquireFormState?(want: Want): formInfo.FormState          | Called to instruct the widget provider to receive the status query result of a widget.      |
W
wusongqing 已提交
45

46
The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md).
W
wusongqing 已提交
47 48 49 50 51 52 53 54 55 56 57 58

**Table 2** FormProvider APIs

| API                                                      | Description                                             |
| :----------------------------------------------------------- | :------------------------------------------------ |
| 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.                   |
| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.|
| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.                                 |
| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.              |

## How to Develop

G
Gloria 已提交
59
### Implementing Lifecycle Callbacks
W
wusongqing 已提交
60

G
Gloria 已提交
61
To create an FA widget, you need to implement lifecycle callbacks using the **LifecycleForm** APIs. The sample code is as follows:
W
wusongqing 已提交
62 63 64 65 66 67 68 69 70

1. Import the required modules.

   ```javascript
   import formBindingData from '@ohos.application.formBindingData'
   import formInfo from '@ohos.application.formInfo'
   import formProvider from '@ohos.application.formProvider'
   ```
   
G
Gloria 已提交
71
2. Implement lifecycle callbacks for the widget.
W
wusongqing 已提交
72 73 74 75 76

   ```javascript
   export default {
       onCreate(want) {
           console.log('FormAbility onCreate');
W
wusongqing 已提交
77
           // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
W
wusongqing 已提交
78 79 80 81 82 83 84 85
           let obj = {
               "title": "titleOnCreate",
               "detail": "detailOnCreate"
           };
           let formData = formBindingData.createFormBindingData(obj);
           return formData;
       },
       onCastToNormal(formId) {
86
           // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion.
W
wusongqing 已提交
87 88 89
           console.log('FormAbility onCastToNormal');
       },
       onUpdate(formId) {
G
Gloria 已提交
90
           // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
W
wusongqing 已提交
91 92 93 94 95 96 97 98 99 100 101
           console.log('FormAbility onUpdate');
           let obj = {
               "title": "titleOnUpdate",
               "detail": "detailOnUpdate"
           };
           let formData = formBindingData.createFormBindingData(obj);
           formProvider.updateForm(formId, formData).catch((error) => {
               console.log('FormAbility updateForm, error:' + JSON.stringify(error));
           });
       },
       onVisibilityChange(newStatus) {
102
           // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification.
W
wusongqing 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
           console.log('FormAbility onVisibilityChange');
       },
       onEvent(formId, message) {
           // If the widget supports event triggering, override this method and implement the trigger.
           console.log('FormAbility onEvent');
       },
       onDestroy(formId) {
           // Delete widget data.
           console.log('FormAbility onDestroy');
       },
       onAcquireFormState(want) {
           console.log('FormAbility onAcquireFormState');
           return formInfo.FormState.READY;
       },
   }
   ```

W
wusongqing 已提交
120
### Configuring the Widget Configuration File
W
wusongqing 已提交
121

G
Gloria 已提交
122
The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need.
W
wusongqing 已提交
123

G
Gloria 已提交
124
- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows: 
W
wusongqing 已提交
125 126 127 128 129

  | Field| Description                                                         | Data Type| Default              |
  | -------- | ------------------------------------------------------------ | -------- | ------------------------ |
  | name     | Name of a JavaScript component. The default value is **default**.   | String  | No                      |
  | 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                      |
W
wusongqing 已提交
130
  | window   | Window-related configurations.                              | Object    | Yes                  |
G
Gloria 已提交
131
  | type     | Type of the JavaScript component.  <br>**normal**: indicates an application instance.<br>**form**: indicates a widget instance.| String  | Yes (initial value: **normal**)|
W
wusongqing 已提交
132 133
  | mode     | Development mode of the JavaScript component.                                      | Object    | Yes (initial value: left empty)      |

G
Gloria 已提交
134
  Example configuration:
W
wusongqing 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147

  ```json
     "js": [{
         "name": "widget",
         "pages": ["pages/index/index"],
         "window": {
             "designWidth": 720,
             "autoDesignWidth": true
         },
         "type": "form"
     }]
  ```

G
Gloria 已提交
148
- The **abilities** module in the **config.json** file corresponds to **LifecycleForm** of the widget. The internal structure is described as follows:
W
wusongqing 已提交
149 150 151 152 153 154

  | Field           | Description                                                         | Data Type  | Default              |
  | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
  | name                | Class name of the widget. The value is a string with a maximum of 127 bytes.                   | String    | No                      |
  | 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)      |
  | 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                      |
G
Gloria 已提交
155 156 157
  | type                | Type of the widget.  <br>**JS**: indicates a JavaScript-programmed widget.            | String    | No                      |
  | 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**)|
  | 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                      |
W
wusongqing 已提交
158
  | defaultDimension    | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String    | No                      |
G
Gloria 已提交
159 160 161
  | 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                      |
  | 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**) |
  | 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**)   |
W
wusongqing 已提交
162
  | formConfigAbility   | Link to a specific page of the application. The value is a URI.                       | String    | Yes (initial value: left empty)    |
W
wusongqing 已提交
163 164
  | formVisibleNotify   | Whether the widget is allowed to use the widget visibility notification.                        | String    | Yes (initial value: left empty)    |
  | jsComponentName     | Component name of the widget. The value is a string with a maximum of 127 bytes.        | String    | No                      |
W
wusongqing 已提交
165 166
  | metaData            | Metadata of the widget. This field contains the array of the **customizeData** field.           | Object      | Yes (initial value: left empty)    |
  | customizeData       | Custom information about the widget.                                      | Object array  | Yes (initial value: left empty)    |
W
wusongqing 已提交
167
  
G
Gloria 已提交
168
  Example configuration:
W
wusongqing 已提交
169 170 171 172 173 174 175 176 177 178

  ```json
     "abilities": [{
         "name": "FormAbility",
         "description": "This is a FormAbility",
         "formsEnabled": true,
         "icon": "$media:icon",
         "label": "$string:form_FormAbility_label",
         "srcPath": "FormAbility",
         "type": "service",
W
wusongqing 已提交
179 180
         "srcLanguage": "ets",
         "formsEnabled": true,
W
wusongqing 已提交
181 182 183
         "forms": [{
             "colorMode": "auto",
             "defaultDimension": "2*2",
W
wusongqing 已提交
184
             "description": "This is a widget.",
W
wusongqing 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197
             "formVisibleNotify": true,
             "isDefault": true,
             "jsComponentName": "widget",
             "name": "widget",
             "scheduledUpdateTime": "10:30",
             "supportDimensions": ["2*2"],
             "type": "JS",
             "updateEnabled": true
          }]
     }]
  ```


W
wusongqing 已提交
198
### Persistently Storing Widget Data
W
wusongqing 已提交
199

G
Gloria 已提交
200
A 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.
W
wusongqing 已提交
201 202 203 204 205 206 207 208

```javascript
       onCreate(want) {
           console.log('FormAbility onCreate');

           let formId = want.parameters["ohos.extra.param.key.form_identity"];
           let formName = want.parameters["ohos.extra.param.key.form_name"];
           let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
W
wusongqing 已提交
209
           // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
G
Gloria 已提交
210
           // The storeFormInfo API is not implemented here.
W
wusongqing 已提交
211 212 213 214 215 216 217 218 219 220 221
           storeFormInfo(formId, formName, tempFlag, want);

           let obj = {
               "title": "titleOnCreate",
               "detail": "detailOnCreate"
           };
           let formData = formBindingData.createFormBindingData(obj);
           return formData;
       }
```

G
Gloria 已提交
222
You should override **onDestroy** to implement widget data deletion.
W
wusongqing 已提交
223 224 225 226

```javascript
       onDestroy(formId) {
           console.log('FormAbility onDestroy');
W
wusongqing 已提交
227

G
Gloria 已提交
228
           // You need to implement the code for deleting the persistent widget data.
G
Gloria 已提交
229
           // The deleteFormInfo API is not implemented here.
W
wusongqing 已提交
230
           deleteFormInfo(formId);
W
wusongqing 已提交
231 232 233
       }
```

G
Gloria 已提交
234
For details about how to implement persistence data storage, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
W
wusongqing 已提交
235

G
Gloria 已提交
236
The **Want** passed by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary.
W
wusongqing 已提交
237

G
Gloria 已提交
238
- Normal widget: a widget persistently used by the widget host
W
wusongqing 已提交
239

G
Gloria 已提交
240
- Temporary widget: a widget temporarily used by the widget host
W
wusongqing 已提交
241

G
Gloria 已提交
242
Data 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.
W
wusongqing 已提交
243

W
wusongqing 已提交
244 245
### Updating Widget Data

G
Gloria 已提交
246
When an application initiates a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows:
W
wusongqing 已提交
247 248 249

```javascript
onUpdate(formId) {
G
Gloria 已提交
250
    // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
W
wusongqing 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
    console.log('FormAbility onUpdate');
    let obj = {
        "title": "titleOnUpdate",
        "detail": "detailOnUpdate"
    };
    let formData = formBindingData.createFormBindingData(obj);
    // Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
    formProvider.updateForm(formId, formData).catch((error) => {
        console.log('FormAbility updateForm, error:' + JSON.stringify(error));
    });
}
```

### Developing Widget UI Pages

W
wusongqing 已提交
266 267
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.

W
wusongqing 已提交
268 269
> **NOTE**
>
G
Gloria 已提交
270
> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
W
wusongqing 已提交
271

G
Gloria 已提交
272
   - HML file:
W
wusongqing 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286
   ```html
   <div class="container">
       <stack>
           <div class="container-img">
               <image src="/common/widget.png" class="bg-img"></image>
           </div>
           <div class="container-inner">
               <text class="title">{{title}}</text>
               <text class="detail_text" onclick="routerEvent">{{detail}}</text>
           </div>
       </stack>
   </div>
   ```

G
Gloria 已提交
287
   - CSS file:
W
wusongqing 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

   ```css
.container {
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.bg-img {
    flex-shrink: 0;
    height: 100%;
}

.container-inner {
    flex-direction: column;
    justify-content: flex-end;
    align-items: flex-start;
    height: 100%;
    width: 100%;
    padding: 12px;
}

.title {
    font-size: 19px;
    font-weight: bold;
    color: white;
    text-overflow: ellipsis;
    max-lines: 1;
}

.detail_text {
    font-size: 16px;
    color: white;
    opacity: 0.66;
    text-overflow: ellipsis;
    max-lines: 1;
    margin-top: 6px;
}
   ```

G
Gloria 已提交
328
   - JSON file:
W
wusongqing 已提交
329 330 331 332 333 334 335 336 337
   ```json
   {
     "data": {
       "title": "TitleDefault",
       "detail": "TextDefault"
     },
     "actions": {
       "routerEvent": {
         "action": "router",
G
Gloria 已提交
338
         "abilityName": "com.example.entry.MainAbility",
W
wusongqing 已提交
339 340 341 342 343 344 345 346 347 348 349
         "params": {
           "message": "add detail"
         }
       }
     }
   }
   ```

Now you've got a widget shown below.

![fa-form-example](figures/fa-form-example.png)
W
wusongqing 已提交
350

G
Gloria 已提交
351 352 353 354
### Developing Widget Events

You 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:

G
Gloria 已提交
355
1. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
G
Gloria 已提交
356
2. For the router event, set the following attributes:
G
Gloria 已提交
357
   - **action**: **router**, which indicates a router event.
G
Gloria 已提交
358 359 360
   - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model.
   - **params**: custom parameters of 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 main ability in the FA model, **featureAbility.getWant()** can be used to obtain **want** and its **parameters** field.
3. For the message event, set the following attributes:
G
Gloria 已提交
361
   - **action**: **message**, which indicates a message event.
G
Gloria 已提交
362 363 364 365
   - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.

The code snippet is as follows:

G
Gloria 已提交
366
   - HML file:
G
Gloria 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380
   ```html
   <div class="container">
       <stack>
           <div class="container-img">
               <image src="/common/widget.png" class="bg-img"></image>
           </div>
           <div class="container-inner">
               <text class="title" onclick="routerEvent">{{title}}</text>
               <text class="detail_text" onclick="messageEvent">{{detail}}</text>
           </div>
       </stack>
   </div>
   ```

G
Gloria 已提交
381
   - JSON file:
G
Gloria 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
   ```json
   {
     "data": {
       "title": "TitleDefault",
       "detail": "TextDefault"
     },
     "actions": {
       "routerEvent": {
         "action": "router",
         "abilityName": "com.example.entry.MainAbility",
         "params": {
           "message": "add detail"
         }
       },
       "messageEvent": {
         "action": "message",
         "params": {
           "message": "add detail"
         }
       }
     }
   }
   ```