提交 b524e958 编写于 作者: Z zengyawen

Merge branch 'OpenHarmony-3.1-Release' of https://gitee.com/zengyawen/docs...

Merge branch 'OpenHarmony-3.1-Release' of https://gitee.com/zengyawen/docs into OpenHarmony-3.1-Release
# Ability Framework Overview # Ability Framework Overview
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more **Ability** instances. An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms. The ability framework model has two forms.
- FA model, which applies to application development using API 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there are Feature Ability (FA) and Particle Ability (PA). The FA supports Page abilities, and the PA supports Service, Data, and Form abilities.
- Stage model, which is introduced since API 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more. - Stage model, which is introduced since API version 9. In the stage model, there are Ability and ExtensionAbility. The ExtensionAbility is further extended to ServiceExtensionAbility, FormExtensionAbility, DataShareExtensionAbility, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
...@@ -14,7 +14,7 @@ The stage model is designed to make it easier to develop complex applications in ...@@ -14,7 +14,7 @@ The stage model is designed to make it easier to develop complex applications in
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported. | Supported. | | Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The **config.json** file is used to describe the HAP and component information. The component must use a fixed file name.| The **module.json** file is used to describe the HAP and component information. The entry file name can be specified.| | Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
...@@ -29,3 +29,6 @@ In addition, the following differences exist in the development process: ...@@ -29,3 +29,6 @@ In addition, the following differences exist in the development process:
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
...@@ -22,20 +22,23 @@ To start the test framework, specify the **TestRunner** and the package name or ...@@ -22,20 +22,23 @@ To start the test framework, specify the **TestRunner** and the package name or
An example command in the FA model is as follows: An example command in the FA model is as follows:
```javascript ```javascript
aa test -p com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 aa test -b BundleName -p com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20
``` ```
An example command in the stage model is as follows: An example command in the stage model is as follows:
```javascript ```javascript
aa test -m com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 aa test -b BundleName -m com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20
``` ```
| Parameter | Mandatory| Description | | Parameter | Mandatory| Description |
| --------------- | -------- | ------------------------------------------------------------ | | --------------- | -------- | ------------------------------------------------------------ |
| -b | Yes | Bundle name of the HAP where the **TestRunner** is located. |
| -p | Yes | Package name of the HAP where the **TestRunner** is located. This parameter is used by the FA model. | | -p | Yes | Package name of the HAP where the **TestRunner** is located. This parameter is used by the FA model. |
| -m | Yes | Module name of the HAP where the **TestRunner** is located. This parameter is used by the stage model. | | -m | Yes | Module name of the HAP where the **TestRunner** is located. This parameter is used by the stage model. |
| -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. | | -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. |
| -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified, the test framework exits only after **finishTest** is invoked.| | -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified or is set to a value less than or equal to **0**, the test framework exits only after **finishTest** is invoked.|
| -s \<key>\<value> | No | It can be any parameter in the key-value format. The entered parameters can be obtained in key-value mode through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **classname** is the key and **myTest** is the value.| | -s \<key>\<value> | No | **-s** can be followed by any key-value pair obtained through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **-s classname** is the key and **myTest** is the value.|
| -D | No | Debug mode for starting the tested application.|
| -h | No | Help information.|
### Using DevEco Studio ### Using DevEco Studio
...@@ -45,6 +48,14 @@ For details about how to use DevEco Studio to start the test framework, see [Ope ...@@ -45,6 +48,14 @@ For details about how to use DevEco Studio to start the test framework, see [Ope
**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). **TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, DevEco Studio initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md).
## Introduction to AbilityDelegatorRegistry
**AbilityDelegatorRegistry** is the **AbilityDelegator** repository class provided by the test framework. You can use **AbilityDelegatorRegistry** to obtain an **AbilityDelegator** instance and the input and generated parameters **AbilityDelegatorArgs** during the test. You can use **AbilityDelegator** to invoke the function set provided by the test framework for testing and verification. For details, see [AbilityDelegatorRegistry](../reference/apis/js-apis-abilityDelegatorRegistry.md).
## Introduction to AbilityDelegatorArgs
**AbilityDelegatorArgs** is a test parameter class provided by the test framework. You can use **AbilityDelegatorArgs** to obtain the parameters passed and generated during the test. For details, see [AbilityDelegatorArgs](../reference/apis/js-apis-application-abilityDelegatorArgs.md).
## Introduction to AbilityMonitor ## Introduction to AbilityMonitor
**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md). **AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. When **AbilityMonitor** is bound to an ability, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md).
...@@ -54,7 +65,7 @@ For details about how to use DevEco Studio to start the test framework, see [Ope ...@@ -54,7 +65,7 @@ For details about how to use DevEco Studio to start the test framework, see [Ope
```javascript ```javascript
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
function onAbilityCreateCallback() { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info("onAbilityCreateCallback");
} }
...@@ -64,7 +75,7 @@ var monitor = { ...@@ -64,7 +75,7 @@ var monitor = {
} }
var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor).then((void) => { abilityDelegator.addAbilityMonitor(monitor).then(() => {
console.info("addAbilityMonitor promise"); console.info("addAbilityMonitor promise");
}); });
``` ```
...@@ -94,7 +105,7 @@ var abilityDelegator; ...@@ -94,7 +105,7 @@ var abilityDelegator;
var ability; var ability;
var timeout = 100; var timeout = 100;
function onAbilityCreateCallback() { function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback"); console.info("onAbilityCreateCallback");
} }
...@@ -113,8 +124,6 @@ var want = { ...@@ -113,8 +124,6 @@ var want = {
bundleName: "bundleName", bundleName: "bundleName",
abilityName: "abilityName" abilityName: "abilityName"
}; };
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.startAbility(want, (err, data) => { abilityDelegator.startAbility(want, (err, data) => {
console.info("startAbility callback"); console.info("startAbility callback");
}); });
...@@ -126,14 +135,47 @@ abilityDelegator.startAbility(want, (err, data) => { ...@@ -126,14 +135,47 @@ abilityDelegator.startAbility(want, (err, data) => {
### Running a Shell Command ### Running a Shell Command
**AbilityDelegator** provides APIs to run shell commands. You can run a shell command in the test code. This feature takes effect only in the test environment. **AbilityDelegator** provides APIs to run shell commands in the test environment.
**Example** **Example**
```javascript ```javascript
var abilityDelegator; var abilityDelegator;
var cmd = "cmd"; var cmd = "cmd";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err,data) => { abilityDelegator.executeShellCommand(cmd, (err, data) => {
console.info("executeShellCommand callback"); console.info("executeShellCommand callback");
}); });
```
### Printing Log Information
**AbilityDelegator** provides APIs for printing log information. You can call any API in the test code to print process logs to the unit test console.
**Example**
```javascript
var abilityDelegator;
var msg = "msg";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.print(msg, (err) => {
console.info("print callback");
});
```
### Finishing the Test and Printing Log Information
**AbilityDelegator** provides the APIs for actively finishing the test. You can call any API in test code to finish the test and print logs to the unit test console.
**Example**
```javascript
var abilityDelegator;
var msg = "msg";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.finishTest(msg, 0, (err) => {
console.info("finishTest callback");
});
``` ```
...@@ -3,14 +3,15 @@ ...@@ -3,14 +3,15 @@
## Overall Architecture ## Overall Architecture
The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling. The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling.
The Feature Ability (FA) model applies to application development using API 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities. The Feature Ability (FA) model applies to application development using API version 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities.
- The Page ability implements the ArkUI and provides the capability of interacting with users. - The Page ability implements the ArkUI and provides the capability of interacting with users.
- The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke. - The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke.
- The Data ability does not have a UI. It also runs in the background and enables other abilities to insert, delete, and query data. - The Data ability does not have a UI. It runs in the background and enables other abilities to insert, delete, and query data.
- The Form ability provides a widget, which is a UI display mode. - The Form ability provides a widget, which is a UI display mode.
## Application Package Structure ## Application Package Structure
**The following figure shows the application package structure.**
The following figure shows the application package structure.
![fa-package-info](figures/fa-package-info.png) ![fa-package-info](figures/fa-package-info.png)
...@@ -18,7 +19,7 @@ For details about the application package structure, see [Description of the App ...@@ -18,7 +19,7 @@ For details about the application package structure, see [Description of the App
## Lifecycle ## Lifecycle
Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and is the interaction entry of applications. Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and acts as a touchpoint for interacting with users.
**The following figure shows the lifecycle of the Page ability.** **The following figure shows the lifecycle of the Page ability.**
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
...@@ -30,6 +31,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** ...@@ -30,6 +31,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
## Process and Thread Model ## Process and Thread Model
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. An application process is created when an ability is started for the first time, and a thread is created for this ability too. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. Therefore, abilities are isolated from each other. An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
...@@ -9,19 +9,19 @@ Data ability providers can customize data access-related APIs such as data inser ...@@ -9,19 +9,19 @@ Data ability providers can customize data access-related APIs such as data inser
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onInitialized|Called during ability initialization to initialize the relational database (RDB).| |onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).|
|update|Updates data in the database.| |update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.|
|query|Queries data in the database.| |query?(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|Queries data in the database.|
|delete|Deletes one or more data records from the database.| |delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Deletes one or more data records from the database.|
|normalizeUri|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| |normalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.|
|batchInsert|Inserts multiple data records into the database.| |batchInsert?(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|Inserts multiple data records into the database.|
|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| |denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert|Inserts a data record into the database.| |insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.|
|openFile|Opens a file.| |openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.|
|getFileTypes|Obtains the MIME type of a file.| |getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\<Array\<string>>): void|Obtains the MIME type of a file.|
|getType|Obtains the MIME type matching the data specified by the URI.| |getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.|
|executeBatch|Operates data in the database in batches.| |executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.|
|call|Calls a custom API.| |call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
## How to Develop ## How to Develop
......
...@@ -10,25 +10,26 @@ Basic concepts: ...@@ -10,25 +10,26 @@ Basic concepts:
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application. - Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update. - Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**
>
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
The widget provider controls the widget content to display, component layout, and click events bound to components. The widget provider controls the widget content to display, component layout, and click events bound to components.
## Scenario ## Development Overview
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: In FA widget development, you need to carry out the following operations as a widget provider based on the [Feature Ability (FA) model](fa-brief.md).
- Develop the lifecycle callbacks in **LifecycleForm**. - Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** instance. - Create a **FormBindingData** instance.
- Update a widget through **FormProvider**. - Update a widget through **FormProvider**.
- Develop the widget UI page. - Develop the widget UI pages.
## Available APIs ## Available APIs
The table below describes the lifecycle callbacks provided **LifecycleForm**. The table below describes the lifecycle callbacks provided in **LifecycleForm**.
**Table 1** LifecycleForm APIs **Table 1** LifecycleForm APIs
...@@ -37,7 +38,7 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. ...@@ -37,7 +38,7 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**.
| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. | | onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. |
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. | | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. |
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. | | onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. |
...@@ -73,7 +74,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -73,7 +74,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default { export default {
onCreate(want) { onCreate(want) {
console.log('FormAbility onCreate'); console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as during widget instance retrieval or update. // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
let obj = { let obj = {
"title": "titleOnCreate", "title": "titleOnCreate",
"detail": "detailOnCreate" "detail": "detailOnCreate"
...@@ -120,7 +121,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -120,7 +121,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
Configure the **config.json** file for the widget. Configure the **config.json** file for the widget.
- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows: - The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal structure is described as follows:
| Field| Description | Data Type| Default | | Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ | | -------- | ------------------------------------------------------------ | -------- | ------------------------ |
...@@ -144,7 +145,7 @@ Configure the **config.json** file for the widget. ...@@ -144,7 +145,7 @@ Configure the **config.json** file for the widget.
}] }]
``` ```
- The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal field structure is described as follows: - The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal structure is described as follows:
| Field | Description | Data Type | Default | | Field | Description | Data Type | Default |
| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
...@@ -195,7 +196,7 @@ Configure the **config.json** file for the widget. ...@@ -195,7 +196,7 @@ Configure the **config.json** file for the widget.
``` ```
### Persistently Store Widget Data ### Persistently Storing Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
...@@ -206,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information ...@@ -206,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formId = want.parameters["ohos.extra.param.key.form_identity"]; let formId = want.parameters["ohos.extra.param.key.form_identity"];
let formName = want.parameters["ohos.extra.param.key.form_name"]; let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update. // Persistently store widget information for subsequent use, such as widget instance retrieval or update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples". // The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples".
storeFormInfo(formId, formName, tempFlag, want); storeFormInfo(formId, formName, tempFlag, want);
...@@ -233,7 +234,7 @@ You should override **onDestroy** to delete widget data. ...@@ -233,7 +234,7 @@ You should override **onDestroy** to delete widget data.
For details about the persistence method, see [Lightweight Data Store Development](../database/database-storage-guidelines.md). For details about the persistence method, see [Lightweight Data Store Development](../database/database-storage-guidelines.md).
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. Note that the **Want** passed by the widget host to the widget provider contains a flag that indicates whether the requested widget is a temporary one.
- Normal widget: a widget that will be persistently used by the widget host - Normal widget: a widget that will be persistently used by the widget host
...@@ -241,13 +242,35 @@ Note that the **Want** passed by the widget host to the widget provider contains ...@@ -241,13 +242,35 @@ Note that the **Want** passed by the widget host to the widget provider contains
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
### Developing the Widget UI Page ### Updating Widget Data
When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows:
```javascript
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
"detail": "detailOnUpdate"
};
let formData = formBindingData.createFormBindingData(obj);
// Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
formProvider.updateForm(formId, formData).catch((error) => {
console.log('FormAbility updateForm, error:' + JSON.stringify(error));
});
}
```
### Developing Widget UI Pages
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**
>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- HML: - In the HML file:
```html ```html
<div class="container"> <div class="container">
<stack> <stack>
...@@ -262,7 +285,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -262,7 +285,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
</div> </div>
``` ```
- CSS: - In the CSS file:
```css ```css
.container { .container {
...@@ -303,7 +326,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -303,7 +326,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
} }
``` ```
- JSON: - In the JSON file:
```json ```json
{ {
"data": { "data": {
......
...@@ -131,8 +131,8 @@ You can also include **parameters** in the **want** parameter and set its value ...@@ -131,8 +131,8 @@ You can also include **parameters** in the **want** parameter and set its value
}, },
); );
``` ```
### Starting a Remote Page Ability (Applying only to System Applications) ### Starting a Remote Page Ability
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Page ability startup applies only to system applications. >Note: This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
**Modules to Import** **Modules to Import**
...@@ -261,4 +261,5 @@ export default { ...@@ -261,4 +261,5 @@ export default {
``` ```
## Samples ## Samples
The following sample is provided to help you better understand how to develop a Page ability: The following sample is provided to help you better understand how to develop a Page ability:
- [`DMS`: Distributed Demo (eTS) (API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -8,11 +8,11 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -8,11 +8,11 @@ A Service ability is used to run tasks in the background, such as playing music
**Table 1** Service ability lifecycle APIs **Table 1** Service ability lifecycle APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onStart|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| |onStart?(): void|Called to initialize a Service ability being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.|
|onCommand|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.| |onCommand?(want: Want, startId: number): void|Called every time a Service ability is created on a client. You can collect calling statistics and perform initialization operations in this callback.|
|onConnect|Called when another ability is connected to the Service ability.| |onConnect?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect|Called when another ability is disconnected from the Service ability.| |onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|onStop|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| |onStop?(): void|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.|
## How to Develop ## How to Develop
...@@ -43,7 +43,7 @@ A Service ability is used to run tasks in the background, such as playing music ...@@ -43,7 +43,7 @@ A Service ability is used to run tasks in the background, such as playing music
2. Register a Service ability. 2. Register a Service ability.
You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. Declare the Service ability in the **config.json** file by setting its **type** attribute to **service**.
```javascript ```javascript
{ {
...@@ -214,8 +214,8 @@ export default { ...@@ -214,8 +214,8 @@ export default {
} }
``` ```
### Connecting to a Remote Service Ability (Applying only to System Applications) ### Connecting to a Remote Service Ability
>NOTE >**NOTE**
> >
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. >This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
......
...@@ -2,18 +2,18 @@ ...@@ -2,18 +2,18 @@
## When to Use ## When to Use
Ability continuation is to continue the current mission of an application, including the UI component status variables and distributed objects, on another device. The UI component status variables are used to synchronize page data, and the distributed objects are used to synchronize data in the memory. Ability continuation is to continue the current mission of an application, including the UI component state variables and distributed objects, on another device. The UI component state variables are used to synchronize UI data, and the distributed objects are used to synchronize memory data.
## Available APIs ## Available APIs
The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-application-ability.md). The following table lists the APIs used for ability continuation. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 1** Ability continuation APIs **Table 1** Ability continuation APIs
|API| Description| |API| Description|
|:------ | :------| |:------ | :------|
| onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the **initiator** to save data during the ability continuation preparation process. The return value **0** means that the continuation request is accepted, and an error code means that the continuation request is denied.| | onContinue(wantParam : {[key: string]: any}): OnContinueResult | Called by the initiator to store the data required for continuation and request continuation. The value **AGREE** means that the continuation is accepted, and **REJECT** means the continuation is rejected, and **MISMATCH** means a version mismatch.|
| onCreate(want: Want, param: LaunchParam): void| Called by the **target** to restore the data and page.| | onCreate(want: Want, param: LaunchParam): void | Called by the target to restore the data and UI page.|
| **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).| | **enum** OnContinueResult | Enumerates the return values of **onContinue**. The options are as follows: **AGREE** (request accepted), **REJECT** (request denied), and **MISMATCH** (version mismatch).|
...@@ -38,9 +38,9 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -38,9 +38,9 @@ The following table lists the APIs used for ability continuation. For details ab
* Configure the application startup type. - Configure the application startup type.
Set **launchType** in the **module.json5** to **standard**. Currently, only multi-instance applications can be continued on another device. Set **launchType** in the **module.json5** file to **standard** to add multi-instance support to the application.
```javascript ```javascript
"launchType": "standard" "launchType": "standard"
...@@ -48,7 +48,7 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -48,7 +48,7 @@ The following table lists the APIs used for ability continuation. For details ab
* Apply for the distributed permissions. - Apply for the distributed permissions.
Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application. Declare the **DISTRIBUTED_DATASYNC** permission in the **module.json5** file for the application.
...@@ -100,9 +100,9 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -100,9 +100,9 @@ The following table lists the APIs used for ability continuation. For details ab
2. Implement the **onContinue** API. 2. Implement the **onContinue()** API.
The **onContinue** API is called by the **initiator** to save the UI component status variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE** to accept the continuation request. If an error code is returned, the request is denied. If this API is not implemented, the system rejects the continuation request by default. The **onContinue()** API is called by the initiator to save the UI component state variables and memory data and prepare for continuation. After the application completes the continuation preparation, the system must return **OnContinueResult.AGREE(0)** to accept the continuation request. If an error code is returned, the request is rejected. If this API is not implemented, the system rejects the continuation request by default.
Modules to import: Modules to import:
...@@ -111,10 +111,10 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -111,10 +111,10 @@ The following table lists the APIs used for ability continuation. For details ab
import AbilityConstant from '@ohos.application.AbilityConstant'; import AbilityConstant from '@ohos.application.AbilityConstant';
``` ```
- To implement ability continuation, you must implement this API and have the value **AGREE** returned. To implement ability continuation, you must implement this API and have the value **AGREE** returned.
- Example Example
```javascript ```javascript
onContinue(wantParam : {[key: string]: any}) { onContinue(wantParam : {[key: string]: any}) {
...@@ -128,24 +128,24 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -128,24 +128,24 @@ The following table lists the APIs used for ability continuation. For details ab
3. Implement the continuation logic in the **onCreate** API. 3. Implement the continuation logic in the **onCreate()** API.
The **onCreate** API is called by the **target**. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component status, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored. The **onCreate()** API is called by the target. When the ability is started on the target device, this API is called to instruct the application to synchronize the memory data and UI component state, and triggers page restoration after the synchronization is complete. If the continuation logic is not implemented, the ability will be started in common startup mode and the page cannot be restored.
- The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate**. The target device determines whether the startup is **LaunchReason.CONTINUATION** based on **launchReason** in **onCreate()**.
- After data restore is complete, call **restoreWindowStage** to trigger page restoration. After data restore is complete, call **restoreWindowStage** to trigger page restoration.
* Example Example
```javascript ```javascript
onCreate(want, launchParam) { onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`) Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want; globalThis.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) { if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
let input = want.parameters.input // get user data from want params let input = want.parameters.input // Obtain user data from want params.
AppStorage.SetOrCreate<string>('ContinueInput', input) AppStorage.SetOrCreate<string>('ContinueInput', input)
Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`) Logger.info(`onCreate for continuation sessionId: ${this.sessionId}`)
...@@ -159,13 +159,13 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -159,13 +159,13 @@ The following table lists the APIs used for ability continuation. For details ab
### Data Continuation ### Data Continuation
1. Use distributed objects. Use distributed objects.
Distributed data objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/database/database-distributedobject-guidelines.md). Distributed objects allow cross-device data synchronization like local variables. For two devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other device. Both devices can listen for the data changes and online and offline states of the other. For details, see [Distributed Data Object Development](../database/database-distributedobject-guidelines.md).
In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device. In the ability continuation scenario, the distributed data object is used to synchronize the memory data from the local device to the target device.
- In **onContinue**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**. - In **onContinue()**, the initiator saves the data to be continued to the distributed object, sets the session ID, and sends the session ID to the target device through **wantParam**.
```javascript ```javascript
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -190,7 +190,7 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -190,7 +190,7 @@ The following table lists the APIs used for ability continuation. For details ab
``` ```
- The target device obtains the session ID from **onCreate**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated for correct data retrieval. - The target device obtains the session ID from **onCreate()**, creates a distributed object, and associates the distributed object with the session ID. In this way, the distributed object can be synchronized. Before calling **restoreWindowStage**, ensure that all distributed objects required for continuation have been associated.
```javascript ```javascript
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -227,3 +227,6 @@ The following table lists the APIs used for ability continuation. For details ab ...@@ -227,3 +227,6 @@ The following table lists the APIs used for ability continuation. For details ab
For details about the complete example, see the sample. For details about the complete example, see the sample.
...@@ -208,7 +208,6 @@ export default class MainAbility extends Ability { ...@@ -208,7 +208,6 @@ export default class MainAbility extends Ability {
The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md). The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
**Table 3** AbilityContext APIs **Table 3** AbilityContext APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.| |startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.|
...@@ -249,7 +248,7 @@ var want = { ...@@ -249,7 +248,7 @@ var want = {
context.startAbility(want).then((data) => { context.startAbility(want).then((data) => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data)) console.log("Succeed to start remote ability with data: " + JSON.stringify(data))
}).catch((error) => { }).catch((error) => {
console.error("Failed to start remote ability with error: "+ JSON.stringify(error)) console.error("Failed to start remote ability with error: " + JSON.stringify(error))
}) })
``` ```
Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows: Obtain the ID of a specified device from `DeviceManager`. The sample code is as follows:
......
# Stage Model Overview # Stage Model Overview
### Design Ideas ## Design Ideas
The stage model is designed to make it easier to develop complex applications in the distributed environment. The stage model is designed to make it easier to develop complex applications in the distributed environment.
...@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations: ...@@ -20,10 +20,10 @@ The stage model is designed based on the following considerations:
- **Support for multiple device types and window forms** - **Support for multiple device types and window forms**
To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency of the component manager and window manager. To support multiple device types and facilitate the implementation of different window forms, the component manager and window manager must be decoupled at the architecture layer for easier tailoring. To achieve this goal, the stage model redefines the ability lifecycle and implements unidirectional dependency for the component manager and window manager.
### Basic Concepts ## Basic Concepts
The following figure shows the basic concepts in the stage model. The following figure shows the basic concepts in the stage model.
...@@ -33,24 +33,24 @@ The following figure shows the basic concepts in the stage model. ...@@ -33,24 +33,24 @@ The following figure shows the basic concepts in the stage model.
- **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application. - **Bundle**: an OpenHarmony application identified by **appid**. A bundle can contain multiple HAP files. Each application has a **bundleName**. However, **bundleName** must be used together with **appid** and other information to uniquely identify an application.
- **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime. - **AbilityStage**: runtime class of an HAP. It is created when the HAP is loaded to the process for the first time and is visible to developers in the runtime.
- **Application**: runtime class of a bundle, which is invisible to developers in the runtime. - **Application**: runtime class of a bundle, which is invisible to developers in the runtime.
- **Context**: provides various capabilities that can be invoked by developers during the runtime. The **Ability** and **ExtensionAbility** classes have their own context classes, which inherit the base class **Context**. The base class provides information such as the bundle name, module name, and path. - **Context**: base class that the context classes of **Ability** and **ExtensionAbility** classes inherit. This class provides various capabilities that can be invoked by developers in the runtime, and various information such as the bundle name, module name, and path.
- **Ability**: provides lifecycle callback, holds the **AbilityContext** class, and supports component continuation and collaboration. - **Ability**: class that provides lifecycle callbacks, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**. - **ExtensionAbility**: general name of scenario-based service extension abilities. The system defines multiple scenario-based **ExtensionAbility** classes, each of which has its own **ExtensionContext**.
- **WindowStage**: local window manager. - **WindowStage**: local window manager.
- **Window**: basic unit managed by the window manager. It has an ArkUI engine instance. - **Window**: basic unit managed by the window manager. It has an ArkUI engine instance.
- **ArkUI Page**: displays declarative ArkUI. - **ArkUI Page**: ArkUI development framework page.
### Lifecycle ## Lifecycle
The ability and ability stage lifecycles are the most important concepts in the basic process of an application. The comparison between the FA model lifecycle and stage model lifecycle is provided in [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage. The ability and ability stage lifecycles are the rudiments of the basic process of an application. For details about how these lifecycles differ from those in the FA model, see [Ability Framework Overview](ability-brief.md). This section focuses on the ability lifecycle transition and the scheduling relationships between the ability, ability stage, and window stage.
![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png) ![stageabilitylifecyclecallback](figures/stageabilitylifecyclecallback.png)
To implement multi-device-form tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes. To implement device-specific tailoring and multi-window scalability, OpenHarmony decouples the component manager from the window manager. The ability lifecycle defined in the stage model includes only the creation, destruction, foreground, and background states. The gain focus and lose focus states that are closely related to UI content are defined in the window stage. This implements weak coupling between the abilities and windows. On the service side, the window manager notifies the component manager of the foreground and background changes, so the component manager only senses the foreground and background changes but not the focus changes.
### Ability Instances and Missions ## Ability Instances and Missions
Abilities can be started in any of the following modes: Abilities can be started in any of the following modes:
...@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes: ...@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes:
Each ability instance corresponds to a mission in **Launcher Recent**. Each ability instance corresponds to a mission in **Launcher Recent**.
The mission corresponding to each ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space exceeds the upper limit. The mission corresponding to an ability instance has a snapshot of the ability instance. After the ability instance is destroyed, the ability class information and snapshot are retained in the mission until the user deletes the information or the storage space reaches the upper limit.
![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png) ![AbilityComponentInstanceMission](figures/AbilityComponentInstanceMission.png)
### ExtensionAbility Mechanism ## ExtensionAbility Mechanism
Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features: Different from the ability used for page display, the extension ability provides a restricted service running environment. It has the following features:
...@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro ...@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro
![ExtensionAbility](figures/ExtensionAbility.png) ![ExtensionAbility](figures/ExtensionAbility.png)
### Process Model ## Process Model
All OpenHarmony applications are designed to meet the single-process model. In the single-process model, an application is not allowed to configure multiple processes, and all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes: All OpenHarmony applications are designed to meet the single-process model. In the single-process model, all processes in the application are created and managed by the system. Each application supports a maximum of three types of processes:
- Main process: runs all ability components, pages, and service logic. - Main process: runs all ability components, pages, and service logic.
......
...@@ -187,7 +187,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ...@@ -187,7 +187,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
{ {
"forms": [{ "forms": [{
"name": "widget", "name": "widget",
"description": "This is a service widget.", "description": "This is a widget.",
"src": "./js/widget/pages/index/index", "src": "./js/widget/pages/index/index",
"window": { "window": {
"autoDesignWidth": true, "autoDesignWidth": true,
...@@ -252,7 +252,28 @@ Note that the **Want** passed by the widget host to the widget provider contains ...@@ -252,7 +252,28 @@ Note that the **Want** passed by the widget host to the widget provider contains
Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets. Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets.
### Updating Widget Data
When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows:
```javascript
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
"detail": "detailOnUpdate"
};
let formData = formBindingData.createFormBindingData(obj);
// Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
formProvider.updateForm(formId, formData).catch((error) => {
console.log('FormAbility updateForm, error:' + JSON.stringify(error));
});
}
```
### Developing the Widget UI Page ### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
......
# Service Extension Ability Development # Service Extension Ability Development
## When to Use ## When to Use
**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**. **ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**.
You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes. You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes.
...@@ -80,7 +80,5 @@ Declare the Service Extension ability in the **module.json** file by setting its ...@@ -80,7 +80,5 @@ Declare the Service Extension ability in the **module.json** file by setting its
The following sample is provided to help you better understand how to develop a Service Extension ability: The following sample is provided to help you better understand how to develop a Service Extension ability:
- [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility) - [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility)
This sample shows how to create a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory.
...@@ -202,7 +202,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -202,7 +202,7 @@ You can obtain the distributed table name for a remote device based on the local
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db",} const STORE_CONFIG = {name: "rdbstore.db",}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
``` ```
......
...@@ -21,7 +21,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -21,7 +21,7 @@ The following table lists the USB APIs currently available. For details, see the
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. |
| function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. | | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
......
...@@ -43,7 +43,7 @@ The full video playback process includes creating an instance, setting the URL, ...@@ -43,7 +43,7 @@ The full video playback process includes creating an instance, setting the URL,
For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes). For details about the **url** types supported by **VideoPlayer**, see the [url attribute](../reference/apis/js-apis-media.md#videoplayer_attributes).
For details about how to create an XComponent, see [XComponent](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md). For details about how to create an XComponent, see [XComponent]( ../reference/arkui-ts/ts-basic-components-xcomponent.md).
*Note: **setSurface** must be called after the URL is set but before **prepare** is called. *Note: **setSurface** must be called after the URL is set but before **prepare** is called.
......
...@@ -2,5 +2,6 @@ ...@@ -2,5 +2,6 @@
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native_window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
# NativeWindow Development
## When to Use
`NativeWindow` is a local platform window of OpenHarmony. It provides APIs for you to create a native window from `Surface`, create a native window buffer from `SurfaceBuffer`, and request and flush a buffer.
The following scenarios are common for native window development:
* Drawing content using native C++ code and displaying the content on the screen
* Requesting and flushing a buffer when adapting to EGL `eglswapbuffer`
## Available APIs
| API| Description|
| -------- | -------- |
| OH_NativeWindow_CreateNativeWindowFromSurface (void \*pSurface) | Creates a `NativeWindow` instance. A new `NativeWindow` instance is created each time this function is called.|
| OH_NativeWindow_DestroyNativeWindow (struct NativeWindow \*window) | Decreases the reference count of a `NativeWindow` instance by 1 and, when the reference count reaches 0, destroys the instance.|
| OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void \*pSurfaceBuffer) | Creates a `NativeWindowBuffer` instance. A new `NativeWindowBuffer` instance is created each time this function is called.|
| OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer \*buffer) | Decreases the reference count of a `NativeWindowBuffer` instance by 1 and, when the reference count reaches 0, destroys the instance.|
| OH_NativeWindow_NativeWindowRequestBuffer (struct NativeWindow \*window struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | Requests a `NativeWindowBuffer` through a `NativeWindow` instance for content production.|
| OH_NativeWindow_NativeWindowFlushBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | Flushes the `NativeWindowBuffer` filled with the content to the buffer queue through a `NativeWindow` instance for content consumption.|
| OH_NativeWindow_NativeWindowCancelBuffer (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | Returns the `NativeWindowBuffer` to the buffer queue through a `NativeWindow` instance, without filling in any content. The `NativeWindowBuffer` can be used for another request.|
| OH_NativeWindow_NativeWindowHandleOpt (struct NativeWindow \*window, int code,...) | Sets or obtains the attributes of a native window, including the width, height, and content format.|
| OH_NativeWindow_GetBufferHandleFromNative (struct NativeWindowBuffer \*buffer) | Obtains the pointer to a `BufferHandle` of a `NativeWindowBuffer` instance.|
| OH_NativeWindow_NativeObjectReference (void \*obj) | Adds the reference count of a native object.|
| OH_NativeWindow_NativeObjectUnreference (void \*obj) | Decreases the reference count of a native object and, when the reference count reaches 0, destroys this object.|
| OH_NativeWindow_GetNativeObjectMagic (void \*obj) | Obtains the magic ID of a native object.|
## How to Develop
The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to draw content using native C++ code and display the content on the screen.
1. Define an `XComponent` of the `texture` type in `index.ets` for content display.
```js
XComponent({ id: 'xcomponentId', type: 'texture', libraryname: 'nativerender'})
.borderColor(Color.Red)
.borderWidth(5)
.onLoad(() => {})
.onDestroy(() => {})
```
2. Obtain an `OH_NativeXComponent` instance (named `nativeXComponent` in this example) by calling `napi_get_named_property`, and obtain a `NativeWindow` instance by registering the callback of the `OH_NativeXComponent` instance.
```c++
// Define a NAPI instance.
napi_value exportInstance = nullptr;
// Define an OH_NativeXComponent instance.
OH_NativeXComponent *nativeXComponent = nullptr;
// Use the OH_NATIVE_XCOMPONENT_OBJ export instance.
napi_getname_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance);
// Convert the NAPI instance to the OH_NativeXComponent instance.
napi_unwarp(env, exportInstance, reinterpret_cast<void**>(&nativeXComponent));
```
3. Define the callback `OnSurfaceCreated`. During the creation of a `Surface`, the callback is used to initialize the rendering environment, for example, the `Skia` rendering environment, and write the content to be displayed to `NativeWindow`.
```c++
void OnSufaceCreatedCB(NativeXComponent* component, void* window) {
// Obtain the width and height of the native window.
uint64_t width_ = 0, height_ = 0;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
// Convert void* into a NativeWindow instance. NativeWindow is defined in native_window/external_window.h.
NativeWindow* nativeWindow_ = (NativeWindow*)(window);
// Set or obtain the NativeWindow attributes by calling OH_NativeWindow_NativeWindowHandleOpt.
// 1. Use SET_USAGE to set the usage attribute of the native window, for example, to HBM_USE_CPU_READ.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_USAGE, HBM_USE_CPU_READ | HBM_USE_CPU_WRITE |HBM_USE_MEM_DMA);
// 2. Use SET_BUFFER_GEOMETRY to set the width and height attributes of the native window.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_BUFFER_GEOMETRY, width_, height_);
// 3. Use SET_FORMAT to set the format attribute of the native window, for example, to PIXEL_FMT_RGBA_8888.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_FORMAT, PIXEL_FMT_RGBA_8888);
// 4. Use SET_STRIDE to set the stride attribute of the native window.
OH_NativeWindow_NativeWindowHandleOpt(nativeWindow_, SET_STRIDE, 0x8);
// Obtain the NativeWindowBuffer instance by calling OH_NativeWindow_NativeWindowRequestBuffer.
struct NativeWindowBuffer* buffer = nullptr;
int fenceFd;
OH_NativeWindow_NativeWindowRequestBuffer(nativeWindow_, &buffer, &fenceFd);
// Obtain the buffer handle by calling OH_NativeWindow_GetNativeBufferHandleFromNative.
BufferHandle* bufferHandle = OH_NativeWindow_GetNativeBufferHandleFromNative(buffer);
// Create a Skia bitmap using BufferHandle.
SkBitmap bitmap;
SkImageInfo imageInfo = ...
bitmap.setInfo(imageInfo, bufferHandle->stride);
bitmap.setPixels(bufferHandle->virAddr);
// Create Skia Canvas and write the content to the native window.
...
// After the write operation is complete, flush the buffer by using OH_NativeWindwo_NativeWindowFlushBuffer so that the data is displayed on the screen.
Regoin region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
}
```
4. Register the callback `OnSurfaceCreated` by using `OH_NativeXComponent_RegisterCallback`.
```c++
OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
```
...@@ -320,10 +320,10 @@ arrayList.add(2); ...@@ -320,10 +320,10 @@ arrayList.add(2);
arrayList.add(4); arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.replaceAllElements((value, index) => { arrayList.replaceAllElements((value: number, index: number)=> {
return value = 2 * value; return value = 2 * value;
}); });
arrayList.replaceAllElements((value, index) => { arrayList.replaceAllElements((value: number, index: number) => {
return value = value - 2; return value = value - 2;
}); });
``` ```
...@@ -394,8 +394,8 @@ arrayList.add(2); ...@@ -394,8 +394,8 @@ arrayList.add(2);
arrayList.add(4); arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.sort((a, b) => a - b); arrayList.sort((a: number, b: number) => a - b);
arrayList.sort((a, b) => b - a); arrayList.sort((a: number, b: number) => b - a);
arrayList.sort(); arrayList.sort();
``` ```
......
# Background Task Management # BackgroundTaskManager
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** This module provides background task management.
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type.
If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup.
If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
> **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -26,7 +34,7 @@ The default duration of delayed suspension is 180000 when the battery level is h ...@@ -26,7 +34,7 @@ The default duration of delayed suspension is 180000 when the battery level is h
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------ | | -------- | -------------------- | ---- | ------------------------------ |
| reason | string | Yes | Reason for delayed transition to the suspended state. | | reason | string | Yes | Reason for delayed transition to the suspended state. |
| callback | Callback&lt;void&gt; | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out. | | callback | Callback&lt;void&gt; | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.|
**Return value** **Return value**
| Type | Description | | Type | Description |
...@@ -120,6 +128,7 @@ Cancels the suspension delay. ...@@ -120,6 +128,7 @@ Cancels the suspension delay.
**Example** **Example**
```js ```js
let id = 1;
backgroundTaskManager.cancelSuspendDelay(id); backgroundTaskManager.cancelSuspendDelay(id);
``` ```
...@@ -191,12 +200,12 @@ Requests a continuous task from the system. This API uses a promise to return th ...@@ -191,12 +200,12 @@ Requests a continuous task from the system. This API uses a promise to return th
| --------- | ---------------------------------- | ---- | ----------------------- | | --------- | ---------------------------------- | ---- | ----------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. | | context | [Context](js-apis-Context.md) | Yes | Application context. |
| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | | bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ---------------- | | -------------- | ---------------- |
| Promise\<void> | Promise used to return the result. | | Promise\<void> | Promise used to return the result.|
**Example** **Example**
```js ```js
...@@ -239,7 +248,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to ...@@ -239,7 +248,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------- | ---- | ---------------------- | | -------- | ----------------------------- | ---- | ---------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. | | context | [Context](js-apis-Context.md) | Yes | Application context. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
```js ```js
...@@ -269,12 +278,12 @@ Requests to cancel a continuous task. This API uses a promise to return the resu ...@@ -269,12 +278,12 @@ Requests to cancel a continuous task. This API uses a promise to return the resu
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ----------------------------- | ---- | --------- | | ------- | ----------------------------- | ---- | --------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. | | context | [Context](js-apis-Context.md) | Yes | Application context.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ---------------- | | -------------- | ---------------- |
| Promise\<void> | Promise used to return the result. | | Promise\<void> | Promise used to return the result.|
**Example** **Example**
```js ```js
...@@ -306,13 +315,13 @@ Provides the information about the suspension delay. ...@@ -306,13 +315,13 @@ Provides the information about the suspension delay.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
| Name | Value| Description | | Name | Value| Description |
| ----------------------- | ------ | ---------------------------- | | ----------------------- | ------ | ------------------------------------------------------------ |
| DATA_TRANSFER | 1 | Data transfer. | | DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | 2 | Audio playback. | | AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | 3 | Audio recording. | | AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | 4 | Positioning and navigation. | | LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | | BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | | MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | 7 | WLAN-related (reserved). | | WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API and cannot be called by third-party applications.|
| VOIP | 8 | Voice and video call (reserved). | | VOIP | 8 | Audio and video calls.<br>This is a system API and cannot be called by third-party applications.|
| TASK_KEEPING | 9 | Computing task (effective only for specific devices).| | TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
# Display # Display
Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays.
> **NOTE**<br/> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -139,7 +141,7 @@ Obtains all the display objects. ...@@ -139,7 +141,7 @@ Obtains all the display objects.
| Type | Description | | Type | Description |
| ----------------------------------------------- | ------------------------------------------------------- | | ----------------------------------------------- | ------------------------------------------------------- |
| Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return an array containing all the display objects.| | Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return all the display objects.|
**Example** **Example**
...@@ -163,7 +165,7 @@ Enables listening. ...@@ -163,7 +165,7 @@ Enables listening.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>-&nbsp;**add**: listening for whether a display is added<br>-&nbsp;**remove**: listening for whether a display is removed<br>-&nbsp;**change**: listening for whether a display is changed| | type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.| | callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example** **Example**
...@@ -186,7 +188,7 @@ Disables listening. ...@@ -186,7 +188,7 @@ Disables listening.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>-&nbsp;**add**: listening for whether a display is added<br>-&nbsp;**remove**: listening for whether a display is removed<br>-&nbsp;**change**: listening for whether a display is changed| | type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.| | callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example** **Example**
......
...@@ -576,13 +576,12 @@ Provides KV store configuration. ...@@ -576,13 +576,12 @@ Provides KV store configuration.
Defines the KV store types. Defines the KV store types.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Default Value| Description | | Name | Default Value| Description |
| --- | ---- | ----------------------- | | --- | ---- | ----------------------- |
| DEVICE_COLLABORATION | 0 | Device KV store. | | DEVICE_COLLABORATION | 0 | Device KV store. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| SINGLE_VERSION | 1 | Single KV store. | | SINGLE_VERSION | 1 | Single KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. | | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
## SecurityLevel ## SecurityLevel
......
# HiAppEvent # HiAppEvent
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import hiAppEvent from '@ohos.hiAppEvent'; import hiAppEvent from '@ohos.hiAppEvent';
``` ```
...@@ -23,14 +25,14 @@ Writes event information to the event file of the current day. This API supports ...@@ -23,14 +25,14 @@ Writes event information to the event file of the current day. This API supports
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ------------------------- | ---- | ------------------------------------------------------------ | | --------- | ------------------------- | ---- | ------------------------------------------------------------ |
| eventName | string | Yes | App event name.<br>You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| | eventName | string | Yes | Application event name.<br>You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. |
| eventType | [EventType](#eventtype) | Yes | Application event type. | | eventType | [EventType](#eventtype) | Yes | Application event type. |
| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.<br>- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).<br>- The number of event parameters must be less than or equal to 32.<br>- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).<br>- A string value can contain a maximum of 8*1024 characters.<br>- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| | keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.<br>- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).<br>- The number of event parameters must be less than or equal to 32.<br>- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).<br>- A string value can contain a maximum of 8*1024 characters.<br>- An array value can contain a maximum of 100 elements. Excess elements will be truncated. |
| callback | AsyncCallback&lt;void&gt; | No | Callback used to process the received return value.<br>-&nbsp; Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously. <br>-&nbsp; A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored. <br>-&nbsp; A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file.| | callback | AsyncCallback&lt;void&gt; | No | Callback used to process the received return value.<br>-&nbsp; Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously. <br>-&nbsp; A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored. <br>-&nbsp; A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file. |
**Example** **Example**
``` ```js
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => {
if (err) { if (err) {
// Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails.
...@@ -56,19 +58,19 @@ Writes event information to the event file of the current day. This API supports ...@@ -56,19 +58,19 @@ Writes event information to the event file of the current day. This API supports
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ | | --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| eventName | string | Yes | App event name.<br>You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| | eventName | string | Yes | Application event name.<br>You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. |
| eventType | [EventType](#eventtype) | Yes | Application event type. | | eventType | [EventType](#eventtype) | Yes | Application event type. |
| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.<br>- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).<br>- The number of event parameters must be less than or equal to 32.<br>- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).<br>- A string value can contain a maximum of 8*1024 characters.<br>- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| | keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.<br>- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).<br>- The number of event parameters must be less than or equal to 32.<br>- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).<br>- A string value can contain a maximum of 8*1024 characters.<br>- An array value can contain a maximum of 100 elements. Excess elements will be truncated. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------ |
| Promise&lt;void&gt; | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed.| | Promise&lt;void&gt; | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed. |
**Example** **Example**
``` ```js
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"})
.then((value) => { .then((value) => {
// Event writing succeeded. // Event writing succeeded.
...@@ -92,16 +94,16 @@ Configures the application event logging function, such as setting the event log ...@@ -92,16 +94,16 @@ Configures the application event logging function, such as setting the event log
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------ | | ------ | ----------------------------- | ---- | ------------------------ |
| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| | config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------------------------------------------------------- | | ------- | ----------------------------------------------------------- |
| boolean | Returns **true** if the configuration is successful; returns **false** otherwise.| | boolean | Returns **true** if the configuration is successful; returns **false** otherwise. |
**Example** **Example**
``` ```js
// Set the application event logging switch. // Set the application event logging switch.
hiAppEvent.configure({ hiAppEvent.configure({
disable: true disable: true
...@@ -122,8 +124,8 @@ Provides the configuration items for application event logging. ...@@ -122,8 +124,8 @@ Provides the configuration items for application event logging.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ | | ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Application event logging switch. The value <b>true</b> means to disable the application event logging function, and the value <b>false</b> means the opposite.| | disable | boolean | No | Application event logging switch. The value <b>true</b> means to disable the application event logging function, and the value <b>false</b> means the opposite. |
| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.| | maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space. |
## EventType ## EventType
...@@ -150,7 +152,7 @@ Provides constants that define the names of all predefined events. ...@@ -150,7 +152,7 @@ Provides constants that define the names of all predefined events.
| ------------------------- | -------- | ---- | ---- | -------------------- | | ------------------------- | -------- | ---- | ---- | -------------------- |
| USER_LOGIN | string | Yes | No | User login event. | | USER_LOGIN | string | Yes | No | User login event. |
| USER_LOGOUT | string | Yes | No | User logout event. | | USER_LOGOUT | string | Yes | No | User logout event. |
| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| | DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event. |
## Param ## Param
...@@ -159,8 +161,8 @@ Provides constants that define the names of all predefined event parameters. ...@@ -159,8 +161,8 @@ Provides constants that define the names of all predefined event parameters.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Readable| Writable| Description | | Name | Type | Readable | Writable | Description |
| ------------------------------- | -------- | ---- | ---- | ------------------ | | ------------------------------- | -------- | ---- | ---- | ------------------ |
| USER_ID | string | Yes | No | Custom user ID. | | USER_ID | string | Yes | No | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | | DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| | DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID. |
\ No newline at end of file
# Distributed Call Chain Tracing # Distributed Call Chain Tracing
This module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
# Performance Tracing # Performance Tracing
This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
...@@ -364,10 +364,10 @@ list.add(2); ...@@ -364,10 +364,10 @@ list.add(2);
list.add(4); list.add(4);
list.add(5); list.add(5);
list.add(4); list.add(4);
list.replaceAllElements((value, index) => { list.replaceAllElements((value: number, index: number) => {
return value = 2 * value; return value = 2 * value;
}); });
list.replaceAllElements((value, index) => { list.replaceAllElements((value: number, index: number) => {
return value = value - 2; return value = value - 2;
}); });
``` ```
...@@ -439,8 +439,8 @@ list.add(2); ...@@ -439,8 +439,8 @@ list.add(2);
list.add(4); list.add(4);
list.add(5); list.add(5);
list.add(4); list.add(4);
list.sort((a, b) => a - b); list.sort((a: number, b: number) => a - b);
list.sort((a, b) => b - a); list.sort((a: number, b: number) => b - a);
``` ```
### getSubList ### getSubList
...@@ -472,9 +472,9 @@ list.add(2); ...@@ -472,9 +472,9 @@ list.add(2);
list.add(4); list.add(4);
list.add(5); list.add(5);
list.add(4); list.add(4);
let result = list.subList(2, 4); let result = list.getSubList(2, 4);
let result1 = list.subList(4, 3); let result1 = list.getSubList(4, 3);
let result2 = list.subList(2, 6); let result2 = list.getSubList(2, 6);
``` ```
### clear ### clear
......
...@@ -23,15 +23,17 @@ matchMediaSync(condition: string): MediaQueryListener ...@@ -23,15 +23,17 @@ matchMediaSync(condition: string): MediaQueryListener
Sets the media query criteria and returns the corresponding listening handle. Sets the media query criteria and returns the corresponding listening handle.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------- | | --------- | ------ | ---- | ---------------------------------------- |
| condition | string | Yes | Matching condition of a media event.| | condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------ | ---------------------- | | ------------------ | ---------------------- |
| MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| | MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.|
**Example** **Example**
```js ```js
...@@ -43,6 +45,7 @@ listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for ...@@ -43,6 +45,7 @@ listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for
Media query handle, including the first query result when the handle is applied for. Media query handle, including the first query result when the handle is applied for.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
### Attributes ### Attributes
...@@ -58,6 +61,8 @@ on(type: 'change', callback: Callback&lt;MediaQueryResult&gt;): void ...@@ -58,6 +61,8 @@ on(type: 'change', callback: Callback&lt;MediaQueryResult&gt;): void
Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ---------------- | | -------- | -------------------------------- | ---- | ---------------- |
...@@ -72,12 +77,15 @@ Registers a callback with the corresponding query condition by using the handle. ...@@ -72,12 +77,15 @@ Registers a callback with the corresponding query condition by using the handle.
off(type: 'change', callback?: Callback&lt;MediaQueryResult&gt;): void off(type: 'change', callback?: Callback&lt;MediaQueryResult&gt;): void
Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. Deregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ----------------------------- | | -------- | -------------------------------- | ---- | ----------------------------- |
| type | boolean | Yes | Must enter the string **change**. | | type | boolean | Yes | Must enter the string **change**. |
| callback | Callback&lt;MediaQueryResult&gt; | No | Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| | callback | Callback&lt;MediaQueryResult&gt; | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.|
**Example** **Example**
```js ```js
...@@ -92,7 +100,7 @@ Unregisters a callback with the corresponding query condition by using the handl ...@@ -92,7 +100,7 @@ Unregisters a callback with the corresponding query condition by using the handl
} }
} }
listener.on('change', onPortrait) // Register a callback. listener.on('change', onPortrait) // Register a callback.
listener.off('change', onPortrait) // Unregister a callback. listener.off('change', onPortrait) // Deregister a callback.
``` ```
......
# Page Routing # Page Routing
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**
> >
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. > - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase.
...@@ -190,6 +190,8 @@ getLength(): string ...@@ -190,6 +190,8 @@ getLength(): string
Obtains the number of pages in the current stack. Obtains the number of pages in the current stack.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
...@@ -275,7 +277,7 @@ Enables the display of a confirm dialog box before returning to the previous pag ...@@ -275,7 +277,7 @@ Enables the display of a confirm dialog box before returning to the previous pag
Describes the confirm dialog box. Describes the confirm dialog box.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
# Screenshot # Screenshot
Provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -18,10 +21,11 @@ Describes screenshot options. ...@@ -18,10 +21,11 @@ Describes screenshot options.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------- | ---- | ------------------------------------------------------------ | | ---------------------- | ------------- | ---- | ------------------------------------------------------------ |
| screenRect | [Rect](#rect) | No | Region of the screen to capture. If this parameter is null, the full screen will be captured.| | screenRect | [Rect](#rect) | No | Region of the screen to capture. If this parameter is null, the full screen will be captured. |
| imageSize | [Size](#size) | No | Size of the screen region to capture. If this parameter is null, the full screen will be captured.| | imageSize | [Size](#size) | No | Size of the screen region to capture. If this parameter is null, the full screen will be captured. |
| rotation | number | No | Rotation angle of the screenshot. Currently, the value can be **0** only. The default value is **0**.| | rotation | number | No | Rotation angle of the screenshot. Currently, the value can be **0** only. The default value is **0**. |
| displayId<sup>8+</sup> | number | No | ID of the [display](js-apis-display.md#display) device on which the screen region is to be captured.|
## Rect ## Rect
...@@ -63,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal ...@@ -63,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| | options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.|
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return a **PixelMap** object. | | callback | AsyncCallback&lt;image.PixelMap&gt; | Yes | Callback used to return a **PixelMap** object. |
**Example** **Example**
...@@ -78,7 +82,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal ...@@ -78,7 +82,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal
"imageSize": { "imageSize": {
"width": 300, "width": 300,
"height": 300}, "height": 300},
"rotation": 0 "rotation": 0,
"displayId": 0
}; };
screenshot.save(ScreenshotOptions, (err, data) => { screenshot.save(ScreenshotOptions, (err, data) => {
if (err) { if (err) {
...@@ -103,13 +108,13 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro ...@@ -103,13 +108,13 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot options, which consist of **screenRect**, **imageSize**, and **rotation**. You need to set these parameters.| | options | [ScreenshotOptions](#screenshotoptions) | No | Consists of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set them separately.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | ----------------------------------------------- | | ----------------------------- | ----------------------------------------------- |
| Promise&lt;image.PixelMap&gt; | Promise used to return an **image.PixelMap** object.| | Promise&lt;image.PixelMap&gt; | Promise used to return a **PixelMap** object.|
**Example** **Example**
...@@ -123,7 +128,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro ...@@ -123,7 +128,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro
"imageSize": { "imageSize": {
"width": 300, "width": 300,
"height": 300}, "height": 300},
"rotation": 0 "rotation": 0,
"displayId": 0
}; };
let promise = screenshot.save(ScreenshotOptions); let promise = screenshot.save(ScreenshotOptions);
promise.then(() => { promise.then(() => {
......
...@@ -190,7 +190,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ...@@ -190,7 +190,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This
**Example** **Example**
```js ```js
systemTime.getCurrentTime().then((data) => { systemTime.getRealActiveTime().then((data) => {
console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error(`failed to systemTime.getRealActiveTime because ` + JSON.stringify(error)); console.error(`failed to systemTime.getRealActiveTime because ` + JSON.stringify(error));
......
...@@ -134,11 +134,11 @@ Obtains the new version information. This function uses an asynchronous callback ...@@ -134,11 +134,11 @@ Obtains the new version information. This function uses an asynchronous callback
**Example** **Example**
``` ```
updater.getNewVersionInfo(info => { updater.getNewVersionInfo((err, info) => {
console.log("getNewVersionInfo success " + info.status); console.log("getNewVersionInfo success " + info.status);
console.log(`info versionName = ` + info.checkResult[0].versionName); console.log(`info versionName = ` + info.checkResults[0].versionName);
console.log(`info versionCode = ` + info.checkResult[0].versionCode); console.log(`info versionCode = ` + info.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); console.log(`info verifyInfo = ` + info.checkResults[0].verifyInfo);
}); });
``` ```
...@@ -160,9 +160,9 @@ Obtains the new version information. This function uses a promise to return the ...@@ -160,9 +160,9 @@ Obtains the new version information. This function uses a promise to return the
``` ```
updater.getNewVersionInfo().then(value => { updater.getNewVersionInfo().then(value => {
console.log(`info versionName = ` + value.checkResult[0].versionName); console.log(`info versionName = ` + value.checkResults[0].versionName);
console.log(`info versionCode = ` + value.checkResult[0].versionCode); console.log(`info versionCode = ` + value.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); console.log(`info verifyInfo = ` + value.checkResults[0].verifyInfo);
}).catch(err => { }).catch(err => {
console.log("getNewVersionInfo promise error: " + err.code); console.log("getNewVersionInfo promise error: " + err.code);
}); });
...@@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro ...@@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro
**Example** **Example**
``` ```
updater.checkNewVersion(info => { updater.checkNewVersion((err, info) => {
console.log("checkNewVersion success " + info.status); console.log("checkNewVersion success " + info.status);
console.log(`info versionName = ` + info.checkResult[0].versionName); console.log(`info versionName = ` + info.checkResults[0].versionName);
console.log(`info versionCode = ` + info.checkResult[0].versionCode); console.log(`info versionCode = ` + info.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo); console.log(`info verifyInfo = ` + info.checkResults[0].verifyInfo);
}); });
``` ```
...@@ -211,9 +211,9 @@ Checks whether the current version is the latest. This function uses a promise t ...@@ -211,9 +211,9 @@ Checks whether the current version is the latest. This function uses a promise t
``` ```
updater.checkNewVersion().then(value => { updater.checkNewVersion().then(value => {
console.log(`info versionName = ` + value.checkResult[0].versionName); console.log(`info versionName = ` + value.checkResults[0].versionName);
console.log(`info versionCode = ` + value.checkResult[0].versionCode); console.log(`info versionCode = ` + value.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo); console.log(`info verifyInfo = ` + value.checkResults[0].verifyInfo);
}).catch(err => { }).catch(err => {
console.log("checkNewVersion promise error: " + err.code); console.log("checkNewVersion promise error: " + err.code);
}); });
...@@ -284,7 +284,7 @@ Reboots the device and clears the user partition data. This function uses a prom ...@@ -284,7 +284,7 @@ Reboots the device and clears the user partition data. This function uses a prom
**Example** **Example**
``` ```
updater.rebootAndCleanUserData(result => { updater.rebootAndCleanUserData((err, result) => {
console.log("rebootAndCleanUserData ", result) console.log("rebootAndCleanUserData ", result)
}); });
``` ```
...@@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result. ...@@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result.
**Example** **Example**
``` ```
updater.applyNewVersion(result => { updater.applyNewVersion((err, result) => {
console.log("applyNewVersion ", result) console.log("applyNewVersion ", result)
}); });
``` ```
...@@ -399,7 +399,7 @@ let policy = { ...@@ -399,7 +399,7 @@ let policy = {
autoUpgradeInterval: [ 2, 3 ], autoUpgradeInterval: [ 2, 3 ],
autoUpgradeCondition: 2 autoUpgradeCondition: 2
} }
updater.setUpdatePolicy(policy, result => { updater.setUpdatePolicy(policy, (err, result) => {
console.log("setUpdatePolicy ", result) console.log("setUpdatePolicy ", result)
}); });
``` ```
...@@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return ...@@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return
**Example** **Example**
``` ```
updater.getUpdatePolicy(policy => { updater.getUpdatePolicy((err, policy) => {
console.log("getUpdatePolicy success"); console.log("getUpdatePolicy success");
console.log(`policy autoDownload = ` + policy.autoDownload); console.log(`policy autoDownload = ` + policy.autoDownload);
console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet);
......
# URL String Parsing # URL String Parsing
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -10,10 +11,6 @@ ...@@ -10,10 +11,6 @@
import Url from '@ohos.url' import Url from '@ohos.url'
``` ```
## System Capabilities
SystemCapability.Utils.Lang
## URLSearchParams ## URLSearchParams
...@@ -23,20 +20,22 @@ constructor(init?: string[][] | Record&lt;string, string&gt; | string | URLSearc ...@@ -23,20 +20,22 @@ constructor(init?: string[][] | Record&lt;string, string&gt; | string | URLSearc
Creates a **URLSearchParams** instance. Creates a **URLSearchParams** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| init | string[][]&nbsp;\|&nbsp;Record&lt;string,&nbsp;string&gt;&nbsp;\|&nbsp;string&nbsp;\|&nbsp;URLSearchParams | No| Input parameter objects, which include the following:<br>- **string[][]**: two-dimensional string array<br>- **Record&lt;string,&nbsp;string&gt;**: list of objects<br>- **string**: string<br>- **URLSearchParams**: object| | init | string[][] \| Record&lt;string, string&gt; \| string \| URLSearchParams | No| Input parameter objects, which include the following:<br>- **string[][]**: two-dimensional string array<br>- **Record&lt;string, string&gt;**: list of objects<br>- **string**: string<br>- **URLSearchParams**: object |
**Example** **Example**
```js ```js
var objectParams = new URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
var objectParams1 = new URLSearchParams({"fod" : 1 , "bard" : 2}); var objectParams1 = new Url.URLSearchParams({"fod" : 1 , "bard" : 2});
var objectParams2 = new URLSearchParams('?fod=1&bard=2'); var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
var urlObject = new URL('https://developer.mozilla.org/?fod=1&bard=2'); var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
var params = new URLSearchParams(urlObject.search); var params = new Url.URLSearchParams(urlObject.search);
``` ```
...@@ -46,18 +45,20 @@ append(name: string, value: string): void ...@@ -46,18 +45,20 @@ append(name: string, value: string): void
Appends a key-value pair into the query string. Appends a key-value pair into the query string.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key of the key-value pair to append.| | name | string | Yes | Key of the key-value pair to append. |
| value | string | Yes| Value of the key-value pair to append.| | value | string | Yes | Value of the key-value pair to append. |
**Example** **Example**
```js ```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); paramsObject.append('fod', 3);
``` ```
...@@ -68,17 +69,19 @@ delete(name: string): void ...@@ -68,17 +69,19 @@ delete(name: string): void
Deletes key-value pairs of the specified key. Deletes key-value pairs of the specified key.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key of the key-value pairs to delete.| | name | string | Yes | Key of the key-value pairs to delete. |
**Example** **Example**
```js ```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsobject = new URLSearchParams(urlObject.search.slice(1)); let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsobject.delete('fod'); paramsobject.delete('fod');
``` ```
...@@ -89,23 +92,25 @@ getAll(name: string): string[] ...@@ -89,23 +92,25 @@ getAll(name: string): string[]
Obtains all the key-value pairs based on the specified key. Obtains all the key-value pairs based on the specified key.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key specified to obtain all key-value pairs.| | name | string | Yes | Key specified to obtain all key-value pairs. |
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| string[] | All key-value pairs matching the specified key.| | string[] | All key-value pairs matching the specified key. |
**Example** **Example**
```js ```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); // Add a second value for the fod parameter. paramsObject.append('fod', 3); // Add a second value for the fod parameter.
console.log(params.getAll('fod')) // Output ["1","3"]. console.log(params.getAll('fod')) // Output ["1","3"].
``` ```
...@@ -117,16 +122,18 @@ entries(): IterableIterator<[string, string]> ...@@ -117,16 +122,18 @@ entries(): IterableIterator<[string, string]>
Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | ES6 iterator.| | IterableIterator&lt;[string, string]&gt; | ES6 iterator. |
**Example** **Example**
```js ```js
var searchParamsObject = new URLSearchParams("keyName1=valueName1&keyName2=valueName2"); var searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2");
for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs
console.log(pair[0]+ ', '+ pair[1]); console.log(pair[0]+ ', '+ pair[1]);
} }
...@@ -139,25 +146,27 @@ forEach(callbackfn: (value: string, key: string, searchParams: this) => void, th ...@@ -139,25 +146,27 @@ forEach(callbackfn: (value: string, key: string, searchParams: this) => void, th
Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. Traverses the key-value pairs in the **URLSearchParams** instance by using a callback.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| | callbackfn | function | Yes | Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance. |
| thisArg | Object | No| Value to use when the callback is invoked.| | thisArg | Object | No | Value to use when the callback is invoked. |
**Table 1** callbackfn parameter description **Table 1** callbackfn parameter description
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | string | Yes| Value that is currently traversed.| | value | string | Yes | Value that is currently traversed. |
| key | string | Yes| Key that is currently traversed.| | key | string | Yes | Key that is currently traversed. |
| searchParams | Object | Yes| Instance that invokes the **forEach** method.| | searchParams | Object | Yes | Instance that invokes the **forEach** method. |
**Example** **Example**
```js ```js
const myURLObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
myURLObject.searchParams.forEach((value, name, searchParams) => { myURLObject.searchParams.forEach((value, name, searchParams) => {
console.log(name, value, myURLObject.searchParams === searchParams); console.log(name, value, myURLObject.searchParams === searchParams);
}); });
...@@ -170,23 +179,25 @@ get(name: string): string | null ...@@ -170,23 +179,25 @@ get(name: string): string | null
Obtains the value of the first key-value pair based on the specified key. Obtains the value of the first key-value pair based on the specified key.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key specified to obtain the value.| | name | string | Yes | Key specified to obtain the value. |
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| string | Returns the value of the first key-value pair if obtained.| | string | Returns the value of the first key-value pair if obtained. |
| null | Returns null if no value is obtained.| | null | Returns null if no value is obtained. |
**Example** **Example**
```js ```js
var paramsOject = new URLSearchParams(document.location.search.substring(1)); var paramsOject = new Url.URLSearchParams(document.location.search.substring(1));
var name = paramsOject.get("name"); // is the string "Jonathan" var name = paramsOject.get("name"); // is the string "Jonathan"
var age = parseInt(paramsOject.get("age"), 10); // is the number 18 var age = parseInt(paramsOject.get("age"), 10); // is the number 18
var address = paramsOject.get("address"); // null var address = paramsOject.get("address"); // null
...@@ -199,23 +210,25 @@ has(name: string): boolean ...@@ -199,23 +210,25 @@ has(name: string): boolean
Checks whether a key has a value. Checks whether a key has a value.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key specified to search for its value.| | name | string | Yes | Key specified to search for its value. |
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the value exists; returns **false** otherwise.| | boolean | Returns **true** if the value exists; returns **false** otherwise. |
**Example** **Example**
```js ```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.has('bard') === true; paramsObject.has('bard') === true;
``` ```
...@@ -226,18 +239,20 @@ set(name: string, value: string): void ...@@ -226,18 +239,20 @@ set(name: string, value: string): void
Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Key of the value to set.| | name | string | Yes | Key of the value to set. |
| value | string | Yes| Value to set.| | value | string | Yes | Value to set. |
**Example** **Example**
```js ```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1)); let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.set('baz', 3); // Add a third parameter. paramsObject.set('baz', 3); // Add a third parameter.
``` ```
...@@ -246,13 +261,14 @@ paramsObject.set('baz', 3); // Add a third parameter. ...@@ -246,13 +261,14 @@ paramsObject.set('baz', 3); // Add a third parameter.
sort(): void sort(): void
Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained.
**System capability**: SystemCapability.Utils.Lang
**Example** **Example**
```js ```js
var searchParamsObject = new URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object var searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object
searchParamsObject.sort(); // Sort the key/value pairs searchParamsObject.sort(); // Sort the key/value pairs
console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4
``` ```
...@@ -262,19 +278,20 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ...@@ -262,19 +278,20 @@ console.log(searchParamsObject.toString()); // Display the sorted query string /
keys(): IterableIterator&lt;string&gt; keys(): IterableIterator&lt;string&gt;
Obtains an ES6 iterator that contains the keys of all the key-value pairs. Obtains an ES6 iterator that contains the keys of all the key-value pairs.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;string&gt; | ES6 iterator that contains the keys of all the key-value pairs.| | IterableIterator&lt;string&gt; | ES6 iterator that contains the keys of all the key-value pairs. |
**Example** **Example**
```js ```js
var searchParamsObject = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing var searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
for (var key of searchParamsObject .keys()) { // Output key-value pairs for (var key of searchParamsObject .keys()) { // Output key-value pairs
console.log(key); console.log(key);
} }
...@@ -287,16 +304,18 @@ values(): IterableIterator&lt;string&gt; ...@@ -287,16 +304,18 @@ values(): IterableIterator&lt;string&gt;
Obtains an ES6 iterator that contains the values of all the key-value pairs. Obtains an ES6 iterator that contains the values of all the key-value pairs.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;string&gt; | ES6 iterator that contains the values of all the key-value pairs.| | IterableIterator&lt;string&gt; | ES6 iterator that contains the values of all the key-value pairs. |
**Example** **Example**
```js ```js
var searchParams = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing var searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing
for (var value of searchParams.values()) { for (var value of searchParams.values()) {
console.log(value); console.log(value);
} }
...@@ -307,19 +326,20 @@ for (var value of searchParams.values()) { ...@@ -307,19 +326,20 @@ for (var value of searchParams.values()) {
[Symbol.iterator]\(): IterableIterator&lt;[string, string]&gt; [Symbol.iterator]\(): IterableIterator&lt;[string, string]&gt;
Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | ES6 iterator.| | IterableIterator&lt;[string, string]&gt; | ES6 iterator. |
**Example** **Example**
```js ```js
const paramsObject = new URLSearchParams('fod=bay&edg=bap'); const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap');
for (const [name, value] of paramsObject) { for (const [name, value] of paramsObject) {
console.log(name, value); console.log(name, value);
} }
...@@ -330,20 +350,21 @@ for (const [name, value] of paramsObject) { ...@@ -330,20 +350,21 @@ for (const [name, value] of paramsObject) {
toString(): string toString(): string
Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| string | String of serialized search parameters, which is percent-encoded if necessary.| | string | String of serialized search parameters, which is percent-encoded if necessary. |
**Example** **Example**
```js ```js
let url = new URL('https://developer.exampleUrl/?fod=1&bard=2'); let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new URLSearchParams(url.search.slice(1)); let params = new Url.URLSearchParams(url.search.slice(1));
params.append('fod', 3); params.append('fod', 3);
console.log(params.toString()); console.log(params.toString());
``` ```
...@@ -351,9 +372,10 @@ console.log(params.toString()); ...@@ -351,9 +372,10 @@ console.log(params.toString());
## URL ## URL
### Attributes ### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| | hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.|
...@@ -374,31 +396,32 @@ console.log(params.toString()); ...@@ -374,31 +396,32 @@ console.log(params.toString());
constructor(url: string, base?: string | URL) constructor(url: string, base?: string | URL)
Creates a URL. Creates a URL.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| url | string | Yes| Input object.| | url | string | Yes | Input object. |
| base | string&nbsp;\|&nbsp;URL | No| Input parameter, which can be any of the following:<br>- **string**: string<br>- **URL**: string or object| | base | string \ |& URL | No | Input parameter, which can be any of the following:<br>- **string**: string<br>- **URL**: string or object |
**Example** **Example**
```js ```js
var mm = 'http://username:password@host:8080'; var mm = 'http://username:password@host:8080';
var a = new URL("/", mm); // Output 'http://username:password@host:8080/'; var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/';
var b = new URL(mm); // Output 'http://username:password@host:8080/'; var b = new Url.URL(mm); // Output 'http://username:password@host:8080/';
new URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1';
var c = new URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; var c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1';
new URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1';
new URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1';
new URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1
new URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL
new URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL
new URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/
new URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/
``` ```
...@@ -408,16 +431,18 @@ toString(): string ...@@ -408,16 +431,18 @@ toString(): string
Converts the parsed URL into a string. Converts the parsed URL into a string.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| string | Website address in a serialized string.| | string | Website address in a serialized string. |
**Example** **Example**
```js ```js
const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toString() url.toString()
``` ```
...@@ -426,17 +451,18 @@ url.toString() ...@@ -426,17 +451,18 @@ url.toString()
toJSON(): string toJSON(): string
Converts the parsed URL into a JSON string. Converts the parsed URL into a JSON string.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | -------- | -------- |
| string | Website address in a serialized string.| | string | Website address in a serialized string. |
**Example** **Example**
```js ```js
const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da');
url.toJSON() url.toJSON()
``` ```
\ No newline at end of file
# util # util
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **types** for checks of built-in object types. This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types.
## Modules to Import ## Modules to Import
...@@ -140,7 +141,7 @@ Processes an asynchronous function and returns a promise version. ...@@ -140,7 +141,7 @@ Processes an asynchronous function and returns a promise version.
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| encoding | string | Yes| No| Encoding format.<br>-&nbsp;Supported formats: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrilli, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le| | encoding | string | Yes| No| Encoding format.<br>- Supported formats: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrilli, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le|
| fatal | boolean | Yes| No| Whether to display fatal errors.| | fatal | boolean | Yes| No| Whether to display fatal errors.|
| ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.| | ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.|
...@@ -208,9 +209,6 @@ Decodes the input content. ...@@ -208,9 +209,6 @@ Decodes the input content.
result[4] = 0x62; result[4] = 0x62;
result[5] = 0x63; result[5] = 0x63;
console.log("input num:"); console.log("input num:");
for(var j= 0; j < 6; j++) {
console.log(result[j]);
}
var retStr = textDecoder.decode( result , {stream: false}); var retStr = textDecoder.decode( result , {stream: false});
console.log("retStr = " + retStr); console.log("retStr = " + retStr);
``` ```
...@@ -262,6 +260,7 @@ Encodes the input content. ...@@ -262,6 +260,7 @@ Encodes the input content.
**Example** **Example**
```js ```js
var textEncoder = new util.TextEncoder(); var textEncoder = new util.TextEncoder();
var buffer = new ArrayBuffer(20);
var result = new Uint8Array(buffer); var result = new Uint8Array(buffer);
result = textEncoder.encode("\uD800¥¥"); result = textEncoder.encode("\uD800¥¥");
``` ```
...@@ -361,7 +360,6 @@ Compares this **RationalNumber** object with a given object. ...@@ -361,7 +360,6 @@ Compares this **RationalNumber** object with a given object.
| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| | number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.|
**Example** **Example**
```js ```js
var rationalNumber = new util.RationalNumber(1,2); var rationalNumber = new util.RationalNumber(1,2);
var rational = rationalNumer.creatRationalFromString("3/4"); var rational = rationalNumer.creatRationalFromString("3/4");
...@@ -484,7 +482,7 @@ Obtains the denominator of this **RationalNumber** object. ...@@ -484,7 +482,7 @@ Obtains the denominator of this **RationalNumber** object.
### isZero<sup>8+</sup> ### isZero<sup>8+</sup>
isZero​(): boolean isZero​():boolean
Checks whether this **RationalNumber** object is **0**. Checks whether this **RationalNumber** object is **0**.
...@@ -524,7 +522,7 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN). ...@@ -524,7 +522,7 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN).
### isFinite<sup>8+</sup> ### isFinite<sup>8+</sup>
isFinite​(): boolean isFinite​():boolean
Checks whether this **RationalNumber** object represents a finite value. Checks whether this **RationalNumber** object represents a finite value.
...@@ -825,7 +823,7 @@ Obtains the value of the specified key. ...@@ -825,7 +823,7 @@ Obtains the value of the specified key.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| V&nbsp;\|&nbsp;undefind | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| | V \| undefind | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.|
**Example** **Example**
```js ```js
...@@ -872,7 +870,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac ...@@ -872,7 +870,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| V&nbsp;[] | All values in the buffer, listed from the most to the least recently accessed.| | V [] | All values in the buffer, listed from the most to the least recently accessed.|
**Example** **Example**
```js ```js
...@@ -895,7 +893,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce ...@@ -895,7 +893,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| K&nbsp;[] | All keys in the buffer, listed from the most to the least recently accessed.| | K [] | All keys in the buffer, listed from the most to the least recently accessed.|
**Example** **Example**
```js ```js
...@@ -921,7 +919,7 @@ Removes the specified key and its value from this buffer. ...@@ -921,7 +919,7 @@ Removes the specified key and its value from this buffer.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| V&nbsp;\|&nbsp;undefind | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| | V \| undefind | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.|
**Example** **Example**
```js ```js
...@@ -1038,7 +1036,7 @@ Obtains a new iterator object that contains all key-value pairs in this object. ...@@ -1038,7 +1036,7 @@ Obtains a new iterator object that contains all key-value pairs in this object.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [K,&nbsp;V] | Iterable array.| | [K, V] | Iterable array.|
**Example** **Example**
```js ```js
...@@ -1059,7 +1057,7 @@ Obtains a two-dimensional array in key-value pairs. ...@@ -1059,7 +1057,7 @@ Obtains a two-dimensional array in key-value pairs.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [K,&nbsp;V] | Two-dimensional array in key-value pairs.| | [K, V] | Two-dimensional array in key-value pairs.|
**Example** **Example**
```js ```js
...@@ -1092,6 +1090,8 @@ Example ...@@ -1092,6 +1090,8 @@ Example
```js ```js
class Temperature{ class Temperature{
constructor(value){ constructor(value){
// If TS is used for development, add the following code:
// private readonly _temp: Temperature;
this._temp = value; this._temp = value;
} }
comapreTo(value){ comapreTo(value){
...@@ -1183,7 +1183,7 @@ Obtains the intersection of this **Scope** and the given **Scope**. ...@@ -1183,7 +1183,7 @@ Obtains the intersection of this **Scope** and the given **Scope**.
### intersect<sup>8+</sup> ### intersect<sup>8+</sup>
intersect(lowerObj: ScopeType,upperObj: ScopeType): Scope intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope
Obtains the intersection of this **Scope** and the given lower and upper limits. Obtains the intersection of this **Scope** and the given lower and upper limits.
...@@ -1276,6 +1276,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits. ...@@ -1276,6 +1276,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits.
| [Scope](#scope8) | Union set of this **Scope** and the given lower and upper limits.| | [Scope](#scope8) | Union set of this **Scope** and the given lower and upper limits.|
**Example** **Example**
```js ```js
var tempLower = new Temperature(30); var tempLower = new Temperature(30);
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
...@@ -1288,7 +1289,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits. ...@@ -1288,7 +1289,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits.
### expand<sup>8+</sup> ### expand<sup>8+</sup>
expand(range:Scope):Scope expand(range: Scope): Scope
Obtains the union set of this **Scope** and the given **Scope**. Obtains the union set of this **Scope** and the given **Scope**.
...@@ -1510,7 +1511,7 @@ Decodes the input content. ...@@ -1510,7 +1511,7 @@ Decodes the input content.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| src | Uint8Array&nbsp;\|&nbsp;string | Yes| Uint8Array or string to decode.| | src | Uint8Array \| string | Yes| Uint8Array or string to decode.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1595,7 +1596,7 @@ Decodes the input content asynchronously. ...@@ -1595,7 +1596,7 @@ Decodes the input content asynchronously.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| src | Uint8Array&nbsp;\|&nbsp;string | Yes| Uint8Array or string to decode asynchronously.| | src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1622,7 +1623,7 @@ Decodes the input content asynchronously. ...@@ -1622,7 +1623,7 @@ Decodes the input content asynchronously.
constructor() constructor()
A constructor used to create a **types** object. A constructor used to create a **Types** object.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
......
...@@ -319,10 +319,10 @@ vector.add(2); ...@@ -319,10 +319,10 @@ vector.add(2);
vector.add(4); vector.add(4);
vector.add(5); vector.add(5);
vector.add(4); vector.add(4);
vector.replaceAllElements((value, index) => { vector.replaceAllElements((value: number, index: number) => {
return value = 2 * value; return value = 2 * value;
}); });
vector.replaceAllElements((value, index) => { vector.replaceAllElements((value: number, index: number) => {
return value = value - 2; return value = value - 2;
}); });
``` ```
...@@ -394,8 +394,8 @@ vector.add(2); ...@@ -394,8 +394,8 @@ vector.add(2);
vector.add(4); vector.add(4);
vector.add(5); vector.add(5);
vector.add(4); vector.add(4);
vector.sort((a, b) => a - b); vector.sort((a: number, b: number) => a - b);
vector.sort((a, b) => b - a); vector.sort((a: number, b: number) => b - a);
vector.sort(); vector.sort();
``` ```
...@@ -620,7 +620,7 @@ vector.add(2); ...@@ -620,7 +620,7 @@ vector.add(2);
vector.add(4); vector.add(4);
vector.add(5); vector.add(5);
vector.add(4); vector.add(4);
let result = vector.toSting(); let result = vector.toString();
``` ```
### copyToArray ### copyToArray
......
# XML Parsing and Generation # XML Parsing and Generation
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -10,10 +11,6 @@ ...@@ -10,10 +11,6 @@
import xml from '@ohos.xml'; import xml from '@ohos.xml';
``` ```
## System Capabilities
SystemCapability.Utils.Lang
## XmlSerializer ## XmlSerializer
...@@ -23,11 +20,13 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string) ...@@ -23,11 +20,13 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string)
A constructor used to create an **XmlSerializer** instance. A constructor used to create an **XmlSerializer** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | Yes| **ArrayBuffer** or **DataView** for storing the XML information to write.| | buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** for storing the XML information to write.|
| encoding | string | No| Encoding format.| | encoding | string | No| Encoding format.|
**Example** **Example**
...@@ -45,6 +44,8 @@ setAttributes(name: string, value: string): void ...@@ -45,6 +44,8 @@ setAttributes(name: string, value: string): void
Sets an attribute. Sets an attribute.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -55,6 +56,8 @@ Sets an attribute. ...@@ -55,6 +56,8 @@ Sets an attribute.
**Example** **Example**
```js ```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView); var thatSer = new xml.XmlSerializer(bufView);
thatSer.setAttributes("importance", "high"); thatSer.setAttributes("importance", "high");
``` ```
...@@ -66,6 +69,8 @@ addEmptyElement(name: string): void ...@@ -66,6 +69,8 @@ addEmptyElement(name: string): void
Adds an empty element. Adds an empty element.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -75,6 +80,8 @@ Adds an empty element. ...@@ -75,6 +80,8 @@ Adds an empty element.
**Example** **Example**
```js ```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView); var thatSer = new xml.XmlSerializer(bufView);
thatSer.addEmptyElement("b"); // => <b/> thatSer.addEmptyElement("b"); // => <b/>
``` ```
...@@ -86,9 +93,13 @@ setDeclaration(): void ...@@ -86,9 +93,13 @@ setDeclaration(): void
Sets a declaration. Sets a declaration.
**System capability**: SystemCapability.Utils.Lang
**Example** **Example**
```js ```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView); var thatSer = new xml.XmlSerializer(bufView);
thatSer.setDeclaration() // => <?xml version="1.0" encoding="utf-8"?>; thatSer.setDeclaration() // => <?xml version="1.0" encoding="utf-8"?>;
``` ```
...@@ -100,6 +111,8 @@ startElement(name: string): void ...@@ -100,6 +111,8 @@ startElement(name: string): void
Writes the start tag based on the given element name. Writes the start tag based on the given element name.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -122,9 +135,13 @@ endElement(): void ...@@ -122,9 +135,13 @@ endElement(): void
Writes the end tag of the element. Writes the end tag of the element.
**System capability**: SystemCapability.Utils.Lang
**Example** **Example**
```js ```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView); var thatSer = new xml.XmlSerializer(bufView);
thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/");
thatSer.startElement("table"); thatSer.startElement("table");
...@@ -140,6 +157,8 @@ setNamespace(prefix: string, namespace: string): void ...@@ -140,6 +157,8 @@ setNamespace(prefix: string, namespace: string): void
Sets the namespace for an element tag. Sets the namespace for an element tag.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -164,6 +183,8 @@ setComment(text: string): void ...@@ -164,6 +183,8 @@ setComment(text: string): void
Sets the comment. Sets the comment.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -187,6 +208,8 @@ setCDATA(text: string): void ...@@ -187,6 +208,8 @@ setCDATA(text: string): void
Sets CDATA attributes. Sets CDATA attributes.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -208,6 +231,8 @@ setText(text: string): void ...@@ -208,6 +231,8 @@ setText(text: string): void
Sets **Text**. Sets **Text**.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -232,6 +257,8 @@ setDocType(text: string): void ...@@ -232,6 +257,8 @@ setDocType(text: string): void
Sets **DocType**. Sets **DocType**.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -256,11 +283,13 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string) ...@@ -256,11 +283,13 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string)
Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default). Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format (UTF-8 by default).
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | Yes| **ArrayBuffer** or **DataView** that contains XML text information.| | buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** that contains XML text information.|
| encoding | string | No| Encoding format. Only UTF-8 is supported.| | encoding | string | No| Encoding format. Only UTF-8 is supported.|
**Example** **Example**
...@@ -289,6 +318,8 @@ parse(option: ParseOptions): void ...@@ -289,6 +318,8 @@ parse(option: ParseOptions): void
Parses XML information. Parses XML information.
**System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -329,14 +360,16 @@ that.parse(options); ...@@ -329,14 +360,16 @@ that.parse(options);
Defines the XML parsing options. Defines the XML parsing options.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.| | supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.|
| ignoreNameSpace | boolean | No| Whether to ignore **Namespace**. The default value is **false**.| | ignoreNameSpace | boolean | No| Whether to ignore **Namespace**. The default value is **false**.|
| tagValueCallbackFunction | (name:&nbsp;string,&nbsp;value:&nbsp;string)=&gt;&nbsp;boolean | No| Callback used to return **tagValue**.| | tagValueCallbackFunction | (name: string, value: string)=&gt; boolean | No| Callback used to return **tagValue**.|
| attributeValueCallbackFunction | (name:&nbsp;string,&nbsp;value:&nbsp;string)=&gt;&nbsp;boolean | No| Callback used to return **attributeValue**.| | attributeValueCallbackFunction | (name: string, value: string)=&gt; boolean | No| Callback used to return **attributeValue**.|
| tokenValueCallbackFunction | (eventType:&nbsp;[EventType](#eventtype),&nbsp;value:&nbsp;[ParseInfo](#parseinfo))=&gt;&nbsp;boolean | No| Callback used to return **tokenValue**.| | tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=&gt; boolean | No| Callback used to return **tokenValue**.|
## ParseInfo ## ParseInfo
...@@ -349,6 +382,8 @@ getColumnNumber(): number ...@@ -349,6 +382,8 @@ getColumnNumber(): number
Obtains the column line number, which starts from 1. Obtains the column line number, which starts from 1.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -362,6 +397,8 @@ getDepth(): number ...@@ -362,6 +397,8 @@ getDepth(): number
Obtains the depth of this element. Obtains the depth of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -375,6 +412,8 @@ getLineNumber(): number ...@@ -375,6 +412,8 @@ getLineNumber(): number
Obtains the current line number, starting from 1. Obtains the current line number, starting from 1.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -388,6 +427,8 @@ getName(): string ...@@ -388,6 +427,8 @@ getName(): string
Obtains the name of this element. Obtains the name of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -401,6 +442,8 @@ getNamespace(): string ...@@ -401,6 +442,8 @@ getNamespace(): string
Obtains the namespace of this element. Obtains the namespace of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -414,6 +457,8 @@ getPrefix(): string ...@@ -414,6 +457,8 @@ getPrefix(): string
Obtains the prefix of this element. Obtains the prefix of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -427,6 +472,8 @@ getText(): string ...@@ -427,6 +472,8 @@ getText(): string
Obtains the text of the current event. Obtains the text of the current event.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -440,6 +487,8 @@ isEmptyElementTag(): boolean ...@@ -440,6 +487,8 @@ isEmptyElementTag(): boolean
Checks whether the current element is empty. Checks whether the current element is empty.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -453,6 +502,8 @@ isWhitespace(): boolean ...@@ -453,6 +502,8 @@ isWhitespace(): boolean
Checks whether the current text event contains only whitespace characters. Checks whether the current text event contains only whitespace characters.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -466,6 +517,8 @@ getAttributeCount(): number ...@@ -466,6 +517,8 @@ getAttributeCount(): number
Obtains the number of attributes for the current start tag. Obtains the number of attributes for the current start tag.
**System capability**: SystemCapability.Utils.Lang
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
...@@ -476,6 +529,8 @@ Obtains the number of attributes for the current start tag. ...@@ -476,6 +529,8 @@ Obtains the number of attributes for the current start tag.
Enumerates the events. Enumerates the events.
**System capability**: SystemCapability.Utils.Lang
| Name| Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| START_DOCUMENT | 0 | Indicates a start document event.| | START_DOCUMENT | 0 | Indicates a start document event.|
......
# Universal Events # Universal Events
> **NOTE**<br>
> Universal events are supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Event Description ## Event Description
- Events are bound to components. When a component meets the event triggering condition, the corresponding event callback in the JS is executed to implement the interaction between the UI and the JS logic layer of the page. - Events are bound to components. When a component meets the event triggering condition, the corresponding event callback in the JS is executed to implement the interaction between the UI and the JS logic layer of the page.
- The event callback can carry additional information through parameters, such as the dataset on the component and event-specific callback parameters. - The event callback can carry additional information through parameters, such as the dataset on the component and event-specific callback parameters.
Different from private events, universal events can be bound to most components.
Different from private events, universal events can be bound to most components.
| Name | Parameter | Description | Support Bubbling | | Name | Parameter | Description | Support Bubbling |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- | | ------------------------ | ---------- | ---------------------------------------- | ---------------------------------------- |
| touchstart | [TouchEvent](js-components-common-events.md) | Triggered when the tapping starts. | Yes<sup>5+</sup> | | touchstart | TouchEvent | Triggered when the tapping starts. For details about **TouchEvent**, see Table 2. | Yes<sup>5+</sup> |
| touchmove | [TouchEvent](js-components-common-events.md) | Triggered when the tapping moves. | Yes<sup>5+</sup> | | touchmove | TouchEvent | Triggered when the tapping moves. | Yes<sup>5+</sup> |
| touchcancel | [TouchEvent](js-components-common-events.md) | Triggered when the tapping is interrupted. | Yes<sup>5+</sup> | | touchcancel | TouchEvent | Triggered when the tapping is interrupted. | Yes<sup>5+</sup> |
| touchend | [TouchEvent](js-components-common-events.md) | Triggered when the tapping ends. | Yes<sup>5+</sup> | | touchend | TouchEvent | Triggered when the tapping ends. | Yes<sup>5+</sup> |
| click | - | Triggered when a component is clicked. | Yes<sup>6+</sup> | | click | - | Triggered when a component is clicked. | Yes<sup>6+</sup> |
| doubleclick<sup>7+</sup> | | Triggered when a component is double-clicked. | No | | doubleclick<sup>7+</sup> | - | Triggered when a component is double-clicked. | No<br>Bubbling is supported since API version 9. |
| longpress | - | Triggered when a component is long pressed. | No | | longpress | - | Triggered when a component is long pressed. | No<br>Bubbling is supported since API version 9.|
| swipe<sup>5+</sup> | [SwipeEvent](js-components-common-events.md#table111811577714) | Triggered when a user quickly swipes on a component. | No | | swipe<sup>5+</sup> | SwipeEvent | Triggered when a user quickly swipes on a component.<br/>For details about **SwipeEvent**, see Table 4. | No<br>Bubbling is supported since API version 9.|
| attached<sup>6+</sup> | - | Triggered after the current component node is mounted to the render tree. | No | | attached<sup>6+</sup> | - | Triggered after the current component node is mounted to the render tree. | No |
| detached<sup>6+</sup> | - | Triggered when the current component node is removed from the render tree. | No | | detached<sup>6+</sup> | - | Triggered when the current component node is removed from the render tree. | No |
| pinchstart<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when a pinch operation is started. | No | | pinchstart<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is started.<br>For details about **PinchEvent**, see Table 5.| No |
| pinchupdate<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when a pinch operation is in progress. | No | | pinchupdate<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is in progress. | No |
| pinchend<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when a pinch operation is ended. | No | | pinchend<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is ended. | No |
| pinchcancel<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when the pinch operation is interrupted. | No | | pinchcancel<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is interrupted. | No |
| dragstart<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when dragging starts. | No | | dragstart<sup>7+</sup> | DragEvent | Triggered when dragging starts.<br>For details about **DragEvent**, see Table 6. | No |
| drag<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when dragging is in progress. | No | | drag<sup>7+</sup> | DragEvent | Triggered when dragging is in progress. | No |
| dragend<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when dragging is ended. | No | | dragend<sup>7+</sup> | DragEvent | Triggered when dragging is ended. | No |
| dragenter<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when the dragged component enters a drop target. | No | | dragenter<sup>7+</sup> | DragEvent | Triggered when the dragged component enters a drop target. | No |
| dragover<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when the dragged component is being dragged over a drop target. | No | | dragover<sup>7+</sup> | DragEvent | Triggered when the dragged component is being dragged over a drop target. | No |
| dragleave<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when the dragged component leaves a drop target. | No | | dragleave<sup>7+</sup> | DragEvent | Triggered when the dragged component leaves a drop target. | No |
| drop<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when a component is dropped on a drop target. | No | | drop<sup>7+</sup> | DragEvent | Triggered when the dragged component is dropped on a drop target. | No |
> ![img](public_sys-resources/icon-note.gif) **NOTE:** Events not listed in the preceding table are non-bubbling events, such as the [change event](js-components-basic-input.md). For details, see the specific component.
**Table 1** Attributes of the BaseEvent object
> **NOTE**<br>
> Events not listed in the preceding table do not support bubbling, such as the [change event](../arkui-js/js-components-basic-input.md#events) of the **<input\>** component. For details, see the description of the specific component.
**Table 1** BaseEvent
| Attribute | Type | Description | | Attribute | Type | Description |
| --------- | ------ | ----------------------------------------------- | | --------------------- | -------------------- | --------------------------- |
| type | string | Event type, such as **click** and **longpress** | | type | string | Event type, such as **click** and **longpress**.|
| timestamp | number | Timestamp when the event is triggered | | timestamp | number | Timestamp when the event is triggered. |
| deviceId<sup>6+</sup> | number | ID of the device that triggers the event. |
**Table 2** Attributes of the TouchEvent object (inherited from BaseEvent) | target<sup>6+</sup> | [Target](#target6)| Target object that triggers the event. |
**Table 2** TouchEvent (inherited from BaseEvent)
| Attribute | Type | Description | | Attribute | Type | Description |
| -------------- | ----------------- | ------------------------------------------------------------ | | -------------- | ---------------------- | ---------------------------------------- |
| touches | Array\<TouchInfo> | Attribute set of the touch event, including the information array of the touch points on the screen. | | touches | Array&lt;TouchInfo&gt; | Attribute set of the touch event, including the information array of the touch points on the screen. |
| changedTouches | Array\<TouchInfo> | Attribute set when a touch event occurs, including the information array of changed touch points on the screen. **changedTouches** has the same data format as **touches** and indicates touch point changes, such as from no touch point to newly generated touch points, from some touch points to no touch point, and location changes. For example, when the user's finger leaves the touchscreen, no data exists in the **touches** array, but **changedTouches** will save the generated data. | | changedTouches | Array&lt;TouchInfo&gt; | Attribute set when a touch event occurs, including the information array of changed touch points on the screen. **changedTouches** has the same data format as **touches** and indicates touch point changes, including changes in the number and location of touch points. For example, when the user's finger leaves the screen, which means that the number of touch points changes from 1 to 0, **changedTouches** has the relevant data generated, but not **touches**.|
**Table 3** TouchInfo **Table 3** TouchInfo
| Attribute | Type | Description | | Attribute | Type | Description |
| --------- | ------ | ------------------------------------------------------------ | | ------------------ | ------ | ------------------------------ |
| globalX | number | Horizontal distance from the upper left corner of the screen (excluding the status bar). The upper left corner of the screen acts as the coordinate origin. | | globalX | number | Horizontal distance from the upper left corner of the screen (excluding the status bar), which acts as the origin of coordinates.|
| globalY | number | Vertical distance from the upper left corner of the screen (excluding the status bar). The upper left corner of the screen acts as the coordinate origin. | | globalY | number | Vertical distance from the upper left corner of the screen (excluding the status bar), which acts as the origin of coordinates.|
| localX | number | Horizontal distance from the upper left corner of the touched component. The upper left corner of the component acts as the coordinate origin. | | localX | number | Horizontal distance from the upper left corner of the touched component, which acts as the origin of coordinates. |
| localY | number | Vertical distance from the upper left corner of the touched component. The upper left corner of the component acts as the coordinate origin. | | localY | number | Vertical distance from the upper left corner of the touched component, which acts as the origin of coordinates. |
| size | number | Touch area. | | size | number | Touch area. |
| force<sup>6+</sup> | number | Touch force. | | force<sup>6+</sup> | number | Touch force. |
**Table 4** Attributes of the SwipeEvent object (inherited from BaseEvent) **Table 4** SwipeEvent (inherited from BaseEvent)
| Attribute | Type | Description | | Attribute | Type | Description |
| ---------- | ------ | ------------------------------------------------------------ | | --------------------- | ------ | ---------------------------------------- |
| direction | string | Swiping direction. The value can be one of the following: <br>- **left**: Swipe from right to left <br>- **right**: Swipe from left to right <br>- **up**: Swipe upwards <br>- **down**: Swipe downwards | | direction | string | Swiping direction. The value can be one of the following:<br>- **left**: Swipe left.<br>- **right**: Swipe right.<br>- **up**: Swipe up.<br>- **down**: Swipe down.|
| distance<sup>6+</sup> | number | Swiping distance in the swiping direction. | | distance<sup>6+</sup> | number | Swiping distance in the swiping direction. |
**Table 5** Attributes of the PinchEvent object<sup>7+</sup> **Table 5** PinchEvent<sup>7+</sup>
| Attribute | Type | Description | | Attribute | Type | Description |
| ------------ | ------ | ---------------------------------------- | | ------------ | ------ | -------------- |
| scale | number | Scale factor. | | scale | number | Scale factor. |
| pinchCenterX | number | X-coordinate of the pinch center, in px. | | pinchCenterX | number | X-coordinate of the pinch center, in px.|
| pinchCenterY | number | Y-coordinate of the pinch center, in px. | | pinchCenterY | number | Y-coordinate of the pinch center, in px.|
**Table 6** Attributes of the DragEvent object (inherited from BaseEvent)<sup>7+</sup>
**Table 6** DragEvent<sup>7+</sup> (inherited from BaseEvent)
| Attribute | Type | Description | | Attribute | Type | Description |
| --------- | ------ | ------------------------------------------------------------ | | ------------------------- | -------------------------------- | ---------------- |
| type | string | Event name. | | type | string | Event name. |
| globalX | number | Horizontal distance from the origin of the coordinates in the upper left corner of the screen. | | globalX | number | Horizontal distance from the upper left corner of the screen, which acts as the origin of coordinates.|
| globalY | number | Vertical distance from the origin of the coordinates in the upper left corner of the screen. | | globalY | number | Vertical distance from the upper left corner of the screen, which acts as the origin of coordinates.|
| timestamp | number | Timestamp. | | timestamp | number | Timestamp. |
## Event Object ## Target<sup>6+</sup>
When a component triggers an event, the event callback receives an event object by default. You can obtain the corresponding information through the event object. When a component triggers an event, the event callback receives an event object by default. You can obtain the corresponding information through the event object.
**target object:**
| Attribute | Type | Description | | Attribute | Type | Description |
| --------- | ------ | ------------------------------------------------------------ | | -------------------- | ------ | ---------------------------------------- |
| dataSet<sup>6+</sup> | Object | Custom attribute set defined through [data-*](js-components-common-attributes.md). | | dataSet<sup>6+</sup> | Object | Custom attribute set defined through [data-*](../arkui-js/js-components-common-attributes.md).|
**Example:** **Example**
``` ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div> <div>
<div data-a="dataA" data-b="dataB" <div data-a="dataA" data-b="dataB"
...@@ -118,7 +110,7 @@ When a component triggers an event, the event callback receives an event object ...@@ -118,7 +110,7 @@ When a component triggers an event, the event callback receives an event object
</div> </div>
``` ```
``` ```js
// xxx.js // xxx.js
export default { export default {
touchstartfunc(msg) { touchstartfunc(msg) {
...@@ -128,3 +120,5 @@ export default { ...@@ -128,3 +120,5 @@ export default {
} }
``` ```
...@@ -61,8 +61,6 @@ ...@@ -61,8 +61,6 @@
- [LoadingProgress](ts-basic-components-loadingprogress.md) - [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md) - [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md) - [Navigation](ts-basic-components-navigation.md)
- [PatternLock](ts-basic-components-patternlock.md)
- [PluginComponent](ts-basic-components-plugincomponent.md)
- [Progress](ts-basic-components-progress.md) - [Progress](ts-basic-components-progress.md)
- [QRCode](ts-basic-components-qrcode.md) - [QRCode](ts-basic-components-qrcode.md)
- [Radio](ts-basic-components-radio.md) - [Radio](ts-basic-components-radio.md)
...@@ -98,7 +96,6 @@ ...@@ -98,7 +96,6 @@
- [List](ts-container-list.md) - [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md) - [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md) - [Navigator](ts-container-navigator.md)
-
- [Panel](ts-container-panel.md) - [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md) - [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md) - [Row](ts-container-row.md)
......
# ImageAnimator # ImageAnimator
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;ImageAnimator&gt;** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured. The **\<ImageAnimator>** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured.
## Required Permissions ## Required Permissions
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -78,6 +78,7 @@ struct ImageAnimatorExample { ...@@ -78,6 +78,7 @@ struct ImageAnimatorExample {
ImageAnimator() ImageAnimator()
.images([ .images([
{ {
// The comment folder is at the same level as the pages folder.
src: '/comment/bg1.jpg', src: '/comment/bg1.jpg',
duration: 500, duration: 500,
width: 325, width: 325,
......
# Marquee # Marquee
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -34,7 +34,7 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boole ...@@ -34,7 +34,7 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boole
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.| | onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.|
| onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.| | onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.|
......
# PatternLock
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<PatternLock>** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen.
## Required Permissions
None
## Child Components
None
## APIs
PatternLock(controller?: PatternLockController)
- Parameters
| Name | Type | Mandatory| Default Value| Description |
| ---------- | ----------------------------------------------- | ---- | ------ | -------------------------------------------- |
| controller | [PatternLockController](#patternlockcontroller) | No | null | Controller of a component to reset the component status.|
## Attributes
Except for **backgroundColor**, universal attributes are not supported.
| Name | Type | Default Value | Description |
| --------------- | --------------------------------------------------- | ----------- | ------------------------------------------------------------ |
| sideLength | Length | 300vp | Width and height (same value) of the component. The minimum value is **0**. |
| circleRadius | Length | 14vp | Radius of a grid dot. |
| regularColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in unselected state. |
| selectedColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in selected state. |
| activeColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in active state. |
| pathColor | [ResourceColor](../../ui/ts-types.md) | Color.Blue | Path color. |
| pathStrokeWidth | Length | 34vp | Width of the path stroke. The minimum value is **0**. |
| autoReset | boolean | true | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite. |
## Events
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onPatternComplete(callback: (input: Array\<number\>) => void) | Invoked when the pattern password input is complete.<br>**input** is an array of digits that represent the connected dots in the pattern (0 to 8) and are arranged in the same sequence as the dots are connected.|
## PatternLockController
Controller bound to the **\<PatternLock>** component for resetting the component status.
### Objects to Import
```typescript
patternLockController: PatternLockController = new PatternLockController()
```
### reset
reset(): void
Resets the component status.
## Example
```typescript
@Entry
@Component
struct PatternLockExample {
@State passwords: Number[] = []
@State message: string = 'please input password'
private patternLockController: PatternLockController = new PatternLockController()
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text(this.message).textAlign(TextAlign.Center)
PatternLock(this.patternLockController)
.sideLength(150)
.circleRadius(7)
.pathStrokeWidth(17)
.backgroundColor(Color.White)
.autoReset(true)
.onPatternComplete((input: Array<number>) => {
if (input == null || input == undefined || input.length < 5) {
this.message = 'The password length needs to be greater than 5.'
return
}
if (this.passwords.length > 0) {
if (this.passwords.toString() == input.toString()) {
this.passwords = input
this.message = 'Set password successfully: ' + this.passwords.toString()
} else {
this.message = 'Inconsistent passwords, please enter again.'
}
} else {
this.passwords = input
this.message = "Please enter again."
}
})
Button('reset button').margin(30).onClick(() => {
this.patternLockController.reset()
this.passwords = []
this.message = 'Please input password'
})
}.width('100%').height('100%')
}
}
```
![patternlock](figures/patternlock.gif)
# PluginComponent
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The APIs of this module are system APIs and cannot be called by third-party applications.
**&lt;PluginComponent&gt;** allows the UI provided by an external application to be displayed in the application.
## Required Permissions
None
## Child Components
None
## APIs
PluginComponent(value: { template: PluginComponentTemplate, data: any })
Creates a **PluginComponent** to display the UI provided by an external application.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | {<br/>template: PluginComponentTemplate,<br/>data: KVObject<br/>} | Yes | - | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.<br/>**data**: data passed to the **PluginComponent** provider. |
- PluginComponentTemplate parameters
| Name | Type | Description |
| -------- | -------- | -------- |
| source | string | Component template name. |
| ability | string | Name of the provider ability. |
## Events
| Name | Description |
| -------- | -------- |
| onComplete(callback: () =&gt; void) | Triggered when the component loading is complete. |
| onError(callback: (info: { errcode: number, msg: string }) =&gt; void) | Triggered when an error occurs during component loading.<br/>**errcode**: error code.<br/>**msg**: error information. |
## PluginComponentManager
Provides APIs for the **PluginComponent**. You can use these APIs to request components and data and send component templates and data.
## Modules to Import
```
import pluginComponentManager from '@ohos.plugincomponent'
```
## Required Permissions
None
## push
push(param: PushParameters, callback: AsyncCallback&lt;void&gt;): void
Used by the component provider to send the component and data to the component consumer.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| param | PushParameters | Yes | Information about the component consumer. For details, see description of PushParameters. |
| callback | AsyncCallback&lt;void&gt; | Yes | Asynchronous callback used to return the result. |
- Description of PushParameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| want | Want | Yes | Ability information of the component consumer. |
| name | string | Yes | Component name. |
| data | KVObject | No | Component data value. |
| extraData | KVObject | No | Additional data value. |
- Example
For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers).
## request
request(param: RequestParameters, callback: AsyncCallback&lt;RequestCallbackParameters&gt;): void
Used by the component consumer to request the component from the component provider.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| param | RequestParameters | Yes | Information about the component request. For details, see  description of RequestParameters. |
| callback | AsyncCallback<RequestCallbackParameters \| void&gt; | | Asynchronous callback used to return the requested data. |
- Description of RequestParameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| want | Want | Yes | Ability information of the component provider. |
| name | string | Yes | Name of the requested component. |
| data | KVObject | Yes | Additional data. |
- Description of RequestCallbackParameters
| Name | Type | Description |
| -------- | -------- | -------- |
| componentTemplate | PluginComponentTemplate | Component template. |
| data | KVObject | Component data. |
| extraData | KVObject | Additional data. |
- Description of KVObject
| Name | Type | Description |
| -------- | -------- | -------- |
| key | number \| string \| boolean \| Array \| KVObject | **KVObject** uses **key** and **value** to store data. **key** is of the string type, and **value** can be of the number, string, boolean, array type or another **KVObject**. |
- Example
For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers).
## on
on(eventType: string, callback: OnPushEventCallback | OnRequestEventCallback): void
Listens for events of the request type and returns the requested data, or listens for events of the push type and receives the data pushed by the provider.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| eventType | string | Yes | Type of the event to listen for. The options are **"push"** and **"request"**.<br/>**"push"**: The component provider pushes data to the component consumer.<br/>**"request"**: The component consumer proactively requests data from the component provider. |
| callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see description of callback. |
- Description of callback
| Name | Type | Description |
| -------- | -------- | -------- |
| OnRequestEventCallback | (source: Want,<br/>name: string,<br/>data: KVObject ) =>RequestEventResult | Callback for the data request event.<br/>**source**: ability information of the component requester.<br/>**name**: name of the requested component.<br/>**data**: additional data.<br/>Return value: request data and result. |
| OnPushEventCallback | (source: Want,<br/>template: PluginComponentTemplate,<br/>data: KVObject,<br/>extraData: KVObject<br/>) =&gt; void | Callback used to receive the data pushed by the component provider.<br/>**source**: ability information of the component provider.<br/>**template**: component template.<br/>**data**: component update data.<br/>**extraData**: additional data. |
- Description of RequestEventResult
| Name | Type | Description |
| -------- | -------- | -------- |
| template | string | Component name. |
| data | KVObject | Component data. |
| extraData | KVObject | Additional data. |
- Example
For details, see [APIs Called by Component Consumers](#apis-called-by-component-consumers).
## Example
### Using the PluginComponent
```
import plugin from "../../test/plugin_component.js"
import plugincomponent from '@ohos.plugincomponent'
@Entry
@Component
struct PluginComponentExample {
@StorageLink("plugincount") plugincount: Object[] = [
{ source: 'plugincomponent1', ability: 'com.example.plugin' },
{ source: 'plugintemplate', ability: 'com.example.myapplication' },
{ source: 'plugintemplate', ability: 'com.example.myapplication' }]
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('Push')
.fontSize(50)
.width(400)
.height(100)
.onClick(() => {
plugin.Push()
console.log("Button('Push')")
})
.margin({ top: 20 })
Button('Request1')
.fontSize(50)
.width(400)
.height(100)
.margin({ top: 20 })
.onClick(() => {
plugin.Request1()
console.log("Button('Request1')")
})
Button('Request2')
.fontSize(50)
.width(400)
.height(100)
.margin({ top: 20 })
.onClick(() => {
plugin.Request2()
console.log("Button('Request2')")
})
ForEach(this.plugincount, item => {
PluginComponent({
template: { source: 'plugincomponent1', ability: 'com.example.plugin' },
data: { 'countDownStartValue': 'new countDownStartValue' }
}).size({ width: 500, height: 100 })
.onComplete(() => {
console.log("onComplete")
})
.onError(({errcode, msg}) => {
console.log("onComplete" + errcode + ":" + msg)
})
})
}
.width('100%')
.height('100%')
}
```
### APIs Called by Component Consumers
```
import pluginComponentManager from '@ohos.plugincomponent'
function onPushListener(source, template, data, extraData) {
console.log("onPushListener template.source=" + template.source)
var jsonObject = JSON.parse(data.componentTemplate.source)
console.log("request_callback1:source json object" + jsonObject)
var jsonArry = jsonObject.ExternalComponent
for (var i in jsonArry) {
console.log(jsonArry[i])
}
console.log("onPushListener:source json object" + jsonObject)
console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
console.log("onPushListener template.ability=" + template.ability)
console.log("onPushListener data=" + JSON.stringify(data))
console.log("onPushListener extraData=" + JSON.stringify(extraData))
}
export default {
//register listener
onListener() {
pluginComponentManager.on("push", onPushListener)
},
Request() {
//The component consumer proactively sends data.
pluginComponentManager.request({
want: {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
},
name: "plugintemplate",
data: {
"key_1": "plugin component test",
"key_2": 34234
},
jsonPath: "assets/js",
},
(err, data) => {
console.log("request_callback1: componentTemplate.ability=" + data.componentTemplate.ability)
console.log("request_callback1: componentTemplate.source=" + data.componentTemplate.source)
var jsonObject = JSON.parse(data.componentTemplate.source)
console.log("request_callback1:source json object" + jsonObject)
var jsonArry = jsonObject.ExternalComponent
for (var i in jsonArry) {
console.log(jsonArry[i])
}
console.log("request_callback1:source json string" + JSON.stringify(jsonObject))
console.log("request_callback1: data=" + JSON.stringify(data.data))
console.log("request_callback1: extraData=" + JSON.stringify(data.extraData))
}
)
}
}
// Example of the component provider using the API
import pluginComponentManager from '@ohos.plugincomponent'
function onRequestListener(source, name, data) {
console.log("onRequestListener name=" + name)
console.log("onRequestListener data=" + JSON.stringify(data))
return { template: "plugintemplate", data: data }
}
export default {
//register listener
onListener() {
pluginComponentManager.on("request", onRequestListener)
},
Push() {
// The component provider proactively sends data.
pluginComponentManager.push(
{
want: {
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
},
name: "plugintemplate",
data: {
"key_1": "plugin component test",
"key_2": 34234
},
extraData: {
"extra_str": "this is push event"
},
jsonPath: "assets/js",
},
(err, data) => {
console.log("push_callback1: componentTemplate.ability=" + data.componentTemplate.ability)
console.log("push_callback1: componentTemplate.source=" + data.componentTemplate.source)
console.log("push ok!")
}
)
},
}
```
# Toggle # Toggle
> **NOTE**<br>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -12,7 +11,7 @@ None ...@@ -12,7 +11,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -20,42 +19,43 @@ None ...@@ -20,42 +19,43 @@ None
Toggle(options: { type: ToggleType, isOn?: boolean }) Toggle(options: { type: ToggleType, isOn?: boolean })
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| type | ToggleType | Yes | - | Type of the toggle. | | type | ToggleType | Yes| - | Type of the toggle.|
| isOn | boolean | No | false | Initial state of the toggle.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> If **isOn** is not set during component creation, the selected state can be retained during component reuse. If **isOn** is set, the selected state needs to be retained during component reuse after the selected state is recorded using an event method. | | isOn | boolean | No| false | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.|
- ToggleType enums - ToggleType enums
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| Checkbox | A checkbox is provided. The text setting of the child component does not take effect. If the text setting is required, you can place the **&lt;Text&gt;** component and the current component in the layout component. | | Checkbox | A checkbox is provided, where the **\<Text>** settings can take effect only when it is placed with the current component in a layout component.<br>> **NOTE**<br><br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br>&nbsp;top: 14 vp,<br>&nbsp;right: 6 vp,<br>&nbsp;bottom: 14 vp,<br>&nbsp;left: 6 vp<br> } |
| Button | A button is provided. If the text setting is available, the corresponding text content is displayed inside the button. | | Button | A button is provided. The set text string, if any, will be displayed inside the button.|
| Switch | A switch is provided. The text setting of the child component does not take effect. If the text setting is required, you can place the **&lt;Text&gt;** component and the current component in the layout component. | | Switch | A switch is provided, where the **\<Text>** settings can take effect only when it is placed with the current component in a layout component.<br>> **NOTE**<br><br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br>&nbsp;top: 12 vp,<br>&nbsp;right: 12 vp,<br>&nbsp;bottom: 12 vp,<br>&nbsp;left: 12 vp<br> } |
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Parameter| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| selectedColor | Color | - | Background color of the toggle when it is enabled. | | selectedColor | Color | - | Background color of the component when it is turned on.|
| switchPointColor | Color | - | Color of the circular slider of the **Switch** type.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> This attribute is valid only when type is set to **ToggleType.Switch**. | | switchPointColor | Color | - | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**. |
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (isOn: boolean) =&gt; void) | Triggered when the switch status changes. | | onChange(callback:&nbsp;(isOn:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) | Triggered when the toggle status changes.|
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct ToggleExample { struct ToggleExample {
build() { build() {
Column({ space: 10 }) { Column({ space: 10 }) {
Text('type: Switch').fontSize(12).fontColor(0xcccccc).width('90%') Text('type: Switch').fontSize(12).fontColor(0xcccccc).width('90%')
......
# OffscreenCanvasRenderingContext2D # OffscreenCanvasRenderingContext2D
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency. Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency.
...@@ -44,14 +42,15 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render ...@@ -44,14 +42,15 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. |
| imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. | | imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> The value of the **&lt;color&gt;** type can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format. > The value of the **&lt;color&gt;** type can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format.
### fillStyle ### fillStyle
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillStyleExample { struct FillStyleExample {
...@@ -84,7 +83,8 @@ struct FillStyleExample { ...@@ -84,7 +83,8 @@ struct FillStyleExample {
### lineWidth ### lineWidth
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineWidthExample { struct LineWidthExample {
...@@ -117,7 +117,8 @@ struct LineWidthExample { ...@@ -117,7 +117,8 @@ struct LineWidthExample {
### strokeStyle ### strokeStyle
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StrokeStyleExample { struct StrokeStyleExample {
...@@ -152,7 +153,8 @@ struct StrokeStyleExample { ...@@ -152,7 +153,8 @@ struct StrokeStyleExample {
### lineCap ### lineCap
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineCapExample { struct LineCapExample {
...@@ -189,7 +191,8 @@ struct LineCapExample { ...@@ -189,7 +191,8 @@ struct LineCapExample {
### lineJoin ### lineJoin
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineJoinExample { struct LineJoinExample {
...@@ -227,7 +230,8 @@ struct LineJoinExample { ...@@ -227,7 +230,8 @@ struct LineJoinExample {
### miterLimit ### miterLimit
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MiterLimit { struct MiterLimit {
...@@ -265,7 +269,8 @@ struct MiterLimit { ...@@ -265,7 +269,8 @@ struct MiterLimit {
### font ### font
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Font { struct Font {
...@@ -298,7 +303,8 @@ struct Font { ...@@ -298,7 +303,8 @@ struct Font {
### textAlign ### textAlign
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -346,7 +352,8 @@ struct CanvasExample { ...@@ -346,7 +352,8 @@ struct CanvasExample {
### textBaseline ### textBaseline
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct TextBaseline { struct TextBaseline {
...@@ -394,7 +401,8 @@ struct TextBaseline { ...@@ -394,7 +401,8 @@ struct TextBaseline {
### globalAlpha ### globalAlpha
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct GlobalAlpha { struct GlobalAlpha {
...@@ -430,7 +438,8 @@ struct GlobalAlpha { ...@@ -430,7 +438,8 @@ struct GlobalAlpha {
### lineDashOffset ### lineDashOffset
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineDashOffset { struct LineDashOffset {
...@@ -478,7 +487,8 @@ struct LineDashOffset { ...@@ -478,7 +487,8 @@ struct LineDashOffset {
| xor | Combines the new drawing and existing drawing using the XOR operation. | | xor | Combines the new drawing and existing drawing using the XOR operation. |
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct GlobalCompositeOperation { struct GlobalCompositeOperation {
...@@ -519,7 +529,8 @@ struct GlobalCompositeOperation { ...@@ -519,7 +529,8 @@ struct GlobalCompositeOperation {
### shadowBlur ### shadowBlur
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ShadowBlur { struct ShadowBlur {
...@@ -554,7 +565,8 @@ struct ShadowBlur { ...@@ -554,7 +565,8 @@ struct ShadowBlur {
### shadowColor ### shadowColor
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ShadowColor { struct ShadowColor {
...@@ -590,7 +602,8 @@ struct ShadowColor { ...@@ -590,7 +602,8 @@ struct ShadowColor {
### shadowOffsetX ### shadowOffsetX
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ShadowOffsetX { struct ShadowOffsetX {
...@@ -626,7 +639,8 @@ struct ShadowOffsetX { ...@@ -626,7 +639,8 @@ struct ShadowOffsetX {
### shadowOffsetY ### shadowOffsetY
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ShadowOffsetY { struct ShadowOffsetY {
...@@ -662,7 +676,8 @@ struct ShadowOffsetY { ...@@ -662,7 +676,8 @@ struct ShadowOffsetY {
### imageSmoothingEnabled ### imageSmoothingEnabled
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ImageSmoothingEnabled { struct ImageSmoothingEnabled {
...@@ -712,7 +727,8 @@ Fills a rectangle on the canvas. ...@@ -712,7 +727,8 @@ Fills a rectangle on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillRect { struct FillRect {
...@@ -801,7 +817,8 @@ Clears the content in a rectangle on the canvas. ...@@ -801,7 +817,8 @@ Clears the content in a rectangle on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClearRect { struct ClearRect {
...@@ -846,7 +863,8 @@ Draws filled text on the canvas. ...@@ -846,7 +863,8 @@ Draws filled text on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillText { struct FillText {
...@@ -942,7 +960,8 @@ Returns a **TextMetrics** object used to obtain the width of specified text. ...@@ -942,7 +960,8 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MeasureText { struct MeasureText {
...@@ -1024,7 +1043,8 @@ Creates a drawing path. ...@@ -1024,7 +1043,8 @@ Creates a drawing path.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BeginPath { struct BeginPath {
...@@ -1071,7 +1091,8 @@ Moves a drawing path to a target position on the canvas. ...@@ -1071,7 +1091,8 @@ Moves a drawing path to a target position on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
...@@ -1116,7 +1137,8 @@ Connects the current point to a target position using a straight line. ...@@ -1116,7 +1137,8 @@ Connects the current point to a target position using a straight line.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
...@@ -1155,7 +1177,8 @@ Draws a closed path. ...@@ -1155,7 +1177,8 @@ Draws a closed path.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
...@@ -1202,7 +1225,8 @@ Creates a pattern for image filling based on a specified source image and repeti ...@@ -1202,7 +1225,8 @@ Creates a pattern for image filling based on a specified source image and repeti
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreatePattern { struct CreatePattern {
...@@ -1251,7 +1275,8 @@ Draws a cubic bezier curve on the canvas. ...@@ -1251,7 +1275,8 @@ Draws a cubic bezier curve on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
...@@ -1298,7 +1323,8 @@ Draws a quadratic curve on the canvas. ...@@ -1298,7 +1323,8 @@ Draws a quadratic curve on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
...@@ -1347,7 +1373,8 @@ Draws an arc on the canvas. ...@@ -1347,7 +1373,8 @@ Draws an arc on the canvas.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
...@@ -1394,7 +1421,8 @@ Draws an arc based on the radius and points on the arc. ...@@ -1394,7 +1421,8 @@ Draws an arc based on the radius and points on the arc.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
...@@ -1445,7 +1473,8 @@ Draws an ellipse in the specified rectangular region. ...@@ -1445,7 +1473,8 @@ Draws an ellipse in the specified rectangular region.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -1491,7 +1520,8 @@ Creates a rectangle. ...@@ -1491,7 +1520,8 @@ Creates a rectangle.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -1528,7 +1558,8 @@ Fills the area inside a closed path. ...@@ -1528,7 +1558,8 @@ Fills the area inside a closed path.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Fill { struct Fill {
...@@ -1565,7 +1596,8 @@ Sets the current path to a clipping path. ...@@ -1565,7 +1596,8 @@ Sets the current path to a clipping path.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Clip { struct Clip {
...@@ -1610,7 +1642,8 @@ Rotates a canvas clockwise around its coordinate axes. ...@@ -1610,7 +1642,8 @@ Rotates a canvas clockwise around its coordinate axes.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Rotate { struct Rotate {
...@@ -1653,7 +1686,8 @@ Scales a canvas based on scale factors. ...@@ -1653,7 +1686,8 @@ Scales a canvas based on scale factors.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Scale { struct Scale {
...@@ -1689,7 +1723,7 @@ transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translat ...@@ -1689,7 +1723,7 @@ transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translat
Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
> >
> - x' = scaleX \* x + skewY \* y + translateX > - x' = scaleX \* x + skewY \* y + translateX
...@@ -1708,7 +1742,8 @@ Defines a transformation matrix. To transform a graph, you only need to set para ...@@ -1708,7 +1742,8 @@ Defines a transformation matrix. To transform a graph, you only need to set para
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Transform { struct Transform {
...@@ -1761,7 +1796,8 @@ Resets the existing transformation matrix and creates a new transformation matri ...@@ -1761,7 +1796,8 @@ Resets the existing transformation matrix and creates a new transformation matri
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct SetTransform { struct SetTransform {
...@@ -1807,7 +1843,8 @@ Moves the origin of the coordinate system. ...@@ -1807,7 +1843,8 @@ Moves the origin of the coordinate system.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
...@@ -1839,18 +1876,18 @@ Moves the origin of the coordinate system. ...@@ -1839,18 +1876,18 @@ Moves the origin of the coordinate system.
### drawImage ### drawImage
drawImage(image: ImageBitmap, dx: number, dy: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
drawImage(image: ImageBitmap, dx: number, dy: number, dWidth: number, dHeight: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dWidth: number, dHeight: number): void
drawImage(image: ImageBitmap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void
Draws an image. Draws an image.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- | | ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Image resource. For details, see ImageBitmap. | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7) | Yes | null | Image resource. For details, see ImageBitmap. |
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | | sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | | sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sWidth | number | No | 0 | Target width to crop the source image. | | sWidth | number | No | 0 | Target width to crop the source image. |
...@@ -1863,7 +1900,8 @@ Draws an image. ...@@ -1863,7 +1900,8 @@ Draws an image.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Index { struct Index {
...@@ -1916,12 +1954,24 @@ Creates an **ImageData** object by copying an existing **ImageData** object. For ...@@ -1916,12 +1954,24 @@ Creates an **ImageData** object by copying an existing **ImageData** object. For
| --------- | ---------------------------------------- | --------- | ------------- | ----------------------------- | | --------- | ---------------------------------------- | --------- | ------------- | ----------------------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy. | | imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy. |
### getPixelMap
getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area. |
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area. |
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
### getImageData ### getImageData
getImageData(sx: number, sy: number, sw: number, sh: number): Object getImageData(sx: number, sy: number, sw: number, sh: number): Object
Creates an [ImageData](ts-components-canvas-imagebitmap.md) object with pixels in the specified area on the canvas. Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
...@@ -1951,7 +2001,8 @@ Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular are ...@@ -1951,7 +2001,8 @@ Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular are
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct PutImageData { struct PutImageData {
...@@ -1994,7 +2045,8 @@ Restores the saved drawing context. ...@@ -1994,7 +2045,8 @@ Restores the saved drawing context.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -2028,7 +2080,8 @@ Saves the current drawing context. ...@@ -2028,7 +2080,8 @@ Saves the current drawing context.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -2070,7 +2123,8 @@ Creates a linear gradient. ...@@ -2070,7 +2123,8 @@ Creates a linear gradient.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateLinearGradient { struct CreateLinearGradient {
...@@ -2122,7 +2176,8 @@ Creates a linear gradient. ...@@ -2122,7 +2176,8 @@ Creates a linear gradient.
- Example - Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateRadialGradient { struct CreateRadialGradient {
......
# Image Effect Configuration # Image Effect Configuration
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -25,7 +25,7 @@ None ...@@ -25,7 +25,7 @@ None
| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. | | invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. |
| colorBlend <sup>8+</sup> | Color | - | Adds the color blend effect to the current component. The input parameter is the blended color. | | colorBlend <sup>8+</sup> | Color | - | Adds the color blend effect to the current component. The input parameter is the blended color. |
| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. | | sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. |
| hueRotate | Angle | 0deg | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. If the input value is **0deg**, the image does not change (because the default rotation angle is **0deg**). The input parameter does not have the maximum value. If the value exceeds **360deg**, the image is rotated one ore more circles. | | hueRotate | number \| string | '0deg' |Adds the hue rotation effect to the current component. The input parameter is a rotation angle. If the input value is **0deg**, the image does not change (because the default rotation angle is **0deg**). The input parameter does not have the maximum value. If the value exceeds **360deg**, the image is rotated for one more circle. In other words, the value **370deg** has the same effect as **10deg**.|
## Example ## Example
......
...@@ -462,8 +462,6 @@ ...@@ -462,8 +462,6 @@
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md) - [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.md) - [Marquee](reference/arkui-ts/ts-basic-components-marquee.md)
- [Navigation](reference/arkui-ts/ts-basic-components-navigation.md) - [Navigation](reference/arkui-ts/ts-basic-components-navigation.md)
- [PatternLock](reference/arkui-ts/ts-basic-components-patternlock.md)
- [PluginComponent](reference/arkui-ts/ts-basic-components-plugincomponent.md)
- [Progress](reference/arkui-ts/ts-basic-components-progress.md) - [Progress](reference/arkui-ts/ts-basic-components-progress.md)
- [QRCode](reference/arkui-ts/ts-basic-components-qrcode.md) - [QRCode](reference/arkui-ts/ts-basic-components-qrcode.md)
- [Radio](reference/arkui-ts/ts-basic-components-radio.md) - [Radio](reference/arkui-ts/ts-basic-components-radio.md)
......
...@@ -203,7 +203,7 @@ ...@@ -203,7 +203,7 @@
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db",} const STORE_CONFIG = {name: "rdbstore.db",}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE) rdbStore.executeSql(CREATE_TABLE_TEST )
console.info('create table done.') console.info('create table done.')
}) })
``` ```
......
...@@ -45,7 +45,7 @@ ...@@ -45,7 +45,7 @@
}); });
``` ```
参考接口API说明,应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。 参考接口API说明[位置服务](../reference/apis/js-apis-geolocation.md),应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。
- 调用getAddressesFromLocationName位置描述转化坐标。 - 调用getAddressesFromLocationName位置描述转化坐标。
``` ```
...@@ -55,6 +55,6 @@ ...@@ -55,6 +55,6 @@
}); });
``` ```
参考接口API说明,应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。 参考接口API说明[位置服务](../reference/apis/js-apis-geolocation.md),应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。
如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。 如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。
...@@ -24,7 +24,7 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js ...@@ -24,7 +24,7 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js
| setConfiguration(pipe:&nbsp;USBDevicePipe,&nbsp;config:&nbsp;USBConfig):&nbsp;number | 设置设备的配置。 | | setConfiguration(pipe:&nbsp;USBDevicePipe,&nbsp;config:&nbsp;USBConfig):&nbsp;number | 设置设备的配置。 |
| setInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface):&nbsp;number | 设置设备的接口。 | | setInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface):&nbsp;number | 设置设备的接口。 |
| claimInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface,&nbsp;force?:&nbsp;boolean):&nbsp;number | 获取接口。 | | claimInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface,&nbsp;force?:&nbsp;boolean):&nbsp;number | 获取接口。 |
| function&nbsp;bulkTransfer(pipe:&nbsp;USBDevicePipe,&nbsp;endpoint:&nbsp;USBEndpoint,&nbsp;buffer:&nbsp;Uint8Array,&nbsp;timeout?:&nbsp;number):&nbsp;Promise&lt;number&gt; | 批量传输。 | |bulkTransfer(pipe:&nbsp;USBDevicePipe,&nbsp;endpoint:&nbsp;USBEndpoint,&nbsp;buffer:&nbsp;Uint8Array,&nbsp;timeout?:&nbsp;number):&nbsp;Promise&lt;number&gt; | 批量传输。 |
| closePipe(pipe:&nbsp;USBDevicePipe):&nbsp;number | 关闭设备消息控制通道。 | | closePipe(pipe:&nbsp;USBDevicePipe):&nbsp;number | 关闭设备消息控制通道。 |
| releaseInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface):&nbsp;number | 释放接口。 | | releaseInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface):&nbsp;number | 释放接口。 |
| getFileDescriptor(pipe:&nbsp;USBDevicePipe):&nbsp;number | 获取文件描述符。 | | getFileDescriptor(pipe:&nbsp;USBDevicePipe):&nbsp;number | 获取文件描述符。 |
......
# DataAbility 谓词 # DataAbility 谓词
DataAbility 谓词用于构造关系型数据库的谓词,提供用于实现不同查询方法的谓词。
> **说明:** > **说明:**
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......
# 结果集 # 结果集
结果集是指用户调用关系型数据库查询接口之后返回的结果集合,提供了多种灵活的数据访问方式,以便用户获取各项数据。
> **说明:** > **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......
...@@ -144,6 +144,8 @@ queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback&lt;Bun ...@@ -144,6 +144,8 @@ queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback&lt;Bun
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -180,6 +182,8 @@ queryBundleStateInfos(begin: number, end: number): Promise&lt;BundleActiveInfoRe ...@@ -180,6 +182,8 @@ queryBundleStateInfos(begin: number, end: number): Promise&lt;BundleActiveInfoRe
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -219,6 +223,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num ...@@ -219,6 +223,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -254,6 +260,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num ...@@ -254,6 +260,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -292,6 +300,8 @@ queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback&lt;A ...@@ -292,6 +300,8 @@ queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback&lt;A
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -326,6 +336,8 @@ queryBundleActiveStates(begin: number, end: number): Promise&lt;Array&lt;BundleA ...@@ -326,6 +336,8 @@ queryBundleActiveStates(begin: number, end: number): Promise&lt;Array&lt;BundleA
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
...@@ -446,8 +458,6 @@ merge(toMerge: BundleStateInfo): void ...@@ -446,8 +458,6 @@ merge(toMerge: BundleStateInfo): void
合并相同包名的应用使用信息。 合并相同包名的应用使用信息。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**参数** **参数**
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册