• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# FA Widget Development
2
3## Widget Overview
4A 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.
5
6A 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.
7
8Before you get started, it would be helpful if you have a basic understanding of the following concepts:
9- 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.
10- Widget host: an application that displays the widget content and controls the widget location.
11- Widget Manager: a resident agent that provides widget management features such as periodic widget updates.
12
13> **NOTE**
14>
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.
16
17You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager.
18
19The widget provider controls the widget content to display, the layout of components used in the widget, and click events bound to the components.
20
21## Development Overview
22
23Carry out the following operations to develop the widget provider based on the [FA model](fa-brief.md):
24
251. Implement lifecycle callbacks by using the **LifecycleForm** APIs.
262. Create a **FormBindingData** instance.
273. Update a widget by using the **FormProvider** APIs.
284. Develop the widget UI page.
29
30## Available APIs
31
32The table below describes the **LifecycleForm** APIs, which represent the lifecycle callbacks of a widget (known as a **Form** instance).
33
34**Table 1** LifecycleForm APIs
35
36| API                                                      | Description                                        |
37| :----------------------------------------------------------- | :------------------------------------------- |
38| onCreate(want: Want): formBindingData.FormBindingData        | Called to notify the widget provider that a widget has been created.          |
39| onCastToNormal(formId: string): void                         | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
40| onUpdate(formId: string): void                               | Called to notify the widget provider that a widget has been updated.          |
41| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.        |
42| onEvent(formId: string, message: string): void               | Called to instruct the widget provider to receive and process a widget event.      |
43| onDestroy(formId: string): void                              | Called to notify the widget provider that a widget has been destroyed.          |
44| onAcquireFormState?(want: Want): formInfo.FormState          | Called to instruct the widget provider to receive the status query result of a widget.      |
45
46The table below describes the **FormProvider** APIs. For details, see [FormProvider](../reference/apis/js-apis-application-formProvider.md).
47
48**Table 2** FormProvider APIs
49
50| API                                                      | Description                                             |
51| :----------------------------------------------------------- | :------------------------------------------------ |
52| 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.                   |
53| setFormNextRefreshTime(formId: string, minute: number): Promise<void>; | Sets the next refresh time for a widget. This API uses a promise to return the result.|
54| updateForm(formId: string, formBindingData: FormBindingData, callback: AsyncCallback<void>): void; | Updates a widget. This API uses an asynchronous callback to return the result.                                 |
55| updateForm(formId: string, formBindingData: FormBindingData): Promise<void>; | Updates a widget. This API uses a promise to return the result.              |
56
57## How to Develop
58
59### Implementing Lifecycle Callbacks
60
61To create an FA widget, you need to implement lifecycle callbacks using the **LifecycleForm** APIs. The sample code is as follows:
62
631. Import the required modules.
64
65   ```javascript
66   import formBindingData from '@ohos.application.formBindingData'
67   import formInfo from '@ohos.application.formInfo'
68   import formProvider from '@ohos.application.formProvider'
69   ```
70
712. Implement lifecycle callbacks for the widget.
72
73   ```javascript
74   export default {
75       onCreate(want) {
76           console.log('FormAbility onCreate');
77           // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
78           let obj = {
79               "title": "titleOnCreate",
80               "detail": "detailOnCreate"
81           };
82           let formData = formBindingData.createFormBindingData(obj);
83           return formData;
84       },
85       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.
87           console.log('FormAbility onCastToNormal');
88       },
89       onUpdate(formId) {
90           // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
91           console.log('FormAbility onUpdate');
92           let obj = {
93               "title": "titleOnUpdate",
94               "detail": "detailOnUpdate"
95           };
96           let formData = formBindingData.createFormBindingData(obj);
97           formProvider.updateForm(formId, formData).catch((error) => {
98               console.log('FormAbility updateForm, error:' + JSON.stringify(error));
99           });
100       },
101       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.
103           console.log('FormAbility onVisibilityChange');
104       },
105       onEvent(formId, message) {
106           // If the widget supports event triggering, override this method and implement the trigger.
107           console.log('FormAbility onEvent');
108       },
109       onDestroy(formId) {
110           // Delete widget data.
111           console.log('FormAbility onDestroy');
112       },
113       onAcquireFormState(want) {
114           console.log('FormAbility onAcquireFormState');
115           return formInfo.FormState.READY;
116       },
117   }
118   ```
119
120### Configuring the Widget Configuration File
121
122The widget configuration file is named **config.json**. Find the **config.json** file for the widget and edit the file depending on your need.
123
124- The **js** module in the **config.json** file provides JavaScript resources of the widget. The internal structure is described as follows:
125
126  | Field| Description                                                         | Data Type| Default              |
127  | -------- | ------------------------------------------------------------ | -------- | ------------------------ |
128  | name     | Name of a JavaScript component. The default value is **default**.   | String  | No                      |
129  | 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                      |
130  | window   | Window-related configurations.                              | Object    | Yes                  |
131  | type     | Type of the JavaScript component.  <br>**normal**: indicates an application instance.<br>**form**: indicates a widget instance.| String  | Yes (initial value: **normal**)|
132  | mode     | Development mode of the JavaScript component.                                      | Object    | Yes (initial value: left empty)      |
133
134  Example configuration:
135
136  ```json
137     "js": [{
138         "name": "widget",
139         "pages": ["pages/index/index"],
140         "window": {
141             "designWidth": 720,
142             "autoDesignWidth": true
143         },
144         "type": "form"
145     }]
146  ```
147
148- The **abilities** module in the **config.json** file corresponds to **LifecycleForm** of the widget. The internal structure is described as follows:
149
150  | Field           | Description                                                         | Data Type  | Default              |
151  | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
152  | name                | Class name of the widget. The value is a string with a maximum of 127 bytes.                   | String    | No                      |
153  | 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)      |
154  | 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                      |
155  | type                | Type of the widget.  <br>**JS**: indicates a JavaScript-programmed widget.            | String    | No                      |
156  | 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**)|
157  | 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                      |
158  | defaultDimension    | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String    | No                      |
159  | 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                      |
160  | 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**) |
161  | 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**)   |
162  | formConfigAbility   | Link to a specific page of the application. The value is a URI.                       | String    | Yes (initial value: left empty)    |
163  | formVisibleNotify   | Whether the widget is allowed to use the widget visibility notification.                        | String    | Yes (initial value: left empty)    |
164  | jsComponentName     | Component name of the widget. The value is a string with a maximum of 127 bytes.        | String    | No                      |
165  | metaData            | Metadata of the widget. This field contains the array of the **customizeData** field.           | Object      | Yes (initial value: left empty)    |
166  | customizeData       | Custom information about the widget.                                      | Object array  | Yes (initial value: left empty)    |
167
168  Example configuration:
169
170  ```json
171     "abilities": [{
172         "name": "FormAbility",
173         "description": "This is a FormAbility",
174         "formsEnabled": true,
175         "icon": "$media:icon",
176         "label": "$string:form_FormAbility_label",
177         "srcPath": "FormAbility",
178         "type": "service",
179         "srcLanguage": "ets",
180         "formsEnabled": true,
181         "forms": [{
182             "colorMode": "auto",
183             "defaultDimension": "2*2",
184             "description": "This is a widget.",
185             "formVisibleNotify": true,
186             "isDefault": true,
187             "jsComponentName": "widget",
188             "name": "widget",
189             "scheduledUpdateTime": "10:30",
190             "supportDimensions": ["2*2"],
191             "type": "JS",
192             "updateEnabled": true
193          }]
194     }]
195  ```
196
197
198### Persistently Storing Widget Data
199
200A 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.
201
202```javascript
203       onCreate(want) {
204           console.log('FormAbility onCreate');
205
206           let formId = want.parameters["ohos.extra.param.key.form_identity"];
207           let formName = want.parameters["ohos.extra.param.key.form_name"];
208           let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
209           // Persistently store widget data for subsequent use, such as widget instance retrieval or update.
210           // The storeFormInfo API is not implemented here.
211           storeFormInfo(formId, formName, tempFlag, want);
212
213           let obj = {
214               "title": "titleOnCreate",
215               "detail": "detailOnCreate"
216           };
217           let formData = formBindingData.createFormBindingData(obj);
218           return formData;
219       }
220```
221
222You should override **onDestroy** to implement widget data deletion.
223
224```javascript
225       onDestroy(formId) {
226           console.log('FormAbility onDestroy');
227
228           // You need to implement the code for deleting the persistent widget data.
229           // The deleteFormInfo API is not implemented here.
230           deleteFormInfo(formId);
231       }
232```
233
234For details about how to implement persistent data storage, see [Data Persistence by User Preferences](../database/data-persistence-by-preferences.md).
235
236The **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.
237
238- Normal widget: a widget persistently used by the widget host
239
240- Temporary widget: a widget temporarily used by the widget host
241
242Data 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.
243
244### Updating Widget Data
245
246When 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:
247
248```javascript
249onUpdate(formId) {
250    // Override this method to support scheduled updates, periodic updates, or updates requested by the widget host.
251    console.log('FormAbility onUpdate');
252    let obj = {
253        "title": "titleOnUpdate",
254        "detail": "detailOnUpdate"
255    };
256    let formData = formBindingData.createFormBindingData(obj);
257    // Call the updateForm() method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
258    formProvider.updateForm(formId, formData).catch((error) => {
259        console.log('FormAbility updateForm, error:' + JSON.stringify(error));
260    });
261}
262```
263
264### Developing the Widget UI Page
265
266You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
267
268> **NOTE**
269>
270> Only the JavaScript-based web-like development paradigm is supported when developing the widget UI.
271
272   - HML file:
273   ```html
274   <div class="container">
275       <stack>
276           <div class="container-img">
277               <image src="/common/widget.png" class="bg-img"></image>
278           </div>
279           <div class="container-inner">
280               <text class="title">{{title}}</text>
281               <text class="detail_text" onclick="routerEvent">{{detail}}</text>
282           </div>
283       </stack>
284   </div>
285   ```
286
287   - CSS file:
288
289   ```css
290.container {
291    flex-direction: column;
292    justify-content: center;
293    align-items: center;
294}
295
296.bg-img {
297    flex-shrink: 0;
298    height: 100%;
299}
300
301.container-inner {
302    flex-direction: column;
303    justify-content: flex-end;
304    align-items: flex-start;
305    height: 100%;
306    width: 100%;
307    padding: 12px;
308}
309
310.title {
311    font-size: 19px;
312    font-weight: bold;
313    color: white;
314    text-overflow: ellipsis;
315    max-lines: 1;
316}
317
318.detail_text {
319    font-size: 16px;
320    color: white;
321    opacity: 0.66;
322    text-overflow: ellipsis;
323    max-lines: 1;
324    margin-top: 6px;
325}
326   ```
327
328   - JSON file:
329   ```json
330   {
331     "data": {
332       "title": "TitleDefault",
333       "detail": "TextDefault"
334     },
335     "actions": {
336       "routerEvent": {
337         "action": "router",
338         "abilityName": "com.example.entry.MainAbility",
339         "params": {
340           "message": "add detail"
341         }
342       }
343     }
344   }
345   ```
346
347Now you've got a widget shown below.
348
349![fa-form-example](figures/fa-form-example.png)
350
351### Developing Widget Events
352
353You 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:
354
3551. Set the **onclick** field in the HML file to **routerEvent** or **messageEvent**, depending on the **actions** settings in the JSON file.
3562. Set the router event.
357   - **action**: **"router"**, which indicates a router event.
358   - **abilityName**: target ability name, for example, **com.example.entry.MainAbility**, which is the default main ability name in DevEco Studio for the FA model.
359   - **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.
3603. Set the message event.
361   - **action**: **"message"**, which indicates a message event.
362   - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onEvent**.
363
364The code snippet is as follows:
365
366   - HML file:
367   ```html
368   <div class="container">
369       <stack>
370           <div class="container-img">
371               <image src="/common/widget.png" class="bg-img"></image>
372           </div>
373           <div class="container-inner">
374               <text class="title" onclick="routerEvent">{{title}}</text>
375               <text class="detail_text" onclick="messageEvent">{{detail}}</text>
376           </div>
377       </stack>
378   </div>
379   ```
380
381   - JSON file:
382   ```json
383   {
384     "data": {
385       "title": "TitleDefault",
386       "detail": "TextDefault"
387     },
388     "actions": {
389       "routerEvent": {
390         "action": "router",
391         "abilityName": "com.example.entry.MainAbility",
392         "params": {
393           "message": "add detail"
394         }
395       },
396       "messageEvent": {
397         "action": "message",
398         "params": {
399           "message": "add detail"
400         }
401       }
402     }
403   }
404   ```
405