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

## Widget Overview
W
wusongqing 已提交
4
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
W
wusongqing 已提交
5

6
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget.
W
wusongqing 已提交
7 8 9 10

Basic concepts:
- Widget provider
  The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget.
11 12
- Widget host
  The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application.
W
wusongqing 已提交
13 14 15 16
- Widget Manager
  The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update.

> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
17
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
W
wusongqing 已提交
18

19
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
W
wusongqing 已提交
20 21 22 23 24

The widget provider controls the widget content to display, component layout, and click events bound to components.

## Scenario

W
wusongqing 已提交
25
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations:
W
wusongqing 已提交
26

W
wusongqing 已提交
27
- Develop the lifecycle callbacks in **LifecycleForm**.
W
wusongqing 已提交
28 29 30 31 32 33
- Create a **FormBindingData** object.
- Update a widget through **FormProvider**.
- Develop the widget UI page.

## Available APIs

W
wusongqing 已提交
34
The table below describes the lifecycle callbacks provided **LifecycleForm**.
W
wusongqing 已提交
35

W
wusongqing 已提交
36
**Table 1** LifecycleForm APIs
W
wusongqing 已提交
37 38 39 40 41 42 43 44 45

| API                                                      | Description                                        |
| :----------------------------------------------------------- | :------------------------------------------- |
| onCreate(want: Want): formBindingData.FormBindingData        | Called to notify the widget provider that a **Form** instance (widget) has been created.          |
| 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.          |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility.        |
| onEvent(formId: string, message: string): void               | Called to instruct the widget provider to receive and process the widget event.      |
| onDestroy(formId: string): void                              | Called to notify the widget provider that a **Form** instance (widget) has been destroyed.          |
W
wusongqing 已提交
46
| onAcquireFormState?(want: Want): formInfo.FormState          | Called when the widget provider receives the status query result of a specified widget.      |
W
wusongqing 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60

For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).

**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

W
wusongqing 已提交
61
### Creating LifecycleForm
W
wusongqing 已提交
62

W
wusongqing 已提交
63
To create a widget in the FA model, you need to implement the lifecycles of **LifecycleForm**. The sample code is as follows:
W
wusongqing 已提交
64 65 66 67 68 69 70 71 72

1. Import the required modules.

   ```javascript
   import formBindingData from '@ohos.application.formBindingData'
   import formInfo from '@ohos.application.formInfo'
   import formProvider from '@ohos.application.formProvider'
   ```
   
W
wusongqing 已提交
73
2. Implement the lifecycle callbacks of **LifecycleForm**.
W
wusongqing 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87

   ```javascript
   export default {
       onCreate(want) {
           console.log('FormAbility onCreate');
           // Persistently store widget information for subsequent use, such as widget instance retrieval and update.
           let obj = {
               "title": "titleOnCreate",
               "detail": "detailOnCreate"
           };
           let formData = formBindingData.createFormBindingData(obj);
           return formData;
       },
       onCastToNormal(formId) {
88
           // 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 已提交
89 90 91
           console.log('FormAbility onCastToNormal');
       },
       onUpdate(formId) {
92
           // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update.
W
wusongqing 已提交
93 94 95 96 97 98 99 100 101 102 103
           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) {
104
           // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification.
W
wusongqing 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
           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;
       },
   }
   ```

### Configuring config.json for the Form Ability

Configure the **config.json** file for the **Form** ability.

- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows:

  | 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 已提交
132
  | window   | Window-related configurations.                              | Object    | Yes                  |
W
wusongqing 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  | type     | Type of the JavaScript component. Available values are as follows:<br>**normal**: indicates that the JavaScript component is an application instance.<br>**form**: indicates that the JavaScript component is a widget instance.| String  | Yes (initial value: **normal**)|
  | mode     | Development mode of the JavaScript component.                                      | Object    | Yes (initial value: left empty)      |

  A configuration example is as follows:

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

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

  | 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                      |
W
wusongqing 已提交
157
  | type                | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget.            | String    | No                      |
W
wusongqing 已提交
158 159 160 161 162 163
  | colorMode           | Color mode of the widget. Available values are as follows:<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. Available values are as follows:<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                      |
  | defaultDimension    | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String    | No                      |
  | updateEnabled       | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<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.        | 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.| Number      | Yes (initial value: **0**)   |
W
wusongqing 已提交
164 165 166
  | formConfigAbility   | Indicates the link to a specific page of the application. The value is a URI.                       | String    | Yes (initial value: left empty)    |
  | 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 已提交
167 168
  | 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 已提交
169
  
W
wusongqing 已提交
170 171 172 173 174 175 176 177 178 179 180
  A configuration example is as follows:

  ```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 已提交
181 182
         "srcLanguage": "ets",
         "formsEnabled": true,
W
wusongqing 已提交
183 184 185
         "forms": [{
             "colorMode": "auto",
             "defaultDimension": "2*2",
W
wusongqing 已提交
186
             "description": "This is a widget.",
W
wusongqing 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
             "formVisibleNotify": true,
             "isDefault": true,
             "jsComponentName": "widget",
             "name": "widget",
             "scheduledUpdateTime": "10:30",
             "supportDimensions": ["2*2"],
             "type": "JS",
             "updateDuration": 1,
             "updateEnabled": true
          }]
     }]
  ```


### Widget Data Persistence

Mostly, the widget provider is started only when it needs to obtain 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.

```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"];
           // Persistently store widget information for subsequent use, such as widget instance retrieval and update.
           storeFormInfo(formId, formName, tempFlag, want);

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

You should override **onDestroy** to delete widget data.

```javascript
       onDestroy(formId) {
           // Delete widget data.
           deleteFormInfo(formId);
           console.log('FormAbility onDestroy');
       }
```

For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).

236
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
W
wusongqing 已提交
237

238
Normal widget: a widget that will be persistently used by the widget host
W
wusongqing 已提交
239

240
Temporary widget: a widget that is temporarily used by the widget host
W
wusongqing 已提交
241

242
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
W
wusongqing 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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

### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.

> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.

   - HML:
   ```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>
   ```

   - CSS:

   ```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;
}
   ```

   - JSON:
   ```json
   {
     "data": {
       "title": "TitleDefault",
       "detail": "TextDefault"
     },
     "actions": {
       "routerEvent": {
         "action": "router",
         "abilityName": "com.example.MyApplication.hmservice.FormAbility",
         "params": {
           "message": "add detail"
         }
       }
     }
   }
   ```

Now you've got a widget shown below.

![fa-form-example](figures/fa-form-example.png)
W
wusongqing 已提交
328 329 330 331 332 333 334 335

## Development Example

The following sample is provided to help you better understand how to develop a widget on the FA model:

[eTSFormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSFormAbility)

This **eTSFormAbility** sample provides a widget. Users can create, update, and delete widgets on the home screen of their phones or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage.