提交 397c1c0e 编写于 作者: X xywang 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into master

Signed-off-by: Nxywang <wangxiaoyuan6@huawei.com>
...@@ -36,9 +36,10 @@ ...@@ -36,9 +36,10 @@
- [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md)
- Widget Event Development - Widget Event Development
- [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md)
- [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) - [Redirecting to a UIAbility Through the router Event](arkts-ui-widget-event-router.md)
- [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md) - [Launching a UIAbility in the Background Through the call Event](arkts-ui-widget-event-call.md)
- [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md) - [Updating Widget Content Through the message Event](arkts-ui-widget-event-formextensionability.md)
- [Updating Widget Content Through the router or call Event](arkts-ui-widget-event-uiability.md)
- Widget Data Interaction - Widget Data Interaction
- [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md) - [Widget Data Interaction Overview](arkts-ui-widget-interaction-overview.md)
- [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md) - [Configuring a Widget to Update Periodically](arkts-ui-widget-update-by-time.md)
......
...@@ -12,17 +12,31 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca ...@@ -12,17 +12,31 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca
This document is organized as follows: This document is organized as follows:
- [AccessibilityExtensionAbility Development](#accessibilityextensionability-development) - [AccessibilityExtensionAbility Overview](#accessibilityextensionability-overview)
- [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service) - [Creating an Accessibility Extension Service](#creating-an-accessibility-extension-service)
- [Creating a Project](#creating-a-project) - [Processing an Accessibility Event](#processing-an-accessibility-event)
- [Creating an AccessibilityExtAbility File](#creating-an-accessibilityextability-file) - [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Processing an Accessibility Event](#processing-an-accessibility-event) - [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service)
- [Declaring Capabilities of Accessibility Extension Services](#declaring-capabilities-of-accessibility-extension-services)
- [Enabling a Custom Accessibility Extension Service](#enabling-a-custom-accessibility-extension-service) ## AccessibilityExtensionAbility Overview
Accessibility is about giving equal access to everyone so that they can access and use information equally and conveniently under any circumstances. It helps narrow the digital divide between people of different classes, regions, ages, and health status in terms of information understanding, information exchange, and information utilization, so that they can participate in social life more conveniently and enjoy the benefits of technological advances.
AccessibilityExtensionAbility is an accessibility extension service framework. It allows you to develop your own extension services and provides a standard mechanism for exchanging information between applications and extension services. You can make use of the provided capabilities and APIs to develop accessibility features for users with disabilities or physical limitations. For example, you can develop a screen reader for users with vision impairments.
Below shows the AccessibilityExtensionAbility framework.
![AccessibilityFramework](figures/AccessibilityFramework.png)
1. Accessibility app: extension service application developed based on the AccessibilityExtensionAbility framework, for example, a screen reader application.
2. Target app: application assisted by the accessibility app.
3. AccessibilityAbilityManagerService (AAMS): main service of the AccessibilityExtensionAbility framework, which is used to manage the lifecycle of accessibility apps and provide a bridge for information exchange between accessibility apps and target apps.
4. AccessibilityAbility (AAkit): ability that is used by the accessibility app to build an extension service ability operating environment and that provides interfaces for the accessibility app to query and operate the target app, including performing click/long press operations.
5. AccessibilitySystemAbilityClient (ASACkit): used by the target app to send accessibility events, such as content change events, to AAMS, and respond to the instructions (such as performing click/long press operations) sent by the accessibility app through AAMS.
## Creating an Accessibility Extension Service ## Creating an Accessibility Extension Service
You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project. You can create an accessibility extension service by creating a project from scratch or adding the service to an existing project. Only one accessibility extension service can be created for a project.
### Creating a Project ### Creating a Project
...@@ -40,15 +54,15 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens ...@@ -40,15 +54,15 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens
class AccessibilityExtAbility extends AccessibilityExtensionAbility { class AccessibilityExtAbility extends AccessibilityExtensionAbility {
onConnect() { onConnect() {
console.log('AccessibilityExtAbility onConnect'); console.info('AccessibilityExtAbility onConnect');
} }
onDisconnect() { onDisconnect() {
console.log('AccessibilityExtAbility onDisconnect'); console.info('AccessibilityExtAbility onDisconnect');
} }
onAccessibilityEvent(accessibilityEvent) { onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); console.info('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
} }
} }
...@@ -69,9 +83,9 @@ You can process the service logic for accessibility events in the **onAccessibil ...@@ -69,9 +83,9 @@ You can process the service logic for accessibility events in the **onAccessibil
```typescript ```typescript
onAccessibilityEvent(accessibilityEvent) { onAccessibilityEvent(accessibilityEvent) {
console.log('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent)); console.info('AccessibilityExtAbility onAccessibilityEvent: ' + JSON.stringify(accessibilityEvent));
if (accessibilityEvent.eventType === 'pageStateUpdate') { if (accessibilityEvent.eventType === 'pageStateUpdate') {
console.log('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate'); console.info('AccessibilityExtAbility onAccessibilityEvent: pageStateUpdate');
// TODO: Develop custom logic. // TODO: Develop custom logic.
} }
} }
...@@ -119,3 +133,4 @@ To enable or disable an accessibility extension service, run the following comma ...@@ -119,3 +133,4 @@ To enable or disable an accessibility extension service, run the following comma
In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve). In the preceding commands, **AccessibilityExtAbility** indicates the name of the accessibility extension service, **com.example.demo** indicates the bundle name, and **rg** indicates the capabilities (**r** is short for retrieve).
If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed. If the service is enabled or disabled successfully, the message "enable ability successfully" or "disable ability successfully" is displayed.
# Launching a UIAbility in the Background Through the call Event
There may be cases you want to provide in a widget access to features available in your application when it is running in the foreground, for example, the play, pause, and stop buttons in a music application widget. This is where the **call** capability of the **postCardAction** API comes in handy. This capability, when used in a widget, can start the specified UIAbility of the widget provider in the background. It also allows the widget to call the specified method of the application and transfer data so that the application, while in the background, can behave accordingly in response to touching of the buttons on the widget.
Generally, buttons are used to trigger the **call** event. Below is an example.
- In this example, two buttons are laid out on the widget page. When one button is clicked, the **postCardAction** API is called to send a **call** event to the target UIAbility. Note that the **method** parameter in the API indicates the method to call in the target UIAbility. It is mandatory and of the string type.
```ts
@Entry
@Component
struct WidgetCard {
build() {
Column() {
Button ('Feature A')
.margin('20%')
.onClick(() => {
console.info('call EntryAbility funA');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
'params': {
'method': 'funA' // Set the name of the method to call in the EntryAbility.
}
});
})
Button ('Feature B')
.margin('20%')
.onClick(() => {
console.info('call EntryAbility funB');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
'params': {
'method': 'funB', // Set the name of the method to call in the EntryAbility.
'num': 1 // Set other parameters to be transferred.
}
});
})
}
.width('100%')
.height('100%')
}
}
```
- The UIAbility receives the **call** event and obtains the transferred parameters. It then executes the target method specified by the **method** parameter. Other data can be obtained in readString mode. Listen for the method required by the **call** event in the **onCreate** callback of the UIAbility.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
function FunACall(data) {
// Obtain all parameters transferred in the call event.
console.info('FunACall param:' + JSON.stringify(data.readString()));
return null;
}
function FunBCall(data) {
console.info('FunACall param:' + JSON.stringify(data.readString()));
return null;
}
export default class CameraAbility extends UIAbility {
// If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received.
onCreate(want, launchParam) {
try {
// Listen for the method required by the call event.
this.callee.on('funA', FunACall);
this.callee.on('funB', FunBCall);
} catch (error) {
console.error(`Failed to register callee on. Cause: ${JSON.stringify(err)}`);
}
}
// Deregister the listener when the process exits.
onDestroy() {
try {
this.callee.off('funA');
this.callee.off('funB');
} catch (err) {
console.error(`Failed to register callee off. Cause: ${JSON.stringify(err)}`);
}
}
};
```
# Updating Widget Content Through FormExtensionAbility # Updating Widget Content Through the message Event
On the widget page, the **postCardAction** API can be used to trigger a message event to the FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode. On the widget page, the **postCardAction** API can be used to trigger a message event to start a FormExtensionAbility, which then updates the widget content. The following is an example of this widget update mode.
- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. - On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility.
...@@ -57,10 +57,10 @@ On the widget page, the **postCardAction** API can be used to trigger a message ...@@ -57,10 +57,10 @@ On the widget page, the **postCardAction** API can be used to trigger a message
}) })
} }
// ... ...
} }
``` ```
The figure below shows the effect. The figure below shows the effect.
![WidgetUpdatePage](figures/WidgetUpdatePage.png) ![WidgetUpdatePage](figures/WidgetUpdatePage.png)
# Widget Event Capability Overview # Widget Event Capability Overview
The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget. The ArkTS widget provides the **postCardAction()** API for interaction between the widget internal and the provider application. Currently, this API supports the router, message, and call events and can be called only in the widget.
![WidgetPostCardAction](figures/WidgetPostCardAction.png) ![WidgetPostCardAction](figures/WidgetPostCardAction.png)
**Definition**: postCardAction(component: Object, action: Object): void
Definition: postCardAction(component: Object, action: Object): void **Parameters**
Parameters:
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| component | Object | Yes| Instance of the current custom component. Generally, **this** is transferred.| | component | Object | Yes| Instance of the current custom component. Generally, **this** is transferred.|
| action | Object | Yes| Action description. For details, see the following table.| | action | Object | Yes| Action description. For details, see the following table.|
**Description of the action parameter**
Description of the action parameter | Key | Value | Description|
| **Key** | **Value** | Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| "action" | string | Action type.<br>- **"router"**: application redirection. If this type of action is triggered, the corresponding UIAbility is displayed. Only the UIAbility of the current application can be displayed.<br>- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.<br>- **"call"**: application startup in the background. If this type of action is triggered, the corresponding UIAbility is started but does not run in the foreground. The target application must have the permission to run in the background ([ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running)).| | "action" | string | Action type.<br>- **"router"**: redirection to the specified UIAbility of the widget provider.<br>- **"message"**: custom message. If this type of action is triggered, the [onFormEvent()](../reference/apis/js-apis-app-form-formExtensionAbility.md#onformevent) lifecycle callback of the provider FormExtensionAbility is called.<br>- **"call"**: launch of the widget provider in the background. If this type of action is triggered, the specified UIAbility of the widget provider is started in the background, but not displayed in the foreground. This action type requires that the widget provider should have the [ohos.permission.KEEP_BACKGROUND_RUNNING](../security/permission-list.md#ohospermissionkeep_background_running) permission.|
| "bundleName" | string | Name of the target bundle when **action** is **"router"** or **"call"**. This parameter is optional.| | "bundleName" | string | Name of the target bundle when **action** is **"router"** or **"call"**. This parameter is optional.|
| "moduleName" | string | Name of the target module when **action** is **"router"** or **"call"**. This parameter is optional.| | "moduleName" | string | Name of the target module when **action** is **"router"** or **"call"**. This parameter is optional.|
| "abilityName" | string | Name of the target UIAbility when **action** is **"router"** or **"call"**. This parameter is mandatory.| | "abilityName" | string | Name of the target UIAbility when **action** is **"router"** or **"call"**. This parameter is mandatory.|
| "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format.| | "params" | Object | Additional parameters carried in the current action. The value is a key-value pair in JSON format. For the **"call"** action type, the **method** parameter must be set and its value type must be string. This parameter is mandatory.|
Sample code of the **postCardAction()** API: Sample code of the **postCardAction()** API:
```typescript ```typescript
Button ('Jump') Button ('Jump')
.width('40%') .width('40%')
...@@ -45,18 +36,26 @@ Button ('Jump') ...@@ -45,18 +36,26 @@ Button ('Jump')
'bundleName': 'com.example.myapplication', 'bundleName': 'com.example.myapplication',
'abilityName': 'EntryAbility', 'abilityName': 'EntryAbility',
'params': { 'params': {
'message': 'testForRouter' // Customize the message to be sent. 'message': 'testForRouter' // Customize the message to send.
} }
}); });
}) })
```
The following are typical widget development scenarios that can be implemented through widget events:
Button ('Start in Background')
.width('40%')
.height('20%')
.onClick(() => {
postCardAction(this, {
'action': 'call',
'bundleName': 'com.example.myapplication',
'abilityName': 'EntryAbility',
'params': {
'method': 'fun', // Set the name of the method to call. It is mandatory.
'message': 'testForcall' // Customize the message to send.
}
});
})
```
- [Updating Widget Content Through FormExtensionAbility](arkts-ui-widget-event-formextensionability.md)
- [Updating Widget Content Through UIAbility](arkts-ui-widget-event-uiability.md)
- [Redirecting to a Specified Page Through the Router Event](arkts-ui-widget-event-router.md) Read on to learn the typical widget development scenarios that can be implemented through widget events.
# Redirecting to a Specified Page Through the Router Event # Redirecting to a UIAbility Through the router Event
The **router** capability of the **postCardAction** API can be used in a widget to quickly start the widget provider application. An application can provide different buttons through the widget so that users can jump to different pages at the touch of a button. For example, a camera widget provides the buttons that direct the user to respective pages, such as the page for taking a photo and the page for recording a video.
The **router** capability of the **postCardAction** API can be used in a widget to quickly start a specific UIAbility of the widget provider. By leveraging this capability, an application can provide in the widget multiple buttons, each of which targets a different target UIAbility. For example, a camera widget can provide the buttons that redirect the user to the UIAbility for taking a photo and the UIAbility for recording a video.
![WidgerCameraCard](figures/WidgerCameraCard.png) ![WidgerCameraCard](figures/WidgerCameraCard.png)
......
# Updating Widget Content Through UIAbility # Updating Widget Content Through the router or call Event
On the widget page, the **postCardAction** API can be used to trigger a router or call event to start the UIAbility, which then updates the widget content. The following is an example of this widget update mode. On the widget page, the **postCardAction** API can be used to trigger a router or call event to start a UIAbility, which then updates the widget content. The following is an example of this widget update mode.
## Updating Widget Content Through the router Event
- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the FormExtensionAbility. - On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the **router** event to the FormExtensionAbility.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
...@@ -84,3 +85,104 @@ On the widget page, the **postCardAction** API can be used to trigger a router o ...@@ -84,3 +85,104 @@ On the widget page, the **postCardAction** API can be used to trigger a router o
... ...
} }
``` ```
## Updating Widget Content Through the call Event
- When using the **call** event of the **postCardAction** API, the value of **formId** must be updated in the **onAddForm** callback of the FormExtensionAbility.
```ts
import formBindingData from '@ohos.app.form.formBindingData';
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class EntryFormAbility extends FormExtensionAbility {
onAddForm(want) {
let formId = want.parameters["ohos.extra.param.key.form_identity"];
let dataObj1 = {
"formId": formId
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
...
};
```
- On the widget page, register the **onClick** event callback of the button and call the **postCardAction** API in the callback to trigger the event to the UIAbility.
```ts
let storage = new LocalStorage();
@Entry(storage)
@Component
struct WidgetCard {
@LocalStorageProp('detail') detail: string = 'init';
@LocalStorageProp('formId') formId: string = '0';
build() {
Column() {
Button ('Start in Background')
.margin('20%')
.onClick(() => {
console.info('postCardAction to EntryAbility');
postCardAction(this, {
'action': 'call',
'abilityName': 'EntryAbility', // Only the UIAbility of the current application is allowed.
'params': {
'method': 'funA',
'formId': this.formId,
'detail': 'CallFromCard'
}
});
})
Text(`${this.detail}`).margin('20%')
}
.width('100%')
.height('100%')
}
}
```
- Listen for the method required by the **call** event in the **onCreate** callback of the UIAbility, and then call the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) API in the corresponding method to update the widget.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
import formInfo from '@ohos.app.form.formInfo';
const MSG_SEND_METHOD: string = 'funA';
// After the call event is received, the method listened for by the callee is triggered.
function FunACall(data) {
// Obtain all parameters transferred in the call event.
let params = JSON.parse(data.readString())
if (params.formId !== undefined) {
let curFormId = params.formId;
let message = params.detail;
console.info(`UpdateForm formId: ${curFormId}, message: ${message}`);
let formData = {
"detail": message
};
let formMsg = formBindingData.createFormBindingData(formData)
formProvider.updateForm(curFormId, formMsg).then((data) => {
console.info('updateForm success.' + JSON.stringify(data));
}).catch((error) => {
console.error('updateForm failed:' + JSON.stringify(error));
})
}
return null;
}
export default class EntryAbility extends UIAbility {
// If the UIAbility is started for the first time, the onCreate lifecycle callback is triggered after the call event is received.
onCreate(want, launchParam) {
console.info('Want:' + JSON.stringify(want));
try {
// Listen for the method required by the call event.
this.callee.on(MSG_SEND_METHOD, FunACall);
} catch (error) {
console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
}
...
}
```
# Updating Local and Online Images in the Widget # Updating Local and Online Images in the Widget
Generally, local images or online images downloaded from the network need to be displayed on a widget. To obtain local and online images, use the FormExtensionAbility. The following exemplifies how to show local and online images on a widget. Typically, a widget includes local images or online images downloaded from the network. To obtain local and online images, use the FormExtensionAbility. The following exemplifies how to show local and online images on a widget.
1. Internet access is required for downloading online images. Therefore, you need to apply for the **ohos.permission.INTERNET** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md). 1. For the widget to download online images, declare the **ohos.permission.INTERNET** permission for the widget. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md).
2. Update local files in the **onAddForm** lifecycle callback of the EntryFormAbility. 2. Update local files in the **onAddForm** lifecycle callback of the EntryFormAbility.
...@@ -44,7 +44,7 @@ Generally, local images or online images downloaded from the network need to be ...@@ -44,7 +44,7 @@ Generally, local images or online images downloaded from the network need to be
} }
``` ```
3. Update online files in the onFormEvent lifecycle callback of the EntryFormAbility. 3. Update online images in the **onFormEvent** lifecycle callback of the EntryFormAbility.
```ts ```ts
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
...@@ -60,8 +60,8 @@ Generally, local images or online images downloaded from the network need to be ...@@ -60,8 +60,8 @@ Generally, local images or online images downloaded from the network need to be
'text': 'Updating...' 'text': 'Updating...'
}) })
formProvider.updateForm(formId, formInfo) formProvider.updateForm(formId, formInfo)
// Note: The FormExtensionAbility is started when the lifecycle callback is triggered. It can run in the background for only 5 seconds. // Note: After being started with the triggering of the lifecycle callback, the FormExtensionAbility can run in the background for only 5 seconds.
// When possible, limit the size of the image to download. If an image cannot be downloaded within 5 seconds, it cannot be updated to the widget page. // When possible, limit the size of the image to download. If an image cannot be downloaded within 5 seconds, it will not be updated to the widget page.
let netFile = 'https://xxxx/xxxx.png'; // Specify the URL of the image to download. let netFile = 'https://xxxx/xxxx.png'; // Specify the URL of the image to download.
let tempDir = this.context.getApplicationContext().tempDir; let tempDir = this.context.getApplicationContext().tempDir;
let fileName = 'file' + Date.now(); let fileName = 'file' + Date.now();
...@@ -161,6 +161,6 @@ Generally, local images or online images downloaded from the network need to be ...@@ -161,6 +161,6 @@ Generally, local images or online images downloaded from the network need to be
``` ```
> **NOTE** > **NOTE**
> - The **\<Image>** component displays images in the remote memory based on the **memory://** identifier in the input parameter (**memory://fileName**). The **fileName** value must be consistent with the key in the object (**'formImages': {key: fd}**) passed by the EntryFormAbility. > - The **\<Image>** component displays images in the remote memory based on the **memory://** identifier in the input parameter (**memory://fileName**). The value of **fileName** must be consistent with the key in the object (**'formImages': {key: fd}**) passed by the EntryFormAbility.
> >
> - The **\<Image>** component determines whether to update the image based on whether the input parameter is changed. Therefore, the value of **imgName** passed by the EntryFormAbility each time must be different. If the two values of **imgName** passed consecutively are identical, the image is not updated. > - The **\<Image>** component determines whether to update the image by comparing the values of **imgName** consecutively passed by the EntryFormAbility. It updates the image only when the values are different.
...@@ -92,4 +92,5 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( ...@@ -92,4 +92,5 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility](
> **NOTE** > **NOTE**
> The FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. The FormExtensionAbility persists for 5 seconds after the lifecycle callback is completed and will exit if no new lifecycle callback is invoked during this time frame. For the service logic that may take more than 5 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md). After the processing is complete, use the [updateForm](../reference/apis/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update. >
> The FormExtensionAbility cannot reside in the background. It persists for 5 seconds after the lifecycle callback is completed and exist if no new lifecycle callback is invoked during this time frame. This means that continuous tasks cannot be processed in the widget lifecycle callbacks. For the service logic that may take more than 5 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md) for processing. After the processing is complete, use [updateForm()](../reference/apis/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update.
# ArkTS Widget Related Modules # ArkTS Widget Related Modules
**Figure 1** ArkTS widget related modules
**Figure 1** ArkTS widget related modules
![WidgetModules](figures/WidgetModules.png) ![WidgetModules](figures/WidgetModules.png)
...@@ -15,10 +15,10 @@ ...@@ -15,10 +15,10 @@
- [formBindingData](../reference/apis/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. - [formBindingData](../reference/apis/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information.
- [Page Layout (Card.ets)](arkts-ui-widget-page-overview.md): provides APIs for a declarative paradigm UI. - [Page layout (Card.ets)](arkts-ui-widget-page-overview.md): provides APIs for a declarative paradigm UI.
- [ArkTS widget capabilities](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget. - [Capabilities exclusive to ArkTS widgets](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget.
- [ArkTS widget capability list](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): lists the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. - [ArkTS widget capability list](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets.
- [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. - [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration.
- Configure FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md).
- Configure the widget configuration information (**WidgetCard.ets**) in the [form_config.json](arkts-ui-widget-configuration.md) file in **resources/base/profile**. - Configure the widget configuration information (**WidgetCard.ets**) in the [form_config.json](arkts-ui-widget-configuration.md) file in **resources/base/profile**.
# Using Animations in the Widget # Using Animations in the Widget
To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Note the following restrictions when using the animations in ArkTS widgets. To make your ArkTS widget more engaging, you can apply animations to it, including [explicit animation](../reference/arkui-ts/ts-explicit-animation.md), [attribute animation](../reference/arkui-ts/ts-animatorproperty.md), and [component transition](../reference/arkui-ts/ts-transition-animation-component.md). Just note the following restrictions when using the animations in ArkTS widgets.
**Table 1** Restrictions on animation parameters **Table 1** Restrictions on animation parameters
| Name| Description| Description| | Name| Description| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -13,14 +13,10 @@ To make your ArkTS widget more engaging, you can apply animations to it, includi ...@@ -13,14 +13,10 @@ To make your ArkTS widget more engaging, you can apply animations to it, includi
| delay | Animation delay duration.| Do not set this parameter in the widget. Use the default value 0.| | delay | Animation delay duration.| Do not set this parameter in the widget. Use the default value 0.|
| iterations | Number of times that the animation is played.| Do not set this parameter in the widget. Use the default value 1.| | iterations | Number of times that the animation is played.| Do not set this parameter in the widget. Use the default value 1.|
The following sample code implements the animation effect of button rotation: The following sample code implements the animation effect of button rotation:
![WidgetAnimation](figures/WidgetAnimation.gif) ![WidgetAnimation](figures/WidgetAnimation.gif)
```ts ```ts
@Entry @Entry
@Component @Component
......
# Applying Custom Drawing in the Widget # Applying Custom Drawing in the Widget
You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code shows how to draw a smiling face in the center of the canvas. You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code snippet draws a smiling face in the center of a canvas.
```typescript ```ts
@Entry @Entry
@Component @Component
struct Card { struct Card {
...@@ -30,41 +30,41 @@ struct Card { ...@@ -30,41 +30,41 @@ struct Card {
this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight); this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
// Draw a red circle in the center of the canvas. // Draw a red circle in the center of the canvas.
this.context.beginPath(); this.context.beginPath();
let radius = this.context.width / 3 let radius = this.context.width / 3;
let circleX = this.context.width / 2 let circleX = this.context.width / 2;
let circleY = this.context.height / 2 let circleY = this.context.height / 2;
this.context.moveTo(circleX - radius, circleY); this.context.moveTo(circleX - radius, circleY);
this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true); this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true);
this.context.closePath(); this.context.closePath();
this.context.fillStyle = 'red'; this.context.fillStyle = 'red';
this.context.fill(); this.context.fill();
// Draw the left eye of the smiling face. // Draw the left eye of the smiling face.
let leftR = radius / 4 let leftR = radius / 4;
let leftX = circleX - (radius / 2) let leftX = circleX - (radius / 2);
let leftY = circleY - (radius / 3.5) let leftY = circleY - (radius / 3.5);
this.context.beginPath(); this.context.beginPath();
this.context.arc(leftX, leftY, leftR, 0, Math.PI, true); this.context.arc(leftX, leftY, leftR, 0, Math.PI, true);
this.context.strokeStyle = '#ffff00' this.context.strokeStyle = '#ffff00';
this.context.lineWidth = 10 this.context.lineWidth = 10;
this.context.stroke() this.context.stroke();
// Draw the right eye of the smiling face. // Draw the right eye of the smiling face.
let rightR = radius / 4 let rightR = radius / 4;
let rightX = circleX + (radius / 2) let rightX = circleX + (radius / 2);
let rightY = circleY - (radius / 3.5) let rightY = circleY - (radius / 3.5);
this.context.beginPath(); this.context.beginPath();
this.context.arc(rightX, rightY, rightR, 0, Math.PI, true); this.context.arc(rightX, rightY, rightR, 0, Math.PI, true);
this.context.strokeStyle = '#ffff00' this.context.strokeStyle = '#ffff00';
this.context.lineWidth = 10 this.context.lineWidth = 10;
this.context.stroke() this.context.stroke();
// Draw the mouth of the smiling face. // Draw the mouth of the smiling face.
let mouthR = radius / 2.5 let mouthR = radius / 2.5;
let mouthX = circleX let mouthX = circleX;
let mouthY = circleY + (radius / 3) let mouthY = circleY + (radius / 3);
this.context.beginPath(); this.context.beginPath();
this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true); this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true);
this.context.strokeStyle = '#ffff00' this.context.strokeStyle = '#ffff00';
this.context.lineWidth = 10 this.context.lineWidth = 10;
this.context.stroke() this.context.stroke();
}) })
} }
}.height('100%').width('100%') }.height('100%').width('100%')
...@@ -72,8 +72,6 @@ struct Card { ...@@ -72,8 +72,6 @@ struct Card {
} }
``` ```
The figure below shows the effect. The figure below shows the effect.
![WidgetCanvasDemo](figures/WidgetCanvasDemo.png)
![WidgetCanvasDemo](figures/WidgetCanvasDemo.jpeg) \ No newline at end of file
# Updating Widget Content by State # Updating Widget Content by State
Multiple widgets of the same application can be configured to implement different features. For example, two weather widgets can be added to the home screen: one for displaying the weather of London, and the other Beijing. The widget is set to be updated at 07:00 every morning. It needs to detect the configured city, and then updates the city-specific weather information. The following example describes how to dynamically update the widget content based on the state. There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. In the following example, two weather widgets are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets.
- Widget configuration file: Configure the widget to be updated at 07:00 every morning. - Widget configuration file: Configure the widget to be updated at 07:00 every morning.
...@@ -74,7 +74,7 @@ Multiple widgets of the same application can be configured to implement differen ...@@ -74,7 +74,7 @@ Multiple widgets of the same application can be configured to implement differen
} }
Row() {// Content that is updated only in state A Row() {// Content that is updated only in state A
Text('State A: ') Text ('State A:')
Text(this.textA) Text(this.textA)
} }
...@@ -167,4 +167,5 @@ Multiple widgets of the same application can be configured to implement differen ...@@ -167,4 +167,5 @@ Multiple widgets of the same application can be configured to implement differen
> **NOTE** > **NOTE**
>
> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used to determine whether the currently added widget is a normal one in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. > When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used to determine whether the currently added widget is a normal one in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion.
...@@ -5,7 +5,7 @@ Before configuring a widget to update periodically, enable the periodic update f ...@@ -5,7 +5,7 @@ Before configuring a widget to update periodically, enable the periodic update f
The widget framework provides the following modes of updating widgets periodically: The widget framework provides the following modes of updating widgets periodically:
- Set the update interval: The widget will be updated at the specified interval. You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour. - Set the update interval: The widget will be updated at the specified interval by calling [onUpdateForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onupdateform). You can specify the interval by setting the [updateDuration](arkts-ui-widget-configuration.md) field in the **form_config.json** file. For example, you can configure the widget to update once an hour.
> **NOTE** > **NOTE**
> >
......
...@@ -7,8 +7,7 @@ OpenHarmony provides Common Event Service (CES) for applications to subscribe to ...@@ -7,8 +7,7 @@ OpenHarmony provides Common Event Service (CES) for applications to subscribe to
Common events are classified into system common events and custom common events. Common events are classified into system common events and custom common events.
- System common events: defined in CES. Only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see [Support](../reference/apis/js-apis-commonEventManager.md#support). - System common events: defined in CES. Currently, only system applications and system services can publish system common events, such as HAP installation, update, and uninstall. For details about the supported system common events, see [System Common Events](../reference/apis/commonEventManager-definitions.md).
- Custom common events: customized by applications to implement cross-process event communication. - Custom common events: customized by applications to implement cross-process event communication.
...@@ -16,9 +15,7 @@ Common events are also classified into unordered, ordered, and sticky common eve ...@@ -16,9 +15,7 @@ Common events are also classified into unordered, ordered, and sticky common eve
- Unordered common events: common events that CES forwards regardless of whether subscribers receive the events and when they subscribe to the events. - Unordered common events: common events that CES forwards regardless of whether subscribers receive the events and when they subscribe to the events.
- Ordered common events: common events that CES forwards based on the subscriber priority. CES preferentially forwards an ordered common event to the subscriber with higher priority, waits until the subscriber receives the event, and then forwards the events to the subscriber with lower priority. Subscribers with the same priority receive common events in a random order.
- Ordered common events: common events that CES forwards based on the subscriber priority. CES forwards common events to the subscriber with lower priority only after receiving a reply from the previous subscriber with higher priority. Subscribers with the same priority receive common events in a random order.
- Sticky common events: common events that can be sent to a subscriber before or after they initiate a subscription. Only system applications and system services can send sticky common events, which remain in the system after being sent. The sends must first request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). - Sticky common events: common events that can be sent to a subscriber before or after they initiate a subscription. Only system applications and system services can send sticky common events, which remain in the system after being sent. The sends must first request the **ohos.permission.COMMONEVENT_STICKY** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
......
# Removing Sticky Common Events # Removing Sticky Common Events (for System Applications Only)
## When to Use ## When to Use
...@@ -16,21 +16,26 @@ For details, see [Common Event](../reference/apis/js-apis-commonEventManager.md) ...@@ -16,21 +16,26 @@ For details, see [Common Event](../reference/apis/js-apis-commonEventManager.md)
## How to Develop ## How to Develop
1. Import the module. 1. Request the **ohos.permission.COMMONEVENT_STICKY** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Import the module.
```ts ```ts
import commonEventManager from '@ohos.commonEventManager'; import commonEventManager from '@ohos.commonEventManager';
``` ```
2. The sticky common event to be removed must have been released by the application. For details about how to release sticky common events, see [Publishing Common Events](common-event-publish.md). 3. Call the [removeStickyCommonEvent()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerremovestickycommonevent10) API to remove the target sticky common event.
> **NOTE**
>
> The sticky common event to be removed must have been released by the application. For details about how to release sticky common events, see [Publishing Common Events](common-event-publish.md).
```ts ```ts
CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { // sticky_event indicates the name of the sticky common event to remove. commonEventManager.removeStickyCommonEvent("sticky_event", (err) => { // sticky_event indicates the name of the target sticky common event.
if (err) { if (err) {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); console.error(`Failed to remove sticky common event. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`Remove sticky event AsyncCallback success`); console.info(`Succeeded in removeing sticky event.`);
}
}); });
``` ```
...@@ -2,38 +2,46 @@ ...@@ -2,38 +2,46 @@
## When to Use ## When to Use
A static subscriber is started once it receives a target event published by the system or application. At the same time, the **onReceiveEvent** callback is triggered, in which you can implement the service logic. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks. Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. Note that this subscribing mode has negative impact on system power consumption. Therefore, exercise caution when using this mode. A static subscriber is started once it receives a target event published by the system or application. At the same time, the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback is triggered.
You can implement the service logic in the [onReceiveEvent()](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md#staticsubscriberextensionabilityonreceiveevent) callback. For example, if an application needs to execute some initialization tasks during device power-on, the application can subscribe to the power-on event in static mode. After receiving the power-on event, the application is started to execute the initialization tasks.
Subscribing to a common event in static mode is achieved by configuring a declaration file and implementing a class that inherits from [StaticSubscriberExtensionAbility](../reference/apis/js-apis-application-staticSubscriberExtensionAbility.md).
> **NOTE**
>
> The static subscription mode has negative impact on system power consumption. Therefore, exercise caution when using this mode.
## How to Develop ## How to Develop
1. Declaring a Static Subscriber 1. Declaring a static subscriber.
To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project. The sample code is as follows: To declare a static subscriber, create an ExtensionAbility, which is derived from the **StaticSubscriberExtensionAbility** class, in the project.
You can implement service logic in the **onReceiveEvent()** callback.
```ts ```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'
export default class StaticSubscriber extends StaticSubscriberExtensionAbility { export default class StaticSubscriber extends StaticSubscriberExtensionAbility {
onReceiveEvent(event) { onReceiveEvent(event) {
console.log('onReceiveEvent, event:' + event.event); console.info('onReceiveEvent, event: ' + event.event);
} }
} }
``` ```
You can implement service logic in the **onReceiveEvent** callback. 2. Configure static subscriber settings.
2. Project Configuration for a Static Subscriber
After writing the static subscriber code, configure the subscriber in the **module.json5** file. The configuration format is as follows: After writing the static subscriber code, configure the subscriber in the [module.json5](../quick-start/module-configuration-file.md) file.
```ts ```ts
{ {
"module": { "module": {
...... ...
"extensionAbilities": [ "extensionAbilities": [
{ {
"name": "StaticSubscriber", "name": "StaticSubscriber",
"srcEntry": "./ets/StaticSubscriber/StaticSubscriber.ts", "srcEntry": "./ets/staticsubscriber/StaticSubscriber.ts",
"description": "$string:StaticSubscriber_desc", "description": "$string:StaticSubscriber_desc",
"icon": "$media:icon", "icon": "$media:icon",
"label": "$string:StaticSubscriber_label", "label": "$string:StaticSubscriber_label",
...@@ -47,14 +55,14 @@ A static subscriber is started once it receives a target event published by the ...@@ -47,14 +55,14 @@ A static subscriber is started once it receives a target event published by the
] ]
} }
] ]
...... ...
} }
} }
``` ```
Pay attention to the following fields in the JSON file: Some fields in the file are described as follows:
- **srcEntry**: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2. - **srcEntry **: entry file path of the ExtensionAbility, that is, the file path of the static subscriber declared in Step 2.
- **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**. - **type**: ExtensionAbility type. For a static subscriber, set this field to **staticSubscriber**.
...@@ -62,42 +70,46 @@ A static subscriber is started once it receives a target event published by the ...@@ -62,42 +70,46 @@ A static subscriber is started once it receives a target event published by the
- **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification. - **name**: name of the ExtensionAbility. For a static subscriber, declare the name as **ohos.extension.staticSubscriber** for successful identification.
- **resource**: path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**. - **resource**: path that stores the ExtensionAbility configuration, which is customizable. In this example, the path is **resources/base/profile/subscribe.json**.
A level-2 configuration file pointed to by **metadata** must be in the following format:
```ts 3. Configure the level-2 configuration file to which the metadata points.
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
If the level-2 configuration file is not declared in this format, the file cannot be identified. The fields are described as follows: ```json
{
"commonEvents": [
{
"name": "xxx",
"permission": "xxx",
"events":[
"xxx"
]
}
]
}
```
- **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**. If the level-2 configuration file is not declared in this format, the file cannot be identified. Some fields in the file are described as follows:
- **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published. - **name**: name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.
- **permission**: permission required for the publisher. If a publisher without the required permission attempts to publish an event, the event is regarded as invalid and will not be published.
- **events**: list of target events to subscribe to.
- **events**: list of target events to subscribe to. 4. Modify the [preset configuration file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) of the device, that is, the **/system/etc/app/install_list_permission.json** file on the device. When the device is started, this file is read. During application installation, the common event type specified by **allowCommonEvent** in the file is authorized. The **install_list_permission.json** file contains the following fields:
3. Device System Configuration - **bundleName**: bundle name of the application.
- **app_signature**: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install_list_capabilityjson).
- **allowCommonEvent**: type of common event that can be started by static broadcast.
In the device system configuration file **/system/etc/app/install_list_capability.json**, add the bundle name of the static subscriber. > **NOTE**
>
> The **install_list_permissions.json** file is available only for preinstalled applications.
```json ```json
{ [
"install_list": [ {
{ "bundleName": "com.example.myapplication",
"bundleName": "ohos.extension.staticSubscriber", "app_signature": ["****"],
"allowCommonEvent": ["usual.event.A", "usual.event.B"], "allowCommonEvent": ["usual.event.A", "usual.event.B"]
} }
] ]
}
``` ```
# Common Event Subscription Overview # Common Event Subscription Overview
The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not. The common event service provides two subscription modes: dynamic and static. The biggest difference between these two modes is that dynamic subscription requires the application to be running, while static subscription does not.
- In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md). - In dynamic subscription mode, a subscriber subscribes to common events by calling an API during the running period. For details, see [Subscribing to Common Events in Dynamic Mode](common-event-subscription.md).
- In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from StaticSubscriberExtensionAbility. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md). - In static subscription mode, a subscriber subscribes to common events by configuring a declaration file and implementing a class that inherits from **StaticSubscriberExtensionAbility**. For details, see [Subscribing to Common Events in Static Mode](common-event-static-subscription.md).
...@@ -32,7 +32,7 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ...@@ -32,7 +32,7 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common
let subscriber = null; let subscriber = null;
// Subscriber information. // Subscriber information.
let subscribeInfo = { let subscribeInfo = {
events: ["usual.event.SCREEN_OFF"], // Subscribe to the common event screen-off. events: ["usual.event.SCREEN_OFF"], // Subscribe to the common event screen-off.
} }
``` ```
...@@ -41,13 +41,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ...@@ -41,13 +41,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common
```ts ```ts
// Callback for subscriber creation. // Callback for subscriber creation.
commonEventManager.createSubscriber(subscribeInfo, (err, data) => { commonEventManager.createSubscriber(subscribeInfo, (err, data) => {
if (err) { if (err) {
console.error(`[CommonEvent] CreateSubscriberCallBack err=${JSON.stringify(err)}`); console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
} else { return;
console.info(`[CommonEvent] CreateSubscriber success`); }
subscriber = data; console.info('Succeeded in creating subscriber.');
// Callback for common event subscription. subscriber = data;
} // Callback for common event subscription.
}) })
``` ```
...@@ -56,14 +56,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common ...@@ -56,14 +56,13 @@ For details about the APIs, see [API Reference](../reference/apis/js-apis-common
```ts ```ts
// Callback for common event subscription. // Callback for common event subscription.
if (subscriber !== null) { if (subscriber !== null) {
commonEventManager.subscribe(subscriber, (err, data) => { commonEventManager.subscribe(subscriber, (err, data) => {
if (err) { if (err) {
console.error(`[CommonEvent] SubscribeCallBack err=${JSON.stringify(err)}`); console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
} else { return;
console.info(`[CommonEvent] SubscribeCallBack data=${JSON.stringify(data)}`); }
} })
})
} else { } else {
console.error(`[CommonEvent] Need create subscriber`); console.error(`Need create subscriber`);
} }
``` ```
# InputMethodExtensionAbility Development # InputMethodExtensionAbility Development
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) is an ExtensionAbility component of the inputMethod type that provides extension capabilities for the input method framework. ## When to Use
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md), inherited from [ExtensionAbility](extensionability-overview.md), is used for developing input method applications.
InputMethodExtensionAbility can be started or connected by other application components to process transactions in the background based on the request of the caller. The entire lifecycle of the [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) instance and the owning ExtensionAbility process is scheduled and managed by the input method framework. The input method framework provides the [InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) base class. Derive this base class to implement initialization and resource clearing.
[InputMethodExtensionAbility](../reference/apis/js-apis-inputmethod-extension-ability.md) provides related capabilities through [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md).
InputMethodExtensionAbility provides related capabilities through the [InputMethodExtensionContext](../reference/apis/js-apis-inputmethod-extension-context.md).
## Implementing an Input Method Application ## Implementing an Input Method Application
...@@ -13,15 +13,13 @@ InputMethodExtensionAbility provides related capabilities through the [InputMeth ...@@ -13,15 +13,13 @@ InputMethodExtensionAbility provides related capabilities through the [InputMeth
InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required. InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** callbacks, as described below. Override them as required.
- **onCreate** - **onCreate**
This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener. This callback is triggered when a service is created for the first time. You can perform initialization operations, for example, registering a common event listener.
> **NOTE** > **NOTE**
> >
> If a service has been created, starting it again does not trigger the **onCreate()** callback. > If a service has been created, starting it again does not trigger the **onCreate()** callback.
- **onDestroy** - **onDestroy**
This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener. This callback is triggered when the service is no longer used and the instance is ready for destruction. You can clear resources in this callback, for example, deregister the listener.
...@@ -29,7 +27,7 @@ InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** call ...@@ -29,7 +27,7 @@ InputMethodExtensionAbility provides the **onCreate()** and **onDestory()** call
To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows: To implement an input method application, manually create an InputMethodExtensionAbility component in DevEco Studio. The procedure is as follows:
In the **ets** directory of the target module, right-click and choose **New** > **Extention Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility. In the **ets** directory of the target module, right-click and choose **New** > **Extension Ability** > **InputMethod** to a minimum template of InputMethodExtensionAbility.
> **NOTE** > **NOTE**
> >
...@@ -70,7 +68,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -70,7 +68,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
onDestroy() { onDestroy() {
console.log("onDestroy."); console.log("onDestroy.");
this.context.destroy(); this.keyboardController.onDestroy(); // Destroy the window and deregister the event listener.
} }
} }
``` ```
...@@ -109,7 +107,6 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -109,7 +107,6 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
this.unRegisterListener(); // Deregister the event listener. this.unRegisterListener(); // Deregister the event listener.
let win = windowManager.findWindow(this.windowName); let win = windowManager.findWindow(this.windowName);
win.destroyWindow(); // Destroy the window. win.destroyWindow(); // Destroy the window.
this.mContext.terminateSelf(); // Terminate the InputMethodExtensionAbility service.
} }
private initWindow(): void // Initialize the window. private initWindow(): void // Initialize the window.
...@@ -159,7 +156,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -159,7 +156,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
}) })
globalThis.inputAbility.on('inputStop', (imeId) => { globalThis.inputAbility.on('inputStop', (imeId) => {
if (imeId == "Bundle name/Ability name") { if (imeId == "Bundle name/Ability name") {
this.onDestroy(); this.mContext.destroy(); // Destroy the InputMethodExtensionAbility service.
} }
}); });
} }
...@@ -233,7 +230,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -233,7 +230,7 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file. Add the path to this file to the **src** field in the **resources/base/profile/main_pages.json** file.
```ts ```ets
import { numberSourceListData, sourceListType } from './keyboardKeyData' import { numberSourceListData, sourceListType } from './keyboardKeyData'
@Component @Component
...@@ -342,12 +339,12 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -342,12 +339,12 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
} }
``` ```
Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the target module. Set **type** to **"inputMethod"** and **srcEntry** to the code path of the InputMethodExtensionAbility component. 5. Register the InputMethodExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) corresponding to the **Module** project. Set **type** to **"inputMethod"** and **srcEntry** to the code path of the InputMethodExtensionAbility component.
```ts ```ts
{ {
"module": { "module": {
// ... ...
"extensionAbilities": [ "extensionAbilities": [
{ {
"description": "inputMethod", "description": "inputMethod",
...@@ -364,3 +361,47 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth ...@@ -364,3 +361,47 @@ The minimum template contains four files: **KeyboardController.ts**, **InputMeth
## Restrictions
To reduce the risk of abuse of the InputMethodExtensionAbility by third-party applications, the invoking of APIs in the following modules is restricted in the InputMethodExtensionAbility:
> **NOTE**
>
> - If a restricted module is imported, no error is reported during compilation, but an incorrect value (**undefined**) is returned during running. As a result, the module does not take effect.
> - Currently, access to the [@ohos.multimedia.audio (Audio Management)](../reference/apis/js-apis-audio.md) module is allowed, with compliance with the following rules:
> - Users who deny the recording permission should still be allowed to use the non-voice-input features of the input method application.
> - Recording-related services are allowed only when the InputMethodExtensionAbility is in the foreground. For example, perform recording only when the soft keyboard is in the foreground and the user is proactively using the voice input method; stop recording when the application is switched to the background.
> - Applications will see increasingly stringent measures against violations with the preceding rules, and any violation may result in function exceptions.
**Restricted modules:**
- [@ohos.ability.featureAbility (FeatureAbility)](../reference/apis/js-apis-ability-featureAbility.md)
- [@ohos.ability.particleAbility (ParticleAbility)](../reference/apis/js-apis-ability-particleAbility.md)
- [@ohos.account.distributedAccount (Distributed Account Management)](../reference/apis/js-apis-distributed-account.md)
- [@ohos.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-backgroundTaskManager.md)
- [@ohos.bluetooth (Bluetooth)](../reference/apis/js-apis-bluetooth.md)
- [@ohos.bluetoothManager (Bluetooth)](../reference/apis/js-apis-bluetoothManager.md)
- [@ohos.connectedTag (Active Tags)](../reference/apis/js-apis-connectedTag.md)
- [@ohos.geolocation (Geolocation)](../reference/apis/js-apis-geolocation.md)
- [@ohos.geoLocationManager (Geolocation Manager)](../reference/apis/js-apis-geoLocationManager.md)
- [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](../reference/apis/js-apis-cardEmulation.md)
- [@ohos.nfc.controller (Standard NFC)](../reference/apis/js-apis-nfcController.md)
- [@ohos.nfc.tag (Standard NFC Tags)](../reference/apis/js-apis-nfcTag.md)
- [@ohos.reminderAgent (Reminder Agent)](../reference/apis/js-apis-reminderAgent.md)
- [@ohos.reminderAgentManager (reminderAgentManager)](../reference/apis/js-apis-reminderAgentManager.md)
- [@ohos.sensor (Sensor)](../reference/apis/js-apis-sensor.md)
- [@ohos.telephony.call (Call)](../reference/apis/js-apis-call.md)
- [@ohos.telephony.data (Cellular Data)](../reference/apis/js-apis-telephony-data.md)
- [@ohos.telephony.observer (observer)](../reference/apis/js-apis-observer.md)
- [@ohos.telephony.radio (Network Search)](../reference/apis/js-apis-radio.md)
- [@ohos.telephony.sim (SIM Management)](../reference/apis/js-apis-sim.md)
- [@ohos.telephony.sms (SMS)](../reference/apis/js-apis-sms.md)
- [@ohos.wallpaper (Wallpaper)](../reference/apis/js-apis-wallpaper.md)
- [@ohos.wifiext (WLAN Extension)](../reference/apis/js-apis-wifiext.md)
- [@ohos.wifiManager (WLAN)](../reference/apis/js-apis-wifiManager.md)
- [@ohos.wifiManagerExt (WLAN Extension Interface)](../reference/apis/js-apis-wifiManagerExt.md)
- [@system.geolocation (Geolocation)](../reference/apis/js-apis-system-location.md)
- [nfctech (Standard NFC Technologies)](../reference/apis/js-apis-nfctech.md)
- [tagSession (Standard NFC Tag Session)](../reference/apis/js-apis-tagSession.md)
...@@ -6,7 +6,7 @@ A service widget (also called widget) is a set of UI components that display imp ...@@ -6,7 +6,7 @@ A service widget (also called widget) is a set of UI components that display imp
## Service Widget Architecture ## Service Widget Architecture
**Figure 1** Service widget architecture **Figure 1** Service widget architecture
![WidgetArchitecture](figures/WidgetArchitecture.png) ![WidgetArchitecture](figures/WidgetArchitecture.png)
...@@ -24,7 +24,7 @@ Before you get started, it would be helpful if you have a basic understanding of ...@@ -24,7 +24,7 @@ Before you get started, it would be helpful if you have a basic understanding of
Below is the typical procedure of using the widget: Below is the typical procedure of using the widget:
**Figure 2** Typical procedure of using the widget **Figure 2** Typical procedure of using the widget
![WidgetUse](figures/WidgetUse.png) ![WidgetUse](figures/WidgetUse.png)
...@@ -55,4 +55,4 @@ ArkTS widgets and JS widgets have different implementation principles and featur ...@@ -55,4 +55,4 @@ ArkTS widgets and JS widgets have different implementation principles and featur
| Custom drawing| Not supported| Supported| | Custom drawing| Not supported| Supported|
| Logic code execution (excluding the import capability)| Not supported| Supported| | Logic code execution (excluding the import capability)| Not supported| Supported|
As can be seen above, ArkTS widgets have more capabilities and use cases than JS widgets. Therefore, ArkTS widgets are always recommended, except for the case where the widget consists of only static pages. As can be seen above, ArkTS widgets provide more capabilities and use cases than JS widgets. Therefore, ArkTS widgets are always recommended, except for the case where the widget consists of only static pages.
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
- [HTTP Data Request](http-request.md) - [HTTP Data Request](http-request.md)
- [WebSocket Connection](websocket-connection.md) - [WebSocket Connection](websocket-connection.md)
- [Socket Connection](socket-connection.md) - [Socket Connection](socket-connection.md)
- [Network Policy Management](net-policy-management.md)
- [Network Sharing](net-sharing.md) - [Network Sharing](net-sharing.md)
- [Ethernet Connection](net-ethernet.md) - [Ethernet Connection](net-ethernet.md)
- [Network Connection Management](net-connection-manager.md) - [Network Connection Management](net-connection-manager.md)
......
...@@ -39,7 +39,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -39,7 +39,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme
| ---- | ---- | ---- | | ---- | ---- | ---- |
| ohos.net.connection | function getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getDefaultNet(callback: AsyncCallback\<NetHandle>): void; |Creates a **NetHandle** object that contains the **netId** of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getGlobalHttpProxy<sup>10+</sup>(callback: AsyncCallback\<HttpProxy>): void;| Obtains the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function setGlobalHttpProxy<sup>10+</sup>(httpProxy: HttpProxy, callback: AsyncCallback\<void>): void;| Sets the global HTTP proxy for the network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getAppNet<sup>9+</sup>(callback: AsyncCallback\<NetHandle>): void;| Obtains a **NetHandle** object that contains the **netId** of the network bound to the application. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function setAppNet<sup>9+</sup>(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Binds an application to the specified network. The application can access the external network only through this network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.| | ohos.net.connection | function getDefaultNetSync<sup>9+</sup>(): NetHandle; |Obtains the default active data network in synchronous mode. You can use **getNetCapabilities** to obtain information such as the network type and capabilities.|
...@@ -47,7 +47,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme ...@@ -47,7 +47,7 @@ For the complete list of APIs and example code, see [Network Connection Manageme
| ohos.net.connection | function getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getAllNets(callback: AsyncCallback\<Array\<NetHandle>>): void;| Obtains the list of **NetHandle** objects of the connected network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void; |Obtains link information of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void; |Obtains the capability set of the default network. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function isDefaultNetMetered<sup>9+</sup>(callback: AsyncCallback\<boolean>): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\<void>): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.|
| ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| | ohos.net.connection | function getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.|
......
...@@ -5,7 +5,6 @@ Network management functions include: ...@@ -5,7 +5,6 @@ Network management functions include:
- [HTTP data request](http-request.md): initiates a data request through HTTP. - [HTTP data request](http-request.md): initiates a data request through HTTP.
- [WebSocket connection](websocket-connection.md): establishes a bidirectional connection between the server and client through WebSocket. - [WebSocket connection](websocket-connection.md): establishes a bidirectional connection between the server and client through WebSocket.
- [Socket connection](socket-connection.md): transmits data through Socket. - [Socket connection](socket-connection.md): transmits data through Socket.
- [Network policy management](net-policy-management.md): restricts network capabilities by setting network policies, including cellular network policy, sleep/power-saving mode policy, and background network policy, and resets network policies as needed.
- [Network sharing](net-sharing.md): shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. - [Network sharing](net-sharing.md): shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume.
- [Ethernet connection](net-ethernet.md): provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. - [Ethernet connection](net-ethernet.md): provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
- [Network connection management](net-connection-manager.md): provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. - [Network connection management](net-connection-manager.md): provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
......
# USB Service Development # USB Service Development
## When to Use ## When to Use
In Host mode, you can obtain the list of connected USB devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer. In Host mode, you can obtain the list of connected USB devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
## APIs
## Available APIs
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management. The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usbManager.md). The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usbManager.md).
**Table 1** Open USB APIs **Table 1** Open USB APIs
| API | Description | | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions. | | hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions.|
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. This API uses a promise to return the result. | | requestRight(deviceName: string): Promise&lt;boolean&gt; | Requests the device access permissions for the application. This API uses a promise to return the result. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device list returned by `getDevices()`. | | removeRight(deviceName: string): boolean | Revokes the device access permissions of the application.|
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the list of USB devices connected to the USB host. If no USB device is connected, an empty list is returned. | | connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; | Connects to the USB device based on the device information returned by `getDevices()`. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. | | getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt; | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise\<number> | Performs bulk transfer. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise&lt;number&gt; | Performs bulk transfer. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
| controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise&lt;number&gt; | Performs control transfer. | | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. |
| controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise&lt;number&gt; | Performs control transfer. |
## How to Develop ## How to Develop
You can set a USB device as the USB host to connect to other USB devices for data transfer. The development procedure is as follows: You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows:
1. Obtain the USB device list.
1. Obtain the USB device list.
```js
// Import the USB API package. ```js
import usb from '@ohos.usbManager'; // Import the USB API package.
// Obtain the USB device list. import usb from '@ohos.usbManager';
let deviceList = usb.getDevices(); // Obtain the USB device list.
/* let deviceList = usb.getDevices();
Example deviceList structure /*
[ Example deviceList structure:
{ [
name: "1-1", {
serial: "", name: "1-1",
manufacturerName: "", serial: "",
productName: "", manufacturerName: "",
version: "", productName: "",
vendorId: 7531, version: "",
productId: 2, vendorId: 7531,
clazz: 9, productId: 2,
subClass: 0, clazz: 9,
protocol: 1, subClass: 0,
devAddress: 1, protocol: 1,
busNum: 1, devAddress: 1,
configs: [ busNum: 1,
{ configs: [
id: 1, {
attributes: 224, id: 1,
isRemoteWakeup: true, attributes: 224,
isSelfPowered: true, isRemoteWakeup: true,
maxPower: 0, isSelfPowered: true,
name: "1-1", maxPower: 0,
interfaces: [ name: "1-1",
{ interfaces: [
id: 0, {
protocol: 0, id: 0,
clazz: 9, protocol: 0,
subClass: 0, clazz: 9,
alternateSetting: 0, subClass: 0,
name: "1-1", alternateSetting: 0,
endpoints: [ name: "1-1",
{ endpoints: [
address: 129, {
attributes: 3, address: 129,
interval: 12, attributes: 3,
maxPacketSize: 4, interval: 12,
direction: 128, maxPacketSize: 4,
number: 1, direction: 128,
type: 3, number: 1,
interfaceId: 0, type: 3,
} interfaceId: 0,
] }
} ]
] }
} ]
] }
} ]
] }
*/ ]
``` */
```
2. Obtain the device operation permissions. 2. Obtain the device operation permissions.
```js ```js
let deviceName = deviceList[0].name; let deviceName = deviceList[0].name;
// Request the permissions to operate a specified device. // Request the permissions to operate a specified device.
usb.requestRight(deviceName).then(hasRight => { usb.requestRight(deviceName).then(hasRight => {
console.info("usb device request right result: " + hasRight); console.info("usb device request right result: " + hasRight);
}).catch(error => { }).catch(error => {
console.info("usb device request right failed : " + error); console.info("usb device request right failed : " + error);
}); });
``` ```
3. Open the device. 3. Open the device.
```js ```js
// Open the device, and obtain the USB device pipe for data transfer. // Open the device, and obtain the USB device pipe for data transfer.
let interface1 = deviceList[0].configs[0].interfaces[0]; let pipe = usb.connectDevice(deviceList[0]);
/* let interface1 = deviceList[0].configs[0].interfaces[0];
Claim the corresponding interface from deviceList. /*
interface1 must be one present in the device configuration. Claim the corresponding interface from **deviceList**.
*/ interface1 must be one present in the device configuration.
usb.claimInterface(pipe, interface1, true); */
``` usb.claimInterface(pipe, interface1, true);
```
4. Perform data transfer. 4. Perform data transfer.
```js ```js
/* /*
Read data. Select the corresponding RX endpoint from deviceList for data transfer. Read data. Select the corresponding RX endpoint from deviceList for data transfer.
(endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array. (endpoint.direction == 0x80); dataUint8Array indicates the data to read. The data type is Uint8Array.
*/ */
let inEndpoint = interface1.endpoints[2]; let inEndpoint = interface1.endpoints[2];
let outEndpoint = interface1.endpoints[1]; let outEndpoint = interface1.endpoints[1];
let dataUint8Array = new Uint8Array(1024); let dataUint8Array = new Uint8Array(1024);
usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => { usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
if (dataLength >= 0) { if (dataLength >= 0) {
console.info("usb readData result Length : " + dataLength); console.info("usb readData result Length : " + dataLength);
} else { } else {
console.info("usb readData failed : " + dataLength); console.info("usb readData failed : " + dataLength);
} }
}).catch(error => { }).catch(error => {
console.info("usb readData error : " + JSON.stringify(error)); console.info("usb readData error : " + JSON.stringify(error));
}); });
// Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0) // Send data. Select the corresponding TX endpoint from deviceList for data transfer. (endpoint.direction == 0)
usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => { usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => {
if (dataLength >= 0) { if (dataLength >= 0) {
console.info("usb writeData result write length : " + dataLength); console.info("usb writeData result write length : " + dataLength);
} else { } else {
console.info("writeData failed"); console.info("writeData failed");
} }
}).catch(error => { }).catch(error => {
console.info("usb writeData error : " + JSON.stringify(error)); console.info("usb writeData error : " + JSON.stringify(error));
}); });
``` ```
5. Release the USB interface, and close the USB device. 5. Release the USB interface, and close the USB device.
```js ```js
usb.releaseInterface(pipe, interface); usb.releaseInterface(pipe, interface1);
usb.closePipe(pipe); usb.closePipe(pipe);
``` ```
\ No newline at end of file \ No newline at end of file
...@@ -111,7 +111,7 @@ The [i18n](../reference/apis/js-apis-i18n.md) module provides enhanced I18N capa ...@@ -111,7 +111,7 @@ The [i18n](../reference/apis/js-apis-i18n.md) module provides enhanced I18N capa
let dateTimeFormat = new Intl.DateTimeFormat(); let dateTimeFormat = new Intl.DateTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions9). Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions6).
```js ```js
let options = {dateStyle: "full", timeStyle: "full"}; let options = {dateStyle: "full", timeStyle: "full"};
...@@ -181,7 +181,7 @@ The [i18n](../reference/apis/js-apis-i18n.md) module provides enhanced I18N capa ...@@ -181,7 +181,7 @@ The [i18n](../reference/apis/js-apis-i18n.md) module provides enhanced I18N capa
let numberFormat = new Intl.NumberFormat(); let numberFormat = new Intl.NumberFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions9). Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions6).
```js ```js
let options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
...@@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll ...@@ -240,7 +240,7 @@ Users in different regions have different requirements for string sorting. [Coll
let collator = new Intl.Collator(); let collator = new Intl.Collator();
``` ```
Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8).
The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'.
```js ```js
...@@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -301,7 +301,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let pluralRules = new Intl.PluralRules(); let pluralRules = new Intl.PluralRules();
``` ```
Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8).
```js ```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
...@@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -349,7 +349,7 @@ According to grammars in certain languages, the singular or plural form of a nou
let relativeTimeFormat = new Intl.RelativeTimeFormat(); let relativeTimeFormat = new Intl.RelativeTimeFormat();
``` ```
Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8).
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
...@@ -384,4 +384,4 @@ According to grammars in certain languages, the singular or plural form of a nou ...@@ -384,4 +384,4 @@ According to grammars in certain languages, the singular or plural form of a nou
```js ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"} let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"}
``` ```
\ No newline at end of file
# Enabling Notification # Enabling Notification
To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time. To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationmanagerrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time.
**Figure 1** Dialog box prompting the user to enable notification **Figure 1** Dialog box prompting the user to enable notification
![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png) ![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png)
- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled. - Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled.
- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows. - The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationmanagerrequestenablenotification) is called later. The user can manually enable notification as follows.
| 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. | | 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) | | ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) |
...@@ -19,7 +19,7 @@ To publish a notification, you must have notification enabled for your applicati ...@@ -19,7 +19,7 @@ To publish a notification, you must have notification enabled for your applicati
## Available APIs ## Available APIs
For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification). For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationmanagerrequestenablenotification).
**Table 1** Notification APIs **Table 1** Notification APIs
......
...@@ -24,4 +24,5 @@ A notification is generated by the notification sender and sent to the notificat ...@@ -24,4 +24,5 @@ A notification is generated by the notification sender and sent to the notificat
System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database. System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database.
**Figure 1** Notification service process
![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png) ![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png)
...@@ -16,19 +16,19 @@ The major APIs for notification subscription are described as follows. For detai ...@@ -16,19 +16,19 @@ The major APIs for notification subscription are described as follows. For detai
| Name | Description| | Name | Description|
| -------- | -------- | | -------- | -------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from a specific application.| | subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from a specific application.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from all applications. | | subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback&lt;void&gt;): void | Subscribes to notifications from all applications. |
**Table 2** Callbacks for notification subscription **Table 2** Callbacks for notification subscription
| Name | Description| | Name | Description|
| -------- | -------- | | -------- | -------- |
| onConsume?:(data: SubscribeCallbackData) =&gt; void | Callback for receiving notifications. | | onConsume?:(data: SubscribeCallbackData) =&gt; void | Callback for receiving notifications. |
| onCancel?:(data: SubscribeCallbackData) =&gt; void | Callback for canceling notifications. | | onCancel?:(data: SubscribeCallbackData) =&gt; void | Callback for canceling notifications. |
| onUpdate?:(data: NotificationSortingMap) =&gt; void | Callback for notification sorting updates. | | onUpdate?:(data: NotificationSortingMap) =&gt; void | Callback for notification sorting updates. |
| onConnect?:() =&gt; void; | Callback for subscription. | | onConnect?:() =&gt; void; | Callback for subscription. |
| onDisconnect?:() =&gt; void; | Callback for unsubscription. | | onDisconnect?:() =&gt; void; | Callback for unsubscription. |
| onDestroy?:() =&gt; void | Callback for disconnecting from the notification subsystem. | | onDestroy?:() =&gt; void | Callback for disconnecting from the notification subsystem. |
| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) =&gt; void | Callback for the Do Not Disturb (DNT) time changes.| | onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) =&gt; void | Callback for the Do Not Disturb (DNT) time changes.|
| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) =&gt; void | Callback for notification switch changes. | | onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) =&gt; void | Callback for notification switch changes. |
...@@ -46,37 +46,38 @@ The major APIs for notification subscription are described as follows. For detai ...@@ -46,37 +46,38 @@ The major APIs for notification subscription are described as follows. For detai
```ts ```ts
let subscriber = { let subscriber = {
onConsume: function (data) { onConsume: function (data) {
let req = data.request; let req = data.request;
console.info('[ANS] onConsume callback req.id: ' + req.id); console.info(`onConsume callback. req.id: ${req.id}`);
}, },
onCancel: function (data) { onCancel: function (data) {
let req = data.request; let req = data.request;
console.info('[ANS] onCancel callback req.id: : ' + req.id); console.info(`onCancel callback. req.id: ${req.id}`);
}, },
onUpdate: function (data) { onUpdate: function (data) {
console.info('[ANS] onUpdate in test'); let req = data.request;
}, console.info(`onUpdate callback. req.id: ${req.id}`);
onConnect: function () { },
console.info('[ANS] onConnect in test'); onConnect: function () {
}, console.info(`onConnect callback.}`);
onDisconnect: function () { },
console.info('[ANS] onDisConnect in test'); onDisconnect: function () {
}, console.info(`onDisconnect callback.}`);
onDestroy: function () { },
console.info('[ANS] onDestroy in test'); onDestroy: function () {
}, console.info(`onDestroy callback.}`);
},
}; };
``` ```
4. Initiate notification subscription. 4. Initiate notification subscription.
```ts ```ts
notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
if (err) { if (err) {
console.error(`[ANS] subscribe failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to subscribe notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] subscribeTest success : + ${data}`); console.info(`Succeeded in subscribing to notification. Data: ${data}`);
}); });
``` ```
...@@ -4,7 +4,7 @@ A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsu ...@@ -4,7 +4,7 @@ A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsu
Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered. Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered.
**Figure 1** Publishing a notification with a WantAgent object **Figure 1** Publishing a notification with a WantAgent object
![notification-with-wantagent](figures/notification-with-wantagent.png) ![notification-with-wantagent](figures/notification-with-wantagent.png)
...@@ -15,11 +15,11 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -15,11 +15,11 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
|getWantAgent(info: WantAgentInfo, callback: AsyncCallback&lt;WantAgent&gt;): void | Creates a **WantAgent** object.| | getWantAgent(info: WantAgentInfo, callback: AsyncCallback&lt;WantAgent&gt;): void | Creates a **WantAgent** object.|
|trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback&lt;CompleteData&gt;): void | Triggers a **WantAgent** object.| | trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback&lt;CompleteData&gt;): void | Triggers a **WantAgent** object.|
|cancel(agent: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Cancels a **WantAgent** object.| | cancel(agent: WantAgent, callback: AsyncCallback&lt;void&gt;): void | Cancels a **WantAgent** object.|
|getWant(agent: WantAgent, callback: AsyncCallback&lt;Want&gt;): void | Obtains a **WantAgent** object.| | getWant(agent: WantAgent, callback: AsyncCallback&lt;Want&gt;): void | Obtains a **WantAgent** object.|
|equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether two **WantAgent** objects are equal.| | equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether two **WantAgent** objects are equal.|
## How to Develop ## How to Develop
...@@ -42,20 +42,20 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -42,20 +42,20 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
// Set the action type through operationType of WantAgentInfo. // Set the action type through operationType of WantAgentInfo.
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
deviceId: '', deviceId: '',
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
abilityName: 'EntryAbility', abilityName: 'EntryAbility',
action: '', action: '',
entities: [], entities: [],
uri: '', uri: '',
parameters: {} parameters: {}
} }
], ],
operationType: wantAgent.OperationType.START_ABILITY, operationType: wantAgent.OperationType.START_ABILITY,
requestCode: 0, requestCode: 0,
wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
}; };
``` ```
...@@ -66,16 +66,16 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -66,16 +66,16 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
// Set the action type through operationType of WantAgentInfo. // Set the action type through operationType of WantAgentInfo.
let wantAgentInfo = { let wantAgentInfo = {
wants: [ wants: [
{ {
action: 'event_name', // Set the action name. action: 'event_name', // Set the action name.
parameters: {}, parameters: {},
} }
], ],
operationType: wantAgent.OperationType.SEND_COMMON_EVENT, operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
requestCode: 0, requestCode: 0,
wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
} };
``` ```
4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object. 4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object.
...@@ -83,12 +83,12 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -83,12 +83,12 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
```typescript ```typescript
// Create a WantAgent object. // Create a WantAgent object.
wantAgent.getWantAgent(wantAgentInfo, (err, data) => { wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
if (err) { if (err) {
console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err)); console.error(`Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info('[WantAgent]getWantAgent success'); console.info('Succeeded in geting want agent.');
wantAgentObj = data; wantAgentObj = data;
}); });
``` ```
...@@ -97,25 +97,25 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/ ...@@ -97,25 +97,25 @@ For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/
```typescript ```typescript
// Create a NotificationRequest object. // Create a NotificationRequest object.
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: { normal: {
title: 'Test_Title', title: 'Test_Title',
text: 'Test_Text', text: 'Test_Text',
additionalText: 'Test_AdditionalText', additionalText: 'Test_AdditionalText',
},
}, },
id: 1, },
label: 'TEST', id: 1,
wantAgent: wantAgentObj, label: 'TEST',
wantAgent: wantAgentObj,
} }
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info('Succeeded in publishing notification.');
}); });
``` ```
......
...@@ -27,13 +27,14 @@ In the [NotificationTemplate](../reference/apis/js-apis-inner-notification-notif ...@@ -27,13 +27,14 @@ In the [NotificationTemplate](../reference/apis/js-apis-inner-notification-notif
```ts ```ts
notificationManager.isSupportTemplate('downloadTemplate').then((data) => { notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
console.info(`[ANS] isSupportTemplate success`); console.info(`[ANS] isSupportTemplate success`);
console.info('Succeeded in supporting download template notification.');
let isSupportTpl: boolean = data; // The value true means that the template of the downloadTemplate type is supported, and false means the opposite. let isSupportTpl: boolean = data; // The value true means that the template of the downloadTemplate type is supported, and false means the opposite.
// ... // ...
}).catch((err) => { }).catch((err) => {
console.error(`[ANS] isSupportTemplate failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to support download template notification. Code is ${err.code}, message is ${err.message}`);
}); });
``` ```
> **NOTE** > **NOTE**
> >
> Proceed with the step below only when the specified template is supported. > Proceed with the step below only when the specified template is supported.
...@@ -61,9 +62,9 @@ In the [NotificationTemplate](../reference/apis/js-apis-inner-notification-notif ...@@ -61,9 +62,9 @@ In the [NotificationTemplate](../reference/apis/js-apis-inner-notification-notif
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success `); console.info('Succeeded in publishing notification.');
}); });
``` ```
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached. You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached.
**Table 1** Basic notification content types
**Table 1** Basic notification content types
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
...@@ -13,16 +12,16 @@ You can publish basic notifications to send SMS messages, prompt messages, and a ...@@ -13,16 +12,16 @@ You can publish basic notifications to send SMS messages, prompt messages, and a
| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| | NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.|
| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.| | NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.|
Notifications are displayed in the notification panel, which is the only supported subscriber to notifications. Below you can see two examples of the basic notification.
Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification. **Figure 1** Examples of the basic notification
**Figure 1** Examples of the basic notification
![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png) ![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png)
## Available APIs ## Available APIs
The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs. The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-inner-notification-notificationRequest.md#notificationrequest) parameter in the APIs.
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
...@@ -48,21 +47,21 @@ The following table describes the APIs for notification publishing. You specify ...@@ -48,21 +47,21 @@ The following table describes the APIs for notification publishing. You specify
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification
normal: { normal: {
title: 'test_title', title: 'test_title',
text: 'test_text', text: 'test_text',
additionalText: 'test_additionalText', additionalText: 'test_additionalText',
} }
} }
} };
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success.`); console.info('Succeeded in publishing notification.');
}); });
``` ```
...@@ -74,25 +73,25 @@ The following table describes the APIs for notification publishing. You specify ...@@ -74,25 +73,25 @@ The following table describes the APIs for notification publishing. You specify
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification
longText: { longText: {
title: 'test_title', title: 'test_title',
text: 'test_text', text: 'test_text',
additionalText: 'test_additionalText', additionalText: 'test_additionalText',
longText: 'test_longText', longText: 'test_longText',
briefText: 'test_briefText', briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle', expandedTitle: 'test_expandedTitle',
} }
} }
} };
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success.`); console.info('Succeeded in publishing notification.');
}); });
``` ```
...@@ -104,24 +103,24 @@ The following table describes the APIs for notification publishing. You specify ...@@ -104,24 +103,24 @@ The following table describes the APIs for notification publishing. You specify
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification
multiLine: { multiLine: {
title: 'test_title', title: 'test_title',
text: 'test_text', text: 'test_text',
briefText: 'test_briefText', briefText: 'test_briefText',
longTitle: 'test_longTitle', longTitle: 'test_longTitle',
lines: ['line_01', 'line_02', 'line_03', 'line_04'], lines: ['line_01', 'line_02', 'line_03', 'line_04'],
} }
} }
} };
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success`); console.info('Succeeded in publishing notification.');
}); });
``` ```
...@@ -132,27 +131,27 @@ The following table describes the APIs for notification publishing. You specify ...@@ -132,27 +131,27 @@ The following table describes the APIs for notification publishing. You specify
```ts ```ts
let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information. let imagePixelMap: PixelMap = undefined; // Obtain the PixelMap information.
let notificationRequest: notificationManager.NotificationRequest = { let notificationRequest: notificationManager.NotificationRequest = {
id: 1, id: 1,
content: { content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE, contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
picture: { picture: {
title: 'test_title', title: 'test_title',
text: 'test_text', text: 'test_text',
additionalText: 'test_additionalText', additionalText: 'test_additionalText',
briefText: 'test_briefText', briefText: 'test_briefText',
expandedTitle: 'test_expandedTitle', expandedTitle: 'test_expandedTitle',
picture: imagePixelMap picture: imagePixelMap
}
} }
} }
};
// Publish the notification. // Publish the notification.
notificationManager.publish(notificationRequest, (err) => { notificationManager.publish(notificationRequest, (err) => {
if (err) { if (err) {
console.error(`[ANS] publish failed, code is ${err.code}, message is ${err.message}`); console.error(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return; return;
} }
console.info(`[ANS] publish success.`); console.info('Succeeded in publishing notification.');
}); });
``` ```
......
# Using Native APIs (NDK) of the OHOS SDK in a CMake Project
## What Is Native API
For details, see [Native APIs](https://gitee.com/openharmony/docs/blob/master/en/application-dev/napi/Readme-EN.md).
## Downloading the NDK
You download the Native API Development Kit (NDK) by downloading the OHOS SDK, where the NDK is included. To download the OHOS SDK, use any of the following modes:
- (Recommended) Acquire source code from mirrors for an officially released version. For details, see [release notes](https://gitee.com/openharmony/docs/tree/master/en/release-notes#/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.2-release.md).
- Download the SDK from the SDK Manager in DevEco Studio.
- Download the SDK from the [daily build](http://ci.openharmony.cn/dailys/dailybuilds), by clicking the download link to the ohos-sdk component.
![Download from Daily Build](figures/ci_download.png)
## Decompressing the NDK
Place the downloaded NDK in a folder you prefer and decompress it. Below shows the directory structure after decompression.
![SDK Directory Structure](figures/sdk-structure.png)
Configure the Linux environment as follows: (Skip this step if the NDK is downloaded from DevEco Studio.)
1. Add the CMake tool that comes with the NDK to the environment variables.
```
# Open the .bashrc file.
vim ~/.bashrc
# Append the custom CMake path to the file. Save the file and exit.
export PATH=~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin:$PATH
# Run the source ~/.bashrc command to make the environment variables take effect.
source ~/.bashrc
```
2. Check the default CMake path.
```
# Run the which cmake command.
which cmake
# The result should be the same as the custom path previously appended to the file.
~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin/cmake
```
## Using the NDK to Compile a Native Program
You can use the NDK to quickly develop a native program, including native dynamic libraries, static libraries, and executable files. The ArkUI application framework can call the native dynamic libraries through the NAPI framework. The following exemplifies how to use the NDK to compile a C/C++ dynamic library in a C/C++ demo project.
### Folders in the NDK
#### build Folder: ohos.toolchain.cmake file
The **ohos.toolchain.cmake** file contains the attributes of the CMake compilation target. Its path must be specified in the **CMAKE_TOOLCHAIN_FILE** parameter so that it can be located during CMake compilation. For details about the mandatory parameters in the **ohos.toolchain.cmake** file, see [Key Parameters in ohos.toolchain.cmake](#key-parameters-in-ohostoolchaincmake).
#### build-tools folder: Build Tool Provided by the NDK
```
# Run the following command to view the CMake version:
cmake -version
# Result
cmake version 3.16.5
CMake suite maintained and supported by Kitware (kitware.com/cmake).
```
#### llvm Folder: Compiler Provided by the NDK
![Compiler](figures/compiler.png)
### Demo Project for the NDK
#### Demo Project Directory
demo
├── CMakeLists.txt
├── include
└── sum.h
└── src
├── CMakeLists.txt
├── sum.cpp
└── hello.cpp
#### CMakeLists.txt in the demo Directory
```
# Specify the minimum CMake version.
CMAKE_MINIMUM_REQUIRED(VERSION 3.16)
# Set the project name, which is HELLO in this example.
PROJECT(HELLO)
# Add a subdirectory and build the subdirectory.
ADD_SUBDIRECTORY(src bin)
```
#### CMakeLists.txt in the src Directory
```
SET(LIBHELLO_SRC hello.cpp)
# Set compilation flags.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")
# Set the link parameter. The value below is only for exemplary purposes.
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--emit-relocs --verbose")
# Add a libsum dynamic library target. If the compilation is successful, a libsum.so file is generated.
ADD_LIBRARY(sum SHARED sum.cpp)
# Add the executable target called Hello. If the compilation is successful, a Hello executable is generated.
ADD_EXECUTABLE(Hello ${LIBHELLO_SRC})
# Specify the path to the include directory of the Hello target.
TARGET_INCLUDE_DIRECTORIES(Hello PUBLIC ../include)
# Specify the name of the library to be linked to the Hello target.
TARGET_LINK_LIBRARIES(Hello PUBLIC sum)
```
For details about CMake, see [CMake Tutorial](https://cmake.org/cmake/help/v3.16/guide/tutorial/).
#### Source Code
**hello.cpp** source code:
```
#include <iostream>
#include "sum.h"
int main(int argc,const char **argv)
{
std::cout<< "hello world!" <<std::endl;
int total = sum(1, 100);
std::cout<< "Sum 1 + 100=" << total << std::endl;
return 0;
}
```
**sum.h** source code:
```
int sum(int a, int b);
```
sum.cpp source code:
```
#include <iostream>
int sum(int a, int b)
{
return a + b;
}
```
### Key Parameters in ohos.toolchain.cmake
| Parameter | Type|Description|
|--------|------|------|
|OHOS_STL|c++\_shared/c++\_static|STL to use. The value must be consistent across the native libraries in the same application.<br>**c++\_shared** (default): The shared library of libc++, libc++\_shared.so, is used.<br>**c++\static**: The static library of libc++, libc++\_static.a, is used.|
|OHOS_ARCH|armeabi-v7a/arm64-v8a/x86_64|ABI to support. Currently, three types of ABI are supported.|
|OHOS_PLATFORM|OHOS|Target platform. Currently, only OHOS is supported.|
|CMAKE_TOOLCHAIN_FILE|Toolchain file|CMake toolchain file, that is, the aforementioned **ohos.toolchain.cmake** file.|
### Building from Command Line
In the project directory, create the **build** directory to store the intermediate files generated during CMake building.
> **NOTE**
>
> In the following commands, **ohos-sdk** is the root directory of the downloaded SDK. Replace it with the actual directory.
1. Use **OHOS_STL=c++_shared** for dynamic compilation.
```
>mkdir build && cd build
>cmake -DOHOS_STL=c++_shared -DOHOS_ARCH=armeabi-v7a -DOHOS_PLATFORM=OHOS -DCMAKE_TOOLCHAIN_FILE={ohos-sdk}/linux/native/build/cmake/ohos.toolchain.cmake ..
>cmake --build .
```
2. Use **OHOS_STL=c++_static** for static compilation.
```
>mkdir build && cd build
>cmake -DOHOS_STL=c++_static -DOHOS_ARCH=armeabi-v7a -DOHOS_PLATFORM=OHOS -DCMAKE_TOOLCHAIN_FILE={ohos-sdk}/linux/native/build/cmake/ohos.toolchain.cmake ..
>cmake --build .
```
<!--no_check-->
\ No newline at end of file
...@@ -120,6 +120,7 @@ ...@@ -120,6 +120,7 @@
- [@ohos.events.emitter (Emitter)](js-apis-emitter.md) - [@ohos.events.emitter (Emitter)](js-apis-emitter.md)
- [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md) - [@ohos.notificationManager (NotificationManager) (Recommended)](js-apis-notificationManager.md)
- [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md) - [@ohos.notificationSubscribe (NotificationSubscribe) (Recommended)](js-apis-notificationSubscribe.md)
- [@ohos.application.StaticSubscriberExtensionContext (NotificationSubscribe) (Recommended)](js-apis-application-StaticSubscriberExtensionContext.md)
- [System Common Events (To Be Deprecated Soon)](commonEvent-definitions.md) - [System Common Events (To Be Deprecated Soon)](commonEvent-definitions.md)
- [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.commonEvent (Common Event) (To Be Deprecated Soon)](js-apis-commonEvent.md)
- [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md) - [@ohos.notification (Notification) (To Be Deprecated Soon)](js-apis-notification.md)
...@@ -137,6 +138,10 @@ ...@@ -137,6 +138,10 @@
- [NotificationFlags](js-apis-inner-notification-notificationFlags.md) - [NotificationFlags](js-apis-inner-notification-notificationFlags.md)
- [NotificationRequest](js-apis-inner-notification-notificationRequest.md) - [NotificationRequest](js-apis-inner-notification-notificationRequest.md)
- [NotificationSlot](js-apis-inner-notification-notificationSlot.md) - [NotificationSlot](js-apis-inner-notification-notificationSlot.md)
- [NotificationSorting](js-apis-inner-notification-notificationSorting.md)
- [NotificationSortingMap](js-apis-inner-notification-notificationSortingMap.md)
- [NotificationSubscribeInfo](js-apis-inner-notification-notificationSubscribeInfo.md)
- [NotificationSubscriber](js-apis-inner-notification-notificationSubscriber.md)
- [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md) - [NotificationTemplate](js-apis-inner-notification-notificationTemplate.md)
- [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md) - [NotificationUserInput](js-apis-inner-notification-notificationUserInput.md)
- Common Events - Common Events
...@@ -320,7 +325,7 @@ ...@@ -320,7 +325,7 @@
- [@ohos.systemTimer (System Timer)](js-apis-system-timer.md) - [@ohos.systemTimer (System Timer)](js-apis-system-timer.md)
- [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md) - [@ohos.wallpaper (Wallpaper)](js-apis-wallpaper.md)
- [@ohos.web.webview (Webview)](js-apis-webview.md) - [@ohos.web.webview (Webview)](js-apis-webview.md)
- [console (Log)](js-apis-logs.md) - [Console](js-apis-logs.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- application - application
- [AccessibilityExtensionContext (Accessibility Extension Context)](js-apis-inner-application-accessibilityExtensionContext.md) - [AccessibilityExtensionContext (Accessibility Extension Context)](js-apis-inner-application-accessibilityExtensionContext.md)
...@@ -330,6 +335,7 @@ ...@@ -330,6 +335,7 @@
- [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md) - [@ohos.batteryStatistics (Battery Statistics)](js-apis-batteryStatistics.md)
- [@ohos.brightness (Screen Brightness)](js-apis-brightness.md) - [@ohos.brightness (Screen Brightness)](js-apis-brightness.md)
- [@ohos.charger (Charging Type)](js-apis-charger.md) - [@ohos.charger (Charging Type)](js-apis-charger.md)
- [@ohos.cooperate (Screen Hopping)](js-apis-devicestatus-cooperate.md)
- [@ohos.deviceInfo (Device Information)](js-apis-device-info.md) - [@ohos.deviceInfo (Device Information)](js-apis-device-info.md)
- [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md) - [@ohos.distributedHardware.deviceManager (Device Management)](js-apis-device-manager.md)
- [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md) - [@ohos.geoLocationManager (Geolocation Manager)](js-apis-geoLocationManager.md)
...@@ -344,6 +350,7 @@ ...@@ -344,6 +350,7 @@
- [@ohos.multimodalInput.mouseEvent (Mouse Event)](js-apis-mouseevent.md) - [@ohos.multimodalInput.mouseEvent (Mouse Event)](js-apis-mouseevent.md)
- [@ohos.multimodalInput.pointer (Mouse Pointer)](js-apis-pointer.md) - [@ohos.multimodalInput.pointer (Mouse Pointer)](js-apis-pointer.md)
- [@ohos.multimodalInput.touchEvent (Touch Event)](js-apis-touchevent.md) - [@ohos.multimodalInput.touchEvent (Touch Event)](js-apis-touchevent.md)
- [@ohos.multimodalInput.shortKey (Shortcut Key)](js-apis-shortKey.md)
- [@ohos.power (System Power Management)](js-apis-power.md) - [@ohos.power (System Power Management)](js-apis-power.md)
- [@ohos.runningLock (Runninglock)](js-apis-runninglock.md) - [@ohos.runningLock (Runninglock)](js-apis-runninglock.md)
- [@ohos.sensor (Sensor)](js-apis-sensor.md) - [@ohos.sensor (Sensor)](js-apis-sensor.md)
...@@ -365,6 +372,7 @@ ...@@ -365,6 +372,7 @@
- [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md) - [@ohos.configPolicy (Configuration Policy)](js-apis-configPolicy.md)
- [@ohos.enterprise.accountManager (Account Management)](js-apis-enterprise-accountManager.md) - [@ohos.enterprise.accountManager (Account Management)](js-apis-enterprise-accountManager.md)
- [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md) - [@ohos.enterprise.adminManager (Enterprise Device Management)](js-apis-enterprise-adminManager.md)
- [@ohos.enterprise.applicationManager (Application Management)](js-apis-enterprise-applicationManager.md)
- [@ohos.enterprise.bundleManager (Bundle Management)](js-apis-enterprise-bundleManager.md) - [@ohos.enterprise.bundleManager (Bundle Management)](js-apis-enterprise-bundleManager.md)
- [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md) - [@ohos.enterprise.dateTimeManager (System Time Management)](js-apis-enterprise-dateTimeManager.md)
- [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md) - [@ohos.enterprise.deviceControl (Device Control Management)](js-apis-enterprise-deviceControl.md)
......
...@@ -904,7 +904,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ...@@ -904,7 +904,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => {
> This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead. > This API is deprecated since API version 9. You are advised to use [bundleManager.getAllApplicationInfo](js-apis-bundleManager.md#bundlemanagergetallapplicationinfo) instead.
getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback<Array\<ApplicationInfo>>) : void; getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback\<Array\<ApplicationInfo\>\>): void;
Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result. Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result.
......
...@@ -25,7 +25,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -25,7 +25,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
onAddForm(want: Want): formBindingData.FormBindingData onAddForm(want: Want): formBindingData.FormBindingData
Called to notify the widget provider that a **Form** instance (widget) has been created. Called to notify the widget provider that a **Form** instance (widget) is being created.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -49,7 +49,7 @@ import formBindingData from '@ohos.app.form.formBindingData'; ...@@ -49,7 +49,7 @@ import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) { onAddForm(want) {
console.log('FormExtensionAbility onAddForm, want: ${want.abilityName}'); console.log(`FormExtensionAbility onAddForm, want: ${want.abilityName}`);
let dataObj1 = { let dataObj1 = {
temperature: '11c', temperature: '11c',
'time': '11:00' 'time': '11:00'
...@@ -64,7 +64,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -64,7 +64,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId: string): void onCastToNormalForm(formId: string): void
Called to notify the widget provider that a temporary widget has been converted to a normal one. Called to notify the widget provider that a temporary widget is being converted to a normal one.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -81,7 +81,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -81,7 +81,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId) { onCastToNormalForm(formId) {
console.log('FormExtensionAbility onCastToNormalForm, formId: ${formId}'); console.log(`FormExtensionAbility onCastToNormalForm, formId: ${formId}`);
} }
}; };
``` ```
...@@ -90,7 +90,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -90,7 +90,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId: string): void onUpdateForm(formId: string): void
Called to notify the widget provider that a widget has been updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data. Called to notify the widget provider that a widget is being updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -109,15 +109,15 @@ import formProvider from '@ohos.app.form.formProvider'; ...@@ -109,15 +109,15 @@ import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId) { onUpdateForm(formId) {
console.log('FormExtensionAbility onUpdateForm, formId: ${formId}'); console.log(`FormExtensionAbility onUpdateForm, formId: ${formId}`);
let obj2 = formBindingData.createFormBindingData({ let obj2 = formBindingData.createFormBindingData({
temperature: '22c', temperature: '22c',
time: '22:00' time: '22:00'
}); });
formProvider.updateForm(formId, obj2).then((data) => { formProvider.updateForm(formId, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data: ${data}'); console.log(`FormExtensionAbility context updateForm, data: ${data}`);
}).catch((error) => { }).catch((error) => {
console.error('Operation updateForm failed. Cause: ${error}'); console.error(`Operation updateForm failed. Cause: ${error}`);
}); });
} }
}; };
...@@ -127,7 +127,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -127,7 +127,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus: { [key: string]: number }): void onChangeFormVisibility(newStatus: { [key: string]: number }): void
Called to notify the widget provider of the change of visibility. Called to notify the widget provider that the widget visibility status is being changed.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -146,18 +146,18 @@ import formProvider from '@ohos.app.form.formProvider'; ...@@ -146,18 +146,18 @@ import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus) { onChangeFormVisibility(newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}'); console.log(`FormExtensionAbility onChangeFormVisibility, newStatus: ${newStatus}`);
let obj2 = formBindingData.createFormBindingData({ let obj2 = formBindingData.createFormBindingData({
temperature: '22c', temperature: '22c',
time: '22:00' time: '22:00'
}); });
for (let key in newStatus) { for (let key in newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}'); console.log(`FormExtensionAbility onChangeFormVisibility, key: ${key}, value= ${newStatus[key]}`);
formProvider.updateForm(key, obj2).then((data) => { formProvider.updateForm(key, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data: ${data}'); console.log(`FormExtensionAbility context updateForm, data: ${data}`);
}).catch((error) => { }).catch((error) => {
console.error('Operation updateForm failed. Cause: ${error}'); console.error(`Operation updateForm failed. Cause: ${error}`);
}); });
} }
} }
...@@ -168,7 +168,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -168,7 +168,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId: string, message: string): void onFormEvent(formId: string, message: string): void
Called to instruct the widget provider to receive and process the widget event. Called to instruct the widget provider to process the widget event.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -186,7 +186,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -186,7 +186,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) { onFormEvent(formId, message) {
console.log('FormExtensionAbility onFormEvent, formId: ${formId}, message: ${message}'); console.log(`FormExtensionAbility onFormEvent, formId: ${formId}, message: ${message}`);
} }
}; };
``` ```
...@@ -195,7 +195,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -195,7 +195,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId: string): void onRemoveForm(formId: string): void
Called to notify the widget provider that a **Form** instance (widget) has been destroyed. Called to notify the widget provider that a **Form** instance (widget) is being destroyed.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -212,7 +212,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -212,7 +212,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId) { onRemoveForm(formId) {
console.log('FormExtensionAbility onRemoveForm, formId: ${formId}'); console.log(`FormExtensionAbility onRemoveForm, formId: ${formId}`);
} }
}; };
``` ```
...@@ -221,7 +221,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -221,7 +221,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(newConfig: Configuration): void; onConfigurationUpdate(newConfig: Configuration): void;
Called when the configuration of the environment where the ability is running is updated. Called when the configuration of the environment where the FormExtensionAbility is running is updated.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -238,7 +238,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -238,7 +238,7 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(config) { onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config: ${JSON.stringify(config)}'); console.log(`onConfigurationUpdate, config: ${JSON.stringify(config)}`);
} }
}; };
``` ```
...@@ -247,7 +247,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -247,7 +247,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState?(want: Want): formInfo.FormState; onAcquireFormState?(want: Want): formInfo.FormState;
Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. Called to notify the widget provider that the widget host is requesting the widget state. By default, the initial state is returned.
**System capability**: SystemCapability.Ability.Form **System capability**: SystemCapability.Ability.Form
...@@ -265,7 +265,7 @@ import formInfo from '@ohos.app.form.formInfo'; ...@@ -265,7 +265,7 @@ import formInfo from '@ohos.app.form.formInfo';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState(want) { onAcquireFormState(want) {
console.log('FormExtensionAbility onAcquireFormState, want: ${want}'); console.log(`FormExtensionAbility onAcquireFormState, want: ${want}`);
return formInfo.FormState.UNKNOWN; return formInfo.FormState.UNKNOWN;
} }
}; };
...@@ -275,7 +275,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility { ...@@ -275,7 +275,7 @@ export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm?(formId: string): { [key: string]: Object } onShareForm?(formId: string): { [key: string]: Object }
Called by the widget provider to receive shared widget data. Called to notify the widget provider that the widget host is sharing the widget data.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -300,7 +300,46 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; ...@@ -300,7 +300,46 @@ import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm(formId) { onShareForm(formId) {
console.log('FormExtensionAbility onShareForm, formId: ${formId}'); console.log(`FormExtensionAbility onShareForm, formId: ${formId}`);
let wantParams = {
'temperature': '20',
'time': '2022-8-8 09:59',
};
return wantParams;
}
};
```
## onAcquireFormData<sup>10+</sup>
onAcquireFormData?(formId: string): { [key: string]: Object }
Called to notify the widget provider that the widget host is requesting the custom data.
**System API**: This is a system API.
**System capability**: SystemCapability.Ability.Form
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| formId | string | Yes | Widget ID.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ----------------------------------------------------------- |
| {[key: string]: any} | Custom data of the widget, in the form of key-value pairs.|
**Example**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormData(formId) {
console.log('FormExtensionAbility onAcquireFormData, formId: ${formId}');
let wantParams = { let wantParams = {
'temperature': '20', 'temperature': '20',
'time': '2022-8-8 09:59', 'time': '2022-8-8 09:59',
......
...@@ -2222,7 +2222,7 @@ try { ...@@ -2222,7 +2222,7 @@ try {
## getRunningFormInfosByFilter<sup>10+</sup> ## getRunningFormInfosByFilter<sup>10+</sup>
function getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise&lt;Array&lt;formInfo.RunningFormInfo&gt;&gt; getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter): Promise&lt;Array&lt;formInfo.RunningFormInfo&gt;&gt;
Obtains the information about widget hosts based on the widget provider information. This API uses a promise to return the result. Obtains the information about widget hosts based on the widget provider information. This API uses a promise to return the result.
...@@ -2273,7 +2273,7 @@ try { ...@@ -2273,7 +2273,7 @@ try {
## getRunningFormInfosByFilter<sup>10+</sup> ## getRunningFormInfosByFilter<sup>10+</sup>
function getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void getRunningFormInfosByFilter(formProviderFilter: formInfo.FormProviderFilter, callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void
Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result. Obtains the information about widget hosts based on the widget provider information. This API uses an asynchronous callback to return the result.
...@@ -2321,7 +2321,7 @@ try { ...@@ -2321,7 +2321,7 @@ try {
## getRunningFormInfoById<sup>10+</sup> ## getRunningFormInfoById<sup>10+</sup>
function getRunningFormInfoById(formId: string): Promise&lt;Array&lt;formInfo.RunningFormInfo&gt;&gt; getRunningFormInfoById(formId: string): Promise&lt;Array&lt;formInfo.RunningFormInfo&gt;&gt;
Obtains the information about widget hosts based on the widget ID. This API uses a promise to return the result. Obtains the information about widget hosts based on the widget ID. This API uses a promise to return the result.
...@@ -2366,7 +2366,7 @@ try { ...@@ -2366,7 +2366,7 @@ try {
## getRunningFormInfoById<sup>10+</sup> ## getRunningFormInfoById<sup>10+</sup>
function getRunningFormInfoById(formId: string, callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void getRunningFormInfoById(formId: string, callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): void
Obtains the information about widget hosts based on the widget ID. This API uses an asynchronous callback to return the result. Obtains the information about widget hosts based on the widget ID. This API uses an asynchronous callback to return the result.
......
# @ohos.application.StaticSubscriberExtensionContext (StaticSubscriberExtensionContext)
The **StaticSubscriberExtensionContext** module, inherited from **ExtensionContext**, provides context for StaticSubscriberExtensionAbilities.
You can use the APIs of this module to start StaticSubscriberExtensionAbilities.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Usage
Before using the **StaticSubscriberExtensionContext** module, you must first obtain a **StaticSubscriberExtensionAbility** instance.
```ts
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'
export default class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility {
context = this.context;
};
```
## StaticSubscriberExtensionContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability that belongs to the same application as this StaticSubscriberExtensionAbility. This API uses an asynchronous callback to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------- | ---- | -------------------------- |
| want | [Want](js-apis-application-want.md) | Yes | Want information about the target ability. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
| 16300003 | The target application is not self application. |
**Example**
```ts
let want = {
bundleName: "com.example.myapp",
abilityName: "MyAbility"
};
try {
this.context.startAbility(want, (error) => {
if (error) {
// Process service logic errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
return;
}
// Carry out normal service processing.
console.log('startAbility succeed');
});
} catch (paramError) {
// Process input parameter errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
## StaticSubscriberExtensionContext.startAbility
startAbility(want: Want): Promise&lt;void&gt;;
Starts an ability that belongs to the same application as this StaticSubscriberExtensionAbility. This API uses a promise to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | ----------------------- |
| want | [Want](js-apis-application-want.md) | Yes | Want information about the target ability.|
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000011 | The context does not exist. |
| 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. |
| 16200001 | The caller has been released. |
| 16300003 | The target application is not self application. |
**Example**
```ts
let want = {
bundleName: "com.example.myapp",
abilityName: "MyAbility"
};
try {
this.context.startAbility(want)
.then(() => {
// Carry out normal service processing.
console.log('startAbility succeed');
})
.catch((error) => {
// Process service logic errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) +
' error.message: ' + JSON.stringify(error.message));
});
} catch (paramError) {
// Process input parameter errors.
console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) +
' error.message: ' + JSON.stringify(paramError.message));
}
```
...@@ -13,6 +13,14 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for ...@@ -13,6 +13,14 @@ The **StaticSubscriberExtensionAbility** module provides Extension abilities for
import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility'; import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility';
``` ```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name | Type | Readable| Writable| Description |
| ------- | ------------------------------------------------------------ | ---- | ---- | -------- |
| context | [StaticSubscriberExtensionContext](js-apis-application-StaticSubscriberExtensionContext.md) | Yes | No | Context.|
## StaticSubscriberExtensionAbility.onReceiveEvent ## StaticSubscriberExtensionAbility.onReceiveEvent
onReceiveEvent(event: CommonEventData): void; onReceiveEvent(event: CommonEventData): void;
...@@ -30,7 +38,6 @@ Callback of the common event of a static subscriber. ...@@ -30,7 +38,6 @@ Callback of the common event of a static subscriber.
| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.| | event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.|
**Example** **Example**
```ts ```ts
class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility { class MyStaticSubscriberExtensionAbility extends StaticSubscriberExtensionAbility {
onReceiveEvent(event) { onReceiveEvent(event) {
......
# @ohos.arkui.componentSnapshot (Component Snapshot) # @ohos.arkui.componentSnapshot (Component Snapshot)
The **componentSnapshot** module provides APIs for obtaining component snapshots, including snapshots of components that have been loaded and snapshots of components that have not been loaded yet. The **componentSnapshot** module provides APIs for obtaining component snapshots, including snapshots of components that have been loaded and snapshots of components that have not been loaded yet. Note that a component snapshot does not contain content drawn outside of the area of the owning component or the parent component.
> **NOTE** > **NOTE**
> >
...@@ -8,6 +8,7 @@ The **componentSnapshot** module provides APIs for obtaining component snapshots ...@@ -8,6 +8,7 @@ The **componentSnapshot** module provides APIs for obtaining component snapshots
> >
> You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. > You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
## Modules to Import ## Modules to Import
```js ```js
...@@ -20,14 +21,18 @@ get(id: string, callback: AsyncCallback<image.PixelMap>): void ...@@ -20,14 +21,18 @@ get(id: string, callback: AsyncCallback<image.PixelMap>): void
Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result. Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ------------------------------------------------------------------------------ | | -------- | ----------------------------------- | ---- | ---------------------------------------- |
| id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.| | id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -45,8 +50,8 @@ struct SnapshotExample { ...@@ -45,8 +50,8 @@ struct SnapshotExample {
Image(this.pixmap) Image(this.pixmap)
.width(300).height(300) .width(300).height(300)
// ...Component // ...Component
// ...Components // ...Component
// ...Components // ...Component
Button("click to generate UI snapshot") Button("click to generate UI snapshot")
.onClick(() => { .onClick(() => {
componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => { componentSnapshot.get("root", (error: Error, pixmap: image.PixelMap) => {
...@@ -71,25 +76,29 @@ get(id: string): Promise<image.PixelMap> ...@@ -71,25 +76,29 @@ get(id: string): Promise<image.PixelMap>
Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result. Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result.
> **NOTE**
>
> The snapshot captures content rendered in the last frame. If this API is called when the component triggers an update, the re-rendered content will not be included in the obtained snapshot.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------------------------------- | ---- | -------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.| | id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | -------------- | | ----------------------------- | -------- |
| Promise&lt;image.PixelMap&gt; | Promise used to return the result.| | Promise&lt;image.PixelMap&gt; | Promise used to return the result.|
**Error codes** **Error codes**
| ID| Error Message | | ID | Error Message |
| -------- | ------------------- | | ------ | ------------------- |
| 100001 | if id is not valid. | | 100001 | if id is not valid. |
**Example** **Example**
...@@ -134,14 +143,21 @@ createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap ...@@ -134,14 +143,21 @@ createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap
Renders a custom component in the application background and outputs its snapshot. This API uses an asynchronous callback to return the result. Renders a custom component in the application background and outputs its snapshot. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> To account for the time spent in awaiting component building and rendering, the callback of offscreen snapshots has a delay of less than 500 ms.
>
> If a component is on a time-consuming task, for example, an **\<Image>** or **\<Web>** component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------- | ---- | -------------------- | | -------- | ---------------------------------------- | ---- | ---------- |
| builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.| | builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.|
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -194,25 +210,31 @@ createFromBuilder(builder: CustomBuilder): Promise<image.PixelMap> ...@@ -194,25 +210,31 @@ createFromBuilder(builder: CustomBuilder): Promise<image.PixelMap>
Renders a custom component in the application background and outputs its snapshot. This API uses a promise to return the result. Renders a custom component in the application background and outputs its snapshot. This API uses a promise to return the result.
> **NOTE**
>
> To account for the time spent in awaiting component building and rendering, the callback of offscreen snapshots has a delay of less than 500 ms.
>
> If a component is on a time-consuming task, for example, an **\<Image>** or **\<Web>** component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------- | ------------------------------------------------------- | ---- | -------------------- | | ------- | ---------------------------------------- | ---- | ---------- |
| builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.| | builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | -------------- | | ----------------------------- | -------- |
| Promise&lt;image.PixelMap&gt; | Promise used to return the result.| | Promise&lt;image.PixelMap&gt; | Promise used to return the result.|
**Error codes** **Error codes**
| ID| Error Message | | ID | Error Message |
| -------- | ----------------------------------------- | | ------ | ---------------------------------------- |
| 100001 | if builder is not a valid build function. | | 100001 | if builder is not a valid build function. |
**Example** **Example**
......
...@@ -113,6 +113,7 @@ Enumerates the types of Extension abilities. ...@@ -113,6 +113,7 @@ Enumerates the types of Extension abilities.
| THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.| | THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.|
| PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.| | PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.|
| PRINT<sup>10+</sup> | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.| | PRINT<sup>10+</sup> | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.|
| PUSH<sup>10+</sup> | 17 | **PushExtensionAbility**: provides APIs for pushing scenario-specific messages. This ability is reserved.|
| DRIVER<sup>10+</sup> | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.| | DRIVER<sup>10+</sup> | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.|
| UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.|
......
...@@ -550,7 +550,7 @@ Listens for camera status changes. This API uses an asynchronous callback to ret ...@@ -550,7 +550,7 @@ Listens for camera status changes. This API uses an asynchronous callback to ret
**Example** **Example**
```js ```js
cameraManager.on('cameraStatus', (cameraStatusInfo) => { cameraManager.on('cameraStatus', (err, cameraStatusInfo) => {
console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
console.log(`status: ${cameraStatusInfo.status}`); console.log(`status: ${cameraStatusInfo.status}`);
}) })
...@@ -1679,7 +1679,7 @@ The coordinate system is based on the horizontal device direction with the devic ...@@ -1679,7 +1679,7 @@ The coordinate system is based on the horizontal device direction with the devic
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | -------------------------------| ---- | ------------------- | | ------------- | -------------------------------| ---- | ------------------- |
| exposurePoint | [Point](#point) | Yes | Exposure point. | | exposurePoint | [Point](#point) | Yes | Metering point. The value range of x and y must be within [0,1]. If a value less than 0 is passed, the value **0** is used. If a value greater than **1** is passed, the value **1** is used. |
**Return value** **Return value**
...@@ -1754,7 +1754,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure ...@@ -1754,7 +1754,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------| ---- | ------------------- | | -------- | -------------------------------| ---- | ------------------- |
| exposureBias | number | Yes | Exposure bias to set, which must be within the range obtained by running **getExposureBiasRange** interface. If the API call fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | exposureBias | number | Yes | EV. The supported EV range can be obtained by calling **getExposureBiasRange**. If calling the API fails, an error code defined in [CameraErrorCode](#cameraerrorcode) will be returned. If the value passed is not within the supported range, the nearest critical point is used.|
**Error codes** **Error codes**
...@@ -1936,7 +1936,7 @@ The coordinate system is based on the horizontal device direction with the devic ...@@ -1936,7 +1936,7 @@ The coordinate system is based on the horizontal device direction with the devic
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------- | | -------- | ----------------------- | ---- | ------------------- |
| Point1 | [Point](#point) | Yes | Focal point. | | Point1 | [Point](#point) | Yes | Focal point. The value range of x and y must be within [0,1]. If a value less than 0 is passed, the value **0** is used. If a value greater than **1** is passed, the value **1** is used. |
**Return value** **Return value**
...@@ -2075,7 +2075,7 @@ Sets a zoom ratio, with a maximum precision of two decimal places. ...@@ -2075,7 +2075,7 @@ Sets a zoom ratio, with a maximum precision of two decimal places.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | -------------------- | ---- | ------------------- | | --------- | -------------------- | ---- | ------------------- |
| zoomRatio | number | Yes | Zoom ratio. You can use **getZoomRatioRange** to obtain the supported values.| | zoomRatio | number | Yes | Zoom ratio. The supported zoom ratio range can be obtained by calling **getZoomRatioRange**. If the value passed is not within the supported range, the nearest critical point is used.|
**Return value** **Return value**
...@@ -2735,7 +2735,7 @@ Captures a photo with the specified shooting parameters. This API uses a promise ...@@ -2735,7 +2735,7 @@ Captures a photo with the specified shooting parameters. This API uses a promise
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------------- | ---- | -------- | | ------- | ------------------------------------------- | ---- | -------- |
| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| | setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting parameters. The input of **undefined** is processed as if no parameters were passed.|
**Return value** **Return value**
......
...@@ -46,7 +46,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -46,7 +46,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -85,7 +85,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -85,7 +85,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -116,7 +116,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -116,7 +116,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -153,7 +153,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -153,7 +153,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -191,7 +191,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -191,7 +191,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -222,7 +222,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -222,7 +222,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -257,7 +257,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -257,7 +257,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -288,7 +288,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -288,7 +288,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -323,7 +323,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -323,7 +323,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -354,7 +354,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -354,7 +354,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -389,7 +389,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -389,7 +389,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -420,7 +420,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -420,7 +420,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -455,7 +455,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -455,7 +455,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -492,7 +492,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -492,7 +492,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -530,7 +530,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -530,7 +530,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -563,7 +563,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -563,7 +563,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -594,7 +594,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -594,7 +594,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -625,7 +625,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -625,7 +625,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```js ```js
...@@ -660,7 +660,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -660,7 +660,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```ts ```ts
...@@ -691,7 +691,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod ...@@ -691,7 +691,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod
| ID | Error Message | | ID | Error Message |
| ------ | ---------------------- | | ------ | ---------------------- |
| 890001 | Unspported para value. | | 890001 | param value not valid |
**Example** **Example**
```ts ```ts
...@@ -1737,6 +1737,35 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID ...@@ -1737,6 +1737,35 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID
let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai");
``` ```
### getTimezonesByLocation<sup>10+</sup>
static getTimezonesByLocation(longitude: number, latitude: number): Array&lt;TimeZone&gt;
Creates an array of **TimeZone** objects corresponding to the specified longitude and latitude.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------ |
| longitude | number | Yes | Longitude. The value ranges from **-180** to **179.9**. A positive value is used for east longitude and a negative value is used for west longitude.|
| latitude | number | Yes | Latitude. The value ranges from **-90** to **89.9**. A positive value is used for north latitude and a negative value is used for south latitude.|
**Return value**
| Type | Description |
| -------- | ----------- |
| Array&lt;[TimeZone](#timezone)&gt; | Array of **TimeZone** objects.|
**Example**
```js
let timezoneArray = I18n.TimeZone.getTimezonesByLocation(-118.1, 34.0);
for (var i = 0; i < timezoneArray.length; i++) {
let tzId = timezoneArray[i].getID();
}
```
## Transliterator<sup>9+</sup> ## Transliterator<sup>9+</sup>
......
...@@ -879,6 +879,53 @@ async function Demo() { ...@@ -879,6 +879,53 @@ async function Demo() {
} }
``` ```
### getColorSpace<sup>10+</sup>
getColorSpace(): colorSpaceManager.ColorSpaceManager
Obtains the color space of this image
**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| ----------------------------------- | ---------------- |
| [colorSpaceManager.ColorSpaceManager](js-apis-colorSpaceManager.md#colorspacemanager) | Color space obtained.|
**Example**
```js
import colorSpaceManager from '@ohos.graphics.colorSpaceManager';
async function Demo() {
let csm = pixelmap.getColorSpace();
}
```
### setColorSpace<sup>10+</sup>
setColorSpace(colorSpace: colorSpaceManager.ColorSpaceManager): void
Sets the color space for this image.
**System capability**: SystemCapability.Multimedia.Image.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ----------------------------------- | ---- | --------------- |
| colorSpace | [colorSpaceManager.ColorSpaceManager](js-apis-colorSpaceManager.md#colorspacemanager) | Yes | Color space to set.|
**Example**
```js
import colorSpaceManager from '@ohos.graphics.colorSpaceManager';
async function Demo() {
var csm = colorSpaceManager.create(colorSpaceName);
pixelmap.setColorSpace(csm);
}
```
### release<sup>7+</sup> ### release<sup>7+</sup>
release():Promise\<void> release():Promise\<void>
...@@ -937,7 +984,7 @@ Creates an **ImageSource** instance based on the URI. ...@@ -937,7 +984,7 @@ Creates an **ImageSource** instance based on the URI.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------------- | | ------ | ------ | ---- | ---------------------------------- |
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following formats are supported: JPG, PNG, GIF, BMP, Webp, and RAW.| | uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following formats are supported: .jpg, .png, .gif, .bmp, .webp, and raw. For details, see [SVG Tags<sup>10+</sup>](#svg-tags). |
**Return value** **Return value**
...@@ -975,7 +1022,7 @@ Creates an **ImageSource** instance based on the URI. ...@@ -975,7 +1022,7 @@ Creates an **ImageSource** instance based on the URI.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------- | ---- | ----------------------------------- | | ------- | ------------------------------- | ---- | ----------------------------------- |
| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following formats are supported: JPG, PNG, GIF, BMP, Webp, and RAW.| | uri | string | Yes | Image path. Currently, only the application sandbox path is supported.<br>Currently, the following formats are supported: .jpg, .png, .gif, .bmp, .webp, and raw. For details, see [SVG Tags<sup>10+</sup>](#svg-tags). |
| options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.| | options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.|
**Return value** **Return value**
...@@ -1553,10 +1600,10 @@ let decodeOpts = { ...@@ -1553,10 +1600,10 @@ let decodeOpts = {
editable: true, editable: true,
desiredSize: { width: 198, height: 202 }, desiredSize: { width: 198, height: 202 },
rotate: 0, rotate: 0,
desiredPixelFormat: RGBA_8888, desiredPixelFormat: 3,
index: 0, index: 0,
}; };
let pixelmaplist = await imageSourceApi.createPixelMapList(decodeOpts); let pixelmaplist = imageSourceApi.createPixelMapList(decodeOpts);
``` ```
### createPixelMapList<sup>10+</sup> ### createPixelMapList<sup>10+</sup>
...@@ -1604,7 +1651,7 @@ let decodeOpts = { ...@@ -1604,7 +1651,7 @@ let decodeOpts = {
editable: true, editable: true,
desiredSize: { width: 198, height: 202 }, desiredSize: { width: 198, height: 202 },
rotate: 0, rotate: 0,
desiredPixelFormat: RGBA_8888, desiredPixelFormat: 3,
index: 0, index: 0,
}; };
imageSourceApi.createPixelMap(decodeOpts, pixelmaplist => { imageSourceApi.createPixelMap(decodeOpts, pixelmaplist => {
...@@ -1651,12 +1698,12 @@ Obtains an array of delay times. This API uses a promise to return the result. ...@@ -1651,12 +1698,12 @@ Obtains an array of delay times. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let delayTimes = await imageSourceApi.getDelayTime(); let delayTimes = imageSourceApi.getDelayTime();
``` ```
### getFrameCount<sup>10+</sup> ### getFrameCount<sup>10+</sup>
getFrameCount(callback: AsyncCallback<number>): void; getFrameCount(callback: AsyncCallback\<number>): void;
Obtains the number of frames. This API uses an asynchronous callback to return the result. Obtains the number of frames. This API uses an asynchronous callback to return the result.
...@@ -1693,7 +1740,7 @@ Obtains the number of frames. This API uses a promise to return the result. ...@@ -1693,7 +1740,7 @@ Obtains the number of frames. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let frameCount = await imageSourceApi.getFrameCount(); let frameCount = imageSourceApi.getFrameCount();
``` ```
### release ### release
...@@ -2787,7 +2834,50 @@ Describes the color components of an image. ...@@ -2787,7 +2834,50 @@ Describes the color components of an image.
| pixelStride | number | Yes | No | Pixel stride. | | pixelStride | number | Yes | No | Pixel stride. |
| byteBuffer | ArrayBuffer | Yes | No | Component buffer.| | byteBuffer | ArrayBuffer | Yes | No | Component buffer.|
## ResponseCode ## Supplementary Information
### SVG Tags
The SVG tags are supported since API verison 10. The used version is (SVG) 1.1. Currently, the following tags are supported:
- a
- circla
- clipPath
- defs
- ellipse
- feBlend
- feColorMatrix
- feComposite
- feDiffuseLighting
- feDisplacementMap
- feDistantLight
- feFlood
- feGaussianBlur
- feImage
- feMorphology
- feOffset
- fePointLight
- feSpecularLighting
- feSpotLight
- feTurbulence
- filter
- g
- image
- line
- linearGradient
- mask
- path
- pattern
- polygon
- polyline
- radialGradient
- rect
- stop
- svg
- text
- textPath
- tspan
- use
### ResponseCode
Enumerates the response codes returned upon build errors. Enumerates the response codes returned upon build errors.
......
# @ohos.intl (Internationalization) # @ohos.intl (Internationalization)
The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402.
The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities.
> **NOTE** > **NOTE**
...@@ -68,7 +67,7 @@ Creates a **Locale** object. ...@@ -68,7 +67,7 @@ Creates a **Locale** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| | locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).|
| options<sup>9+</sup> | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | | options | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. |
**Example** **Example**
```js ```js
...@@ -160,9 +159,10 @@ Minimizes information of the **Locale** object. If the script and locale informa ...@@ -160,9 +159,10 @@ Minimizes information of the **Locale** object. If the script and locale informa
``` ```
## LocaleOptions<sup>9+</sup> ## LocaleOptions<sup>6+</sup>
Represents the locale options. Represents the locale options.
In API version 9, the attributes in **LocaleOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -207,7 +207,7 @@ Creates a **DateTimeOptions** object for the specified locale. ...@@ -207,7 +207,7 @@ Creates a **DateTimeOptions** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | | options | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -299,7 +299,7 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -299,7 +299,7 @@ Obtains the formatting options for **DateTimeFormat** object.
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------------------- | | ------------------------------------ | ----------------------------- |
| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| | [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.|
**Example** **Example**
```js ```js
...@@ -311,9 +311,10 @@ Obtains the formatting options for **DateTimeFormat** object. ...@@ -311,9 +311,10 @@ Obtains the formatting options for **DateTimeFormat** object.
``` ```
## DateTimeOptions<sup>9+</sup> ## DateTimeOptions<sup>6+</sup>
Provides the options for the **DateTimeFormat** object. Provides the options for the **DateTimeFormat** object.
In API version 9, the attributes in **DateTimeOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -371,7 +372,7 @@ Creates a **NumberFormat** object for the specified locale. ...@@ -371,7 +372,7 @@ Creates a **NumberFormat** object for the specified locale.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | -------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | | options | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. |
**Example** **Example**
```js ```js
...@@ -421,7 +422,7 @@ Obtains the options of the **NumberFormat** object. ...@@ -421,7 +422,7 @@ Obtains the options of the **NumberFormat** object.
| Type | Description | | Type | Description |
| -------------------------------- | --------------------------- | | -------------------------------- | --------------------------- |
| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| | [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.|
**Example** **Example**
...@@ -434,9 +435,10 @@ Obtains the options of the **NumberFormat** object. ...@@ -434,9 +435,10 @@ Obtains the options of the **NumberFormat** object.
``` ```
## NumberOptions<sup>9+</sup> ## NumberOptions<sup>6+</sup>
Defines the device capability. Defines the device capability.
In API version 9, the attributes in **NumberOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -448,7 +450,7 @@ Defines the device capability. ...@@ -448,7 +450,7 @@ Defines the device capability.
| currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| | currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.|
| unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. | | unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. |
| unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **narrow**.| | unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **narrow**.|
| unitUsage | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| | unitUsage<sup>8+</sup> | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.|
| signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.| | signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.|
| compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. | | compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. |
| notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.| | notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.|
...@@ -494,7 +496,7 @@ Creates a **Collator** object. ...@@ -494,7 +496,7 @@ Creates a **Collator** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------------------------------------ | ---- | ---------------------------- | | -------------------- | ------------------------------------ | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | | options | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. |
**Example** **Example**
```js ```js
...@@ -545,7 +547,7 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -545,7 +547,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
| Type | Description | | Type | Description |
| ------------------------------------ | ----------------- | | ------------------------------------ | ----------------- |
| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| | [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.|
**Example** **Example**
```js ```js
...@@ -557,9 +559,10 @@ Returns properties reflecting the locale and collation options of a **Collator** ...@@ -557,9 +559,10 @@ Returns properties reflecting the locale and collation options of a **Collator**
``` ```
## CollatorOptions<sup>9+</sup> ## CollatorOptions<sup>8+</sup>
Represents the properties of a **Collator** object. Represents the properties of a **Collator** object.
In API version 9, the attributes in **CollatorOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -605,7 +608,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers. ...@@ -605,7 +608,7 @@ Creates a **PluralRules** object to obtain the singular-plural type of numbers.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | | options | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. |
**Example** **Example**
```js ```js
...@@ -648,9 +651,10 @@ Obtains a string that represents the singular-plural type of the specified numbe ...@@ -648,9 +651,10 @@ Obtains a string that represents the singular-plural type of the specified numbe
``` ```
## PluralRulesOptions<sup>9+</sup> ## PluralRulesOptions<sup>8+</sup>
Represents the properties of a **PluralRules** object. Represents the properties of a **PluralRules** object.
In API version 9, the attributes in **PluralRulesOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
...@@ -696,7 +700,7 @@ Creates a **RelativeTimeFormat** object. ...@@ -696,7 +700,7 @@ Creates a **RelativeTimeFormat** object.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ---------------------------------------- | ---- | ---------------------------- | | -------------------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.| | locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
| options<sup>9+</sup> | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | | options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. |
**Example** **Example**
```js ```js
...@@ -788,9 +792,10 @@ Obtains the formatting options for **RelativeTimeFormat** objects. ...@@ -788,9 +792,10 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
``` ```
## RelativeTimeFormatInputOptions<sup>9+</sup> ## RelativeTimeFormatInputOptions<sup>8+</sup>
Represents the properties of a **RelativeTimeFormat** object. Represents the properties of a **RelativeTimeFormat** object.
In API version 9, the attributes in **RelativeTimeFormatInputOptions** are optional.
**System capability**: SystemCapability.Global.I18n **System capability**: SystemCapability.Global.I18n
......
此差异已折叠。
...@@ -55,8 +55,7 @@ ethernet.setIfaceConfig("eth0", { ...@@ -55,8 +55,7 @@ ethernet.setIfaceConfig("eth0", {
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1"
domain: "2.2.2.2"
}, (error) => { }, (error) => {
if (error) { if (error) {
console.log("setIfaceConfig callback error = " + JSON.stringify(error)); console.log("setIfaceConfig callback error = " + JSON.stringify(error));
...@@ -115,8 +114,7 @@ ethernet.setIfaceConfig("eth0", { ...@@ -115,8 +114,7 @@ ethernet.setIfaceConfig("eth0", {
route: "192.168.xx.xxx", route: "192.168.xx.xxx",
gateway: "192.168.xx.xxx", gateway: "192.168.xx.xxx",
netMask: "255.255.255.0", netMask: "255.255.255.0",
dnsServers: "1.1.1.1", dnsServers: "1.1.1.1"
domain: "2.2.2.2"
}).then(() => { }).then(() => {
console.log("setIfaceConfig promise ok "); console.log("setIfaceConfig promise ok ");
}).catch(error => { }).catch(error => {
...@@ -168,7 +166,6 @@ ethernet.getIfaceConfig("eth0", (error, value) => { ...@@ -168,7 +166,6 @@ ethernet.getIfaceConfig("eth0", (error, value) => {
console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway)); console.log("getIfaceConfig callback gateway = " + JSON.stringify(value.gateway));
console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask)); console.log("getIfaceConfig callback netMask = " + JSON.stringify(value.netMask));
console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers)); console.log("getIfaceConfig callback dnsServers = " + JSON.stringify(value.dnsServers));
console.log("getIfaceConfig callback domain = " + JSON.stringify(value.domain));
} }
}); });
``` ```
...@@ -219,7 +216,6 @@ ethernet.getIfaceConfig("eth0").then((data) => { ...@@ -219,7 +216,6 @@ ethernet.getIfaceConfig("eth0").then((data) => {
console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway)); console.log("getIfaceConfig promise gateway = " + JSON.stringify(data.gateway));
console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask)); console.log("getIfaceConfig promise netMask = " + JSON.stringify(data.netMask));
console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers)); console.log("getIfaceConfig promise dnsServers = " + JSON.stringify(data.dnsServers));
console.log("getIfaceConfig promise domain = " + JSON.stringify(data.domain));
}).catch(error => { }).catch(error => {
console.log("getIfaceConfig promise error = " + JSON.stringify(error)); console.log("getIfaceConfig promise error = " + JSON.stringify(error));
}); });
......
...@@ -39,7 +39,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -39,7 +39,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
| 9700005 | StartWork failed. | | 9700005 | StartWork failed. |
...@@ -80,7 +80,7 @@ Instructs the **WorkSchedulerService** to stop the specified task. ...@@ -80,7 +80,7 @@ Instructs the **WorkSchedulerService** to stop the specified task.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- | | ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | Yes | Task to stop. | | work | [WorkInfo](#workinfo) | Yes | Task to stop. |
| needCancel | boolean | Yes | Whether to cancel the task.| | needCancel | boolean | No | Whether to cancel the task. The default value is **false**.|
**Error codes** **Error codes**
...@@ -91,7 +91,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -91,7 +91,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
**Example** **Example**
...@@ -118,7 +118,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -118,7 +118,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.getWorkStatus:callback ## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void
Obtains the latest task status. This API uses an asynchronous callback to return the result. Obtains the latest task status. This API uses an asynchronous callback to return the result.
...@@ -141,7 +141,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -141,7 +141,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
**Example** **Example**
...@@ -161,7 +161,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -161,7 +161,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.getWorkStatus:promise ## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<WorkInfo> getWorkStatus(workId: number): Promise\<WorkInfo>
Obtains the latest task status. This API uses a promise to return the result. Obtains the latest task status. This API uses a promise to return the result.
...@@ -189,7 +189,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -189,7 +189,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
**Example** **Example**
...@@ -207,7 +207,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -207,7 +207,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.obtainAllWorks:callback ## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo> obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
...@@ -252,8 +252,8 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -252,8 +252,8 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.obtainAllWorks:promise ## workScheduler.obtainAllWorks
obtainAllWorks(): Promise<Array\<WorkInfo>> obtainAllWorks(): Promise\<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result. Obtains all tasks associated with this application. This API uses a promise to return the result.
...@@ -317,7 +317,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -317,7 +317,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.isLastWorkTimeOut:callback ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
...@@ -346,7 +346,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -346,7 +346,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
**Example** **Example**
...@@ -364,7 +364,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -364,7 +364,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
} }
``` ```
## workScheduler.isLastWorkTimeOut:promise ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean> isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
...@@ -392,7 +392,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -392,7 +392,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700001 | Memory operation failed. | | 9700001 | Memory operation failed. |
| 9700002 | Parcel operation failed. | | 9700002 | Parcel operation failed. |
| 9700003 | System service operation failed. | | 9700003 | System service operation failed. |
| 9700004 | Checking workInfo failed. | | 9700004 | Check workInfo failed. |
**Example** **Example**
...@@ -432,7 +432,7 @@ Provides detailed information about the task. For details about the constraints ...@@ -432,7 +432,7 @@ Provides detailed information about the task. For details about the constraints
| isPersisted | boolean | No | Whether to enable persistent storage for the task. | | isPersisted | boolean | No | Whether to enable persistent storage for the task. |
| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. | | isDeepIdle | boolean | No | Whether the device needs to enter the idle state. |
| idleWaitTime | number | No | Time to wait in the idle state. | | idleWaitTime | number | No | Time to wait in the idle state. |
| parameters | {[key: string]: number | string | boolean} | No | Carried parameters. | | parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
## NetworkType ## NetworkType
Enumerates the network types that can trigger the task. Enumerates the network types that can trigger the task.
......
...@@ -45,9 +45,9 @@ During RPC or IPC, the sender can use the **write()** method provided by **Messa ...@@ -45,9 +45,9 @@ During RPC or IPC, the sender can use the **write()** method provided by **Messa
### create ### create
static create(): MessageSequence static create(): MessageSequence
Creates a **MessageSequence** object. This API is a static method. Creates a **MessageSequence** object. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -6821,8 +6821,8 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6821,8 +6821,8 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
let deathRecipient = new MyDeathRecipient(); let deathRecipient = new MyDeathRecipient();
try { try {
proxy.registerDeathRecippient(deathRecipient, 0); proxy.registerDeathRecipient(deathRecipient, 0);
proxy.unregisterDeathRecippient(deathRecipient, 0); proxy.unregisterDeathRecipient(deathRecipient, 0);
} catch(error) { } catch(error) {
console.info("proxy register deathRecipient fail, errorCode " + error.code); console.info("proxy register deathRecipient fail, errorCode " + error.code);
console.info("proxy register deathRecipient fail, errorMessage " + error.message); console.info("proxy register deathRecipient fail, errorMessage " + error.message);
...@@ -6893,7 +6893,7 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6893,7 +6893,7 @@ Removes the callback used to receive death notifications of the remote object.
} }
} }
let deathRecipient = new MyDeathRecipient(); let deathRecipient = new MyDeathRecipient();
proxy.addDeathRecippient(deathRecipient, 0); proxy.addDeathRecipient(deathRecipient, 0);
proxy.removeDeathRecipient(deathRecipient, 0); proxy.removeDeathRecipient(deathRecipient, 0);
``` ```
......
此差异已折叠。
...@@ -123,7 +123,7 @@ Unsubscribes from the device status. ...@@ -123,7 +123,7 @@ Unsubscribes from the device status.
| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | | -------------------- | -------------------------------------------------- | ---- | ---------------------------- |
| activity | [ActivityType](#activitytype) | Yes | Device status type. | | activity | [ActivityType](#activitytype) | Yes | Device status type. |
| event | [ActivityEvent](#activityevent) | Yes | Event type. | | event | [ActivityEvent](#activityevent) | Yes | Event type. |
| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data, if the callback parameter is not passed, all callbacks subscribed to this type under this process will be removed. | | callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. If this parameter is not passed, all callbacks associated with the specified event in the process will be unregistered. |
**Example** **Example**
......
...@@ -142,6 +142,7 @@ Compresses a file. This API uses an asynchronous callback to return the result. ...@@ -142,6 +142,7 @@ Compresses a file. This API uses an asynchronous callback to return the result.
**Error codes** **Error codes**
For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md).
| ID| Error Message | | ID| Error Message |
| -------- | --------------------------------------| | -------- | --------------------------------------|
| 900001 | The input source file is invalid. | | 900001 | The input source file is invalid. |
......
...@@ -50,7 +50,7 @@ Application resources can be accessed via an absolute or relative path. In this ...@@ -50,7 +50,7 @@ Application resources can be accessed via an absolute or relative path. In this
> >
> - If code files A and B are in the same directory, you can use either a relative or absolute path in code file B to reference resource files. > - If code files A and B are in the same directory, you can use either a relative or absolute path in code file B to reference resource files.
> >
> - If code files A and B are in different directories, you must use an absolute path in code file B to reference resource files. The reason is that the directory of code file B changes during Webpack packaging. > - If code files A and B are in different directories, you must use an absolute path in code file B to reference resource files, because the directory of code file B changes during Webpack packaging.
> >
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册