提交 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
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.
- 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.
- 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.
- 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 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.
| Item | FA Model | Stage 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. |
| 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. |
| 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.|
| Intra-process object sharing| Not supported. | Supported. |
| 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). |
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).
## 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
An example command in the FA model is as follows:
```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:
```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 |
| --------------- | -------- | ------------------------------------------------------------ |
| -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. |
| -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. |
| -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.|
| -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.|
| -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 | **-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
......@@ -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).
## 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
**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
```javascript
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
function onAbilityCreateCallback() {
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
......@@ -64,7 +75,7 @@ var monitor = {
}
var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityMonitor(monitor).then((void) => {
abilityDelegator.addAbilityMonitor(monitor).then(() => {
console.info("addAbilityMonitor promise");
});
```
......@@ -94,7 +105,7 @@ var abilityDelegator;
var ability;
var timeout = 100;
function onAbilityCreateCallback() {
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
......@@ -113,8 +124,6 @@ var want = {
bundleName: "bundleName",
abilityName: "abilityName"
};
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.startAbility(want, (err, data) => {
console.info("startAbility callback");
});
......@@ -126,14 +135,47 @@ abilityDelegator.startAbility(want, (err, data) => {
### 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**
```javascript
var abilityDelegator;
var cmd = "cmd";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err,data) => {
var abilityDelegator;
var cmd = "cmd";
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.executeShellCommand(cmd, (err, data) => {
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 @@
## 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 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 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.
## 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)
......@@ -18,7 +19,7 @@ For details about the application package structure, see [Description of the App
## 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.**
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
......@@ -30,6 +31,20 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
## 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)
## 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
**Table 1** Data ability lifecycle APIs
|API|Description|
|:------|:------|
|onInitialized|Called during ability initialization to initialize the relational database (RDB).|
|update|Updates data in the database.|
|query|Queries data in the database.|
|delete|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.|
|batchInsert|Inserts multiple data records into the database.|
|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert|Inserts a data record into the database.|
|openFile|Opens a file.|
|getFileTypes|Obtains the MIME type of a file.|
|getType|Obtains the MIME type matching the data specified by the URI.|
|executeBatch|Operates data in the database in batches.|
|call|Calls a custom API.|
|onInitialized?(info: AbilityInfo): void|Called during ability initialization to initialize the relational database (RDB).|
|update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Updates data in the database.|
|query?(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|Queries data in the database.|
|delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|Deletes one or more data records from the database.|
|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?(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|Inserts multiple data records into the database.|
|denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.|
|insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|Inserts a data record into the database.|
|openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|Opens a file.|
|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\<Array\<string>>): void|Obtains the MIME type of a file.|
|getType?(uri: string, callback: AsyncCallback\<string>): void|Obtains the MIME type matching the data specified by the URI.|
|executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|Operates data in the database in batches.|
|call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|Calls a custom API.|
## How to Develop
......
......@@ -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 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.
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.
## 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**.
- Create a **FormBindingData** instance.
- Update a widget through **FormProvider**.
- Develop the widget UI page.
- Develop the widget UI pages.
## 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
......@@ -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. |
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. |
| 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. |
| 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. |
......@@ -73,7 +74,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default {
onCreate(want) {
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 = {
"title": "titleOnCreate",
"detail": "detailOnCreate"
......@@ -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.
- 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 |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ |
......@@ -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 |
| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
......@@ -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.
......@@ -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 formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// 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".
storeFormInfo(formId, formName, tempFlag, want);
......@@ -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).
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
......@@ -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.
### 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.
> ![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.
- HML:
- In the HML file:
```html
<div class="container">
<stack>
......@@ -262,7 +285,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
</div>
```
- CSS:
- In the CSS file:
```css
.container {
......@@ -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
{
"data": {
......
......@@ -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)
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Page ability startup applies only to system applications.
### Starting a Remote Page Ability
>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**
......@@ -261,4 +261,5 @@ export default {
```
## Samples
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
**Table 1** Service ability lifecycle APIs
|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.|
|onCommand|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.|
|onDisconnect|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.|
|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?(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?(want: Want): rpc.RemoteObject|Called when another ability is connected to the Service ability.|
|onDisconnect?(want: Want): void|Called when another ability is disconnected from the Service ability.|
|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
......@@ -43,7 +43,7 @@ A Service ability is used to run tasks in the background, such as playing music
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
{
......@@ -214,8 +214,8 @@ export default {
}
```
### Connecting to a Remote Service Ability (Applying only to System Applications)
>NOTE
### Connecting to a Remote Service Ability
>**NOTE**
>
>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 @@
## 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
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
|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.|
| onCreate(want: Want, param: LaunchParam): void| Called by the **target** to restore the data and page.|
| 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 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).|
......@@ -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
"launchType": "standard"
......@@ -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.
......@@ -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:
......@@ -111,10 +111,10 @@ The following table lists the APIs used for ability continuation. For details ab
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
onContinue(wantParam : {[key: string]: any}) {
......@@ -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
onCreate(want, launchParam) {
Logger.info(`MainAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
globalThis.abilityWant = want;
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)
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
### 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
import Ability from '@ohos.application.Ability';
......@@ -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
import Ability from '@ohos.application.Ability';
......@@ -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.
......@@ -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).
**Table 3** AbilityContext APIs
|API|Description|
|:------|:------|
|startAbility(want: Want, callback: AsyncCallback\<void>): void|Starts an ability.|
......@@ -249,7 +248,7 @@ var want = {
context.startAbility(want).then((data) => {
console.log("Succeed to start remote ability with data: " + JSON.stringify(data))
}).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:
......
# Stage Model Overview
### Design Ideas
## Design Ideas
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:
- **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.
......@@ -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.
- **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.
- **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.
- **Ability**: provides lifecycle callback, holds the **AbilityContext** class, and supports component continuation and collaboration.
- **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**: 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**.
- **WindowStage**: local window manager.
- **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)
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:
......@@ -62,11 +62,11 @@ Abilities can be started in any of the following modes:
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)
### 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:
......@@ -82,9 +82,9 @@ The following figure uses the widget scenario as an example. You can inherit fro
![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.
......
......@@ -187,7 +187,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
{
"forms": [{
"name": "widget",
"description": "This is a service widget.",
"description": "This is a widget.",
"src": "./js/widget/pages/index/index",
"window": {
"autoDesignWidth": true,
......@@ -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.
### 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
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**
......
# Service Extension Ability Development
## 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.
......@@ -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:
- [ServiceExtensionAbility](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.
- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility)
......@@ -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 STORE_CONFIG = {name: "rdbstore.db",}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE)
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
......
......@@ -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. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets 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. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
......
......@@ -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 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.
......
......@@ -2,5 +2,6 @@
- [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native_window-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);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.replaceAllElements((value, index) => {
arrayList.replaceAllElements((value: number, index: number)=> {
return value = 2 * value;
});
arrayList.replaceAllElements((value, index) => {
arrayList.replaceAllElements((value: number, index: number) => {
return value = value - 2;
});
```
......@@ -394,8 +394,8 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.sort((a, b) => a - b);
arrayList.sort((a, b) => b - a);
arrayList.sort((a: number, b: number) => a - b);
arrayList.sort((a: number, b: number) => b - a);
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.
......@@ -26,7 +34,7 @@ The default duration of delayed suspension is 180000 when the battery level is h
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------ |
| 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**
| Type | Description |
......@@ -120,6 +128,7 @@ Cancels the suspension delay.
**Example**
```js
let id = 1;
backgroundTaskManager.cancelSuspendDelay(id);
```
......@@ -187,16 +196,16 @@ Requests a continuous task from the system. This API uses a promise to return th
**Parameters**
| Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ----------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| 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. |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| 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.|
**Return value**
| Type | Description |
| Type | Description |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result. |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
......@@ -236,10 +245,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
**Parameters**
| Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description |
| -------- | ----------------------------- | ---- | ---------------------- |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
| context | [Context](js-apis-Context.md) | Yes | Application context. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
......@@ -267,14 +276,14 @@ Requests to cancel a continuous task. This API uses a promise to return the resu
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
**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**
| Type | Description |
| Type | Description |
| -------------- | ---------------- |
| Promise\<void> | Promise used to return the result. |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
......@@ -305,14 +314,14 @@ Provides the information about the suspension delay.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
| Name | Value| Description |
| ----------------------- | ------ | ---------------------------- |
| DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | 7 | WLAN-related (reserved). |
| VOIP | 8 | Voice and video call (reserved). |
| TASK_KEEPING | 9 | Computing task (effective only for specific devices).|
| Name | Value| Description |
| ----------------------- | ------ | ------------------------------------------------------------ |
| DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API and cannot be called by third-party applications.|
| 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). |
# 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.
## Modules to Import
......@@ -139,7 +141,7 @@ Obtains all the display objects.
| 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**
......@@ -163,7 +165,7 @@ Enables listening.
**Parameters**
| 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.|
**Example**
......@@ -186,7 +188,7 @@ Disables listening.
**Parameters**
| 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.|
**Example**
......
......@@ -576,13 +576,12 @@ Provides KV store configuration.
Defines the KV store types.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Default Value| Description |
| --- | ---- | ----------------------- |
| DEVICE_COLLABORATION | 0 | Device KV store. |
| SINGLE_VERSION | 1 | Single KV store. |
| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. |
| DEVICE_COLLABORATION | 0 | Device KV store. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| 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. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
## SecurityLevel
......
# 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.
## Modules to Import
```
```js
import hiAppEvent from '@ohos.hiAppEvent';
```
......@@ -23,14 +25,14 @@ Writes event information to the event file of the current day. This API supports
| 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. |
| 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.|
| 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. |
**Example**
```
```js
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => {
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.
......@@ -56,19 +58,19 @@ Writes event information to the event file of the current day. This API supports
| 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. |
| 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**
| 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**
```
```js
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"})
.then((value) => {
// Event writing succeeded.
......@@ -92,16 +94,16 @@ Configures the application event logging function, such as setting the event log
| 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**
| 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**
```
```js
// Set the application event logging switch.
hiAppEvent.configure({
disable: true
......@@ -122,8 +124,8 @@ Provides the configuration items for application event logging.
| 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.|
| 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.|
| 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. |
## EventType
......@@ -150,7 +152,7 @@ Provides constants that define the names of all predefined events.
| ------------------------- | -------- | ---- | ---- | -------------------- |
| USER_LOGIN | string | Yes | No | User login 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
......@@ -159,8 +161,8 @@ Provides constants that define the names of all predefined event parameters.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
| Name | Type| Readable| Writable| Description |
| Name | Type | Readable | Writable | Description |
| ------------------------------- | -------- | ---- | ---- | ------------------ |
| USER_ID | string | Yes | No | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.|
| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID. |
\ No newline at end of file
# 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>
> 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
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>
> 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);
list.add(4);
list.add(5);
list.add(4);
list.replaceAllElements((value, index) => {
list.replaceAllElements((value: number, index: number) => {
return value = 2 * value;
});
list.replaceAllElements((value, index) => {
list.replaceAllElements((value: number, index: number) => {
return value = value - 2;
});
```
......@@ -439,8 +439,8 @@ list.add(2);
list.add(4);
list.add(5);
list.add(4);
list.sort((a, b) => a - b);
list.sort((a, b) => b - a);
list.sort((a: number, b: number) => a - b);
list.sort((a: number, b: number) => b - a);
```
### getSubList
......@@ -472,9 +472,9 @@ list.add(2);
list.add(4);
list.add(5);
list.add(4);
let result = list.subList(2, 4);
let result1 = list.subList(4, 3);
let result2 = list.subList(2, 6);
let result = list.getSubList(2, 4);
let result1 = list.getSubList(4, 3);
let result2 = list.getSubList(2, 6);
```
### clear
......
......@@ -23,15 +23,17 @@ matchMediaSync(condition: string): MediaQueryListener
Sets the media query criteria and returns the corresponding listening handle.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------- |
| condition | string | Yes | Matching condition of a media event.|
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- |
| 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**
| 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**
```js
......@@ -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.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
### Attributes
......@@ -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.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ---------------- |
......@@ -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
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**
| Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ----------------------------- |
| 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**
```js
......@@ -92,7 +100,7 @@ Unregisters a callback with the corresponding query condition by using the handl
}
}
listener.on('change', onPortrait) // Register a callback.
listener.off('change', onPortrait) // Unregister a callback.
listener.off('change', onPortrait) // Deregister a callback.
```
......
# 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.
> - 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
Obtains the number of pages in the current stack.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Return value**
| Type| Description|
| -------- | -------- |
......@@ -275,7 +277,7 @@ Enables the display of a confirm dialog box before returning to the previous pag
Describes the confirm dialog box.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......
# 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**
>
> 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
......@@ -17,11 +20,12 @@ Describes screenshot options.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| 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.|
| 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**.|
| 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. |
| 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**. |
| 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
......@@ -63,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal
| 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. |
**Example**
......@@ -78,7 +82,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a cal
"imageSize": {
"width": 300,
"height": 300},
"rotation": 0
"rotation": 0,
"displayId": 0
};
screenshot.save(ScreenshotOptions, (err, data) => {
if (err) {
......@@ -103,13 +108,13 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro
| 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**
| 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**
......@@ -123,7 +128,8 @@ Takes a screenshot and saves it as a **PixelMap** object. This method uses a pro
"imageSize": {
"width": 300,
"height": 300},
"rotation": 0
"rotation": 0,
"displayId": 0
};
let promise = screenshot.save(ScreenshotOptions);
promise.then(() => {
......
......@@ -190,7 +190,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This
**Example**
```js
systemTime.getCurrentTime().then((data) => {
systemTime.getRealActiveTime().then((data) => {
console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data));
}).catch((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
**Example**
```
updater.getNewVersionInfo(info => {
updater.getNewVersionInfo((err, info) => {
console.log("getNewVersionInfo success " + info.status);
console.log(`info versionName = ` + info.checkResult[0].versionName);
console.log(`info versionCode = ` + info.checkResult[0].versionCode);
console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo);
console.log(`info versionName = ` + info.checkResults[0].versionName);
console.log(`info versionCode = ` + info.checkResults[0].versionCode);
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
```
updater.getNewVersionInfo().then(value => {
console.log(`info versionName = ` + value.checkResult[0].versionName);
console.log(`info versionCode = ` + value.checkResult[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo);
console.log(`info versionName = ` + value.checkResults[0].versionName);
console.log(`info versionCode = ` + value.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResults[0].verifyInfo);
}).catch(err => {
console.log("getNewVersionInfo promise error: " + err.code);
});
......@@ -185,11 +185,11 @@ Checks whether the current version is the latest. This function uses an asynchro
**Example**
```
updater.checkNewVersion(info => {
updater.checkNewVersion((err, info) => {
console.log("checkNewVersion success " + info.status);
console.log(`info versionName = ` + info.checkResult[0].versionName);
console.log(`info versionCode = ` + info.checkResult[0].versionCode);
console.log(`info verifyInfo = ` + info.checkResult[0].verifyInfo);
console.log(`info versionName = ` + info.checkResults[0].versionName);
console.log(`info versionCode = ` + info.checkResults[0].versionCode);
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
```
updater.checkNewVersion().then(value => {
console.log(`info versionName = ` + value.checkResult[0].versionName);
console.log(`info versionCode = ` + value.checkResult[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResult[0].verifyInfo);
console.log(`info versionName = ` + value.checkResults[0].versionName);
console.log(`info versionCode = ` + value.checkResults[0].versionCode);
console.log(`info verifyInfo = ` + value.checkResults[0].verifyInfo);
}).catch(err => {
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
**Example**
```
updater.rebootAndCleanUserData(result => {
updater.rebootAndCleanUserData((err, result) => {
console.log("rebootAndCleanUserData ", result)
});
```
......@@ -330,7 +330,7 @@ Installs the update package. This function uses a promise to return the result.
**Example**
```
updater.applyNewVersion(result => {
updater.applyNewVersion((err, result) => {
console.log("applyNewVersion ", result)
});
```
......@@ -399,7 +399,7 @@ let policy = {
autoUpgradeInterval: [ 2, 3 ],
autoUpgradeCondition: 2
}
updater.setUpdatePolicy(policy, result => {
updater.setUpdatePolicy(policy, (err, result) => {
console.log("setUpdatePolicy ", result)
});
```
......@@ -458,7 +458,7 @@ Obtains the update policy. This function uses an asynchronous callback to return
**Example**
```
updater.getUpdatePolicy(policy => {
updater.getUpdatePolicy((err, policy) => {
console.log("getUpdatePolicy success");
console.log(`policy autoDownload = ` + policy.autoDownload);
console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet);
......
# 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.
......@@ -10,10 +11,6 @@
import Url from '@ohos.url'
```
## System Capabilities
SystemCapability.Utils.Lang
## URLSearchParams
......@@ -23,20 +20,22 @@ constructor(init?: string[][] | Record&lt;string, string&gt; | string | URLSearc
Creates a **URLSearchParams** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| 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**
```js
var objectParams = new URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
var objectParams1 = new URLSearchParams({"fod" : 1 , "bard" : 2});
var objectParams2 = new URLSearchParams('?fod=1&bard=2');
var urlObject = new URL('https://developer.mozilla.org/?fod=1&bard=2');
var params = new URLSearchParams(urlObject.search);
var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]);
var objectParams1 = new Url.URLSearchParams({"fod" : 1 , "bard" : 2});
var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2');
var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2');
var params = new Url.URLSearchParams(urlObject.search);
```
......@@ -46,18 +45,20 @@ append(name: string, value: string): void
Appends a key-value pair into the query string.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| name | string | Yes| Key of the key-value pair to append.|
| value | string | Yes| Value 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. |
**Example**
```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1));
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3);
```
......@@ -68,17 +69,19 @@ delete(name: string): void
Deletes key-value pairs of the specified key.
**System capability**: SystemCapability.Utils.Lang
**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**
```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsobject = new URLSearchParams(urlObject.search.slice(1));
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsobject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsobject.delete('fod');
```
......@@ -89,23 +92,25 @@ getAll(name: string): string[]
Obtains all the key-value pairs based on the specified key.
**System capability**: SystemCapability.Utils.Lang
**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**
| Type| Description|
| Type | Description |
| -------- | -------- |
| string[] | All key-value pairs matching the specified key.|
| string[] | All key-value pairs matching the specified key. |
**Example**
```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1));
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.append('fod', 3); // Add a second value for the fod parameter.
console.log(params.getAll('fod')) // Output ["1","3"].
```
......@@ -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.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| Type | Description |
| -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | ES6 iterator.|
| IterableIterator&lt;[string, string]&gt; | ES6 iterator. |
**Example**
```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
console.log(pair[0]+ ', '+ pair[1]);
}
......@@ -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.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| 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.|
| 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. |
**Table 1** callbackfn parameter description
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| value | string | Yes| Value that is currently traversed.|
| key | string | Yes| Key that is currently traversed.|
| searchParams | Object | Yes| Instance that invokes the **forEach** method.|
| value | string | Yes | Value that is currently traversed. |
| key | string | Yes | Key that is currently traversed. |
| searchParams | Object | Yes | Instance that invokes the **forEach** method. |
**Example**
```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) => {
console.log(name, value, myURLObject.searchParams === searchParams);
});
......@@ -170,23 +179,25 @@ get(name: string): string | null
Obtains the value of the first key-value pair based on the specified key.
**System capability**: SystemCapability.Utils.Lang
**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**
| Type| Description|
| Type | Description |
| -------- | -------- |
| string | Returns the value of the first key-value pair if obtained.|
| null | Returns null if no value is obtained.|
| string | Returns the value of the first key-value pair if obtained. |
| null | Returns null if no value is obtained. |
**Example**
```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 age = parseInt(paramsOject.get("age"), 10); // is the number 18
var address = paramsOject.get("address"); // null
......@@ -199,23 +210,25 @@ has(name: string): boolean
Checks whether a key has a value.
**System capability**: SystemCapability.Utils.Lang
**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**
| 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**
```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1));
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.has('bard') === true;
```
......@@ -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.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| name | string | Yes| Key of the value to set.|
| value | string | Yes| Value to set.|
| name | string | Yes | Key of the value to set. |
| value | string | Yes | Value to set. |
**Example**
```js
let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new URLSearchParams(urlObject.search.slice(1));
let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let paramsObject = new Url.URLSearchParams(urlObject.search.slice(1));
paramsObject.set('baz', 3); // Add a third parameter.
```
......@@ -246,13 +261,14 @@ paramsObject.set('baz', 3); // Add a third parameter.
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**
```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
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 /
keys(): IterableIterator&lt;string&gt;
Obtains an ES6 iterator that contains the keys of all the key-value pairs.
**System capability**: SystemCapability.Utils.Lang
**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**
```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
console.log(key);
}
......@@ -287,16 +304,18 @@ values(): IterableIterator&lt;string&gt;
Obtains an ES6 iterator that contains the values of all the key-value pairs.
**System capability**: SystemCapability.Utils.Lang
**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**
```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()) {
console.log(value);
}
......@@ -307,19 +326,20 @@ for (var value of searchParams.values()) {
[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.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| Type | Description |
| -------- | -------- |
| IterableIterator&lt;[string,&nbsp;string]&gt; | ES6 iterator.|
| IterableIterator&lt;[string, string]&gt; | ES6 iterator. |
**Example**
```js
const paramsObject = new URLSearchParams('fod=bay&edg=bap');
const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap');
for (const [name, value] of paramsObject) {
console.log(name, value);
}
......@@ -330,20 +350,21 @@ for (const [name, value] of paramsObject) {
toString(): 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**
| 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**
```js
let url = new URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new URLSearchParams(url.search.slice(1));
let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2');
let params = new Url.URLSearchParams(url.search.slice(1));
params.append('fod', 3);
console.log(params.toString());
```
......@@ -351,9 +372,10 @@ console.log(params.toString());
## URL
### Attributes
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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());
constructor(url: string, base?: string | URL)
Creates a URL.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| 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|
| url | string | Yes | Input object. |
| base | string \ |& URL | No | Input parameter, which can be any of the following:<br>- **string**: string<br>- **URL**: string or object |
**Example**
```js
var mm = 'http://username:password@host:8080';
var a = new URL("/", mm); // Output 'http://username:password@host:8080/';
var b = new URL(mm); // Output 'http://username:password@host:8080/';
new 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';
new 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('/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('/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('http://www.shanxi.com', b); // Output http://www.shanxi.com/
var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/';
var b = new Url.URL(mm); // Output 'http://username:password@host:8080/';
new Url.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.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1';
new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1';
new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1
new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL
new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL
new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/
new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/
```
......@@ -408,16 +431,18 @@ toString(): string
Converts the parsed URL into a string.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| Type | Description |
| -------- | -------- |
| string | Website address in a serialized string.|
| string | Website address in a serialized string. |
**Example**
```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()
```
......@@ -426,17 +451,18 @@ url.toString()
toJSON(): string
Converts the parsed URL into a JSON string.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| Type | Description |
| -------- | -------- |
| string | Website address in a serialized string.|
| string | Website address in a serialized string. |
**Example**
```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()
```
```
\ No newline at end of file
# 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.
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
......@@ -140,7 +141,7 @@ Processes an asynchronous function and returns a promise version.
| 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.|
| 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.
result[4] = 0x62;
result[5] = 0x63;
console.log("input num:");
for(var j= 0; j < 6; j++) {
console.log(result[j]);
}
var retStr = textDecoder.decode( result , {stream: false});
console.log("retStr = " + retStr);
```
......@@ -262,6 +260,7 @@ Encodes the input content.
**Example**
```js
var textEncoder = new util.TextEncoder();
var buffer = new ArrayBuffer(20);
var result = new Uint8Array(buffer);
result = textEncoder.encode("\uD800¥¥");
```
......@@ -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.|
**Example**
```js
var rationalNumber = new util.RationalNumber(1,2);
var rational = rationalNumer.creatRationalFromString("3/4");
......@@ -484,7 +482,7 @@ Obtains the denominator of this **RationalNumber** object.
### isZero<sup>8+</sup>
isZero​(): boolean
isZero​():boolean
Checks whether this **RationalNumber** object is **0**.
......@@ -524,7 +522,7 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN).
### isFinite<sup>8+</sup>
isFinite​(): boolean
isFinite​():boolean
Checks whether this **RationalNumber** object represents a finite value.
......@@ -825,7 +823,7 @@ Obtains the value of the specified key.
**Return value**
| 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**
```js
......@@ -872,7 +870,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac
**Return value**
| 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**
```js
......@@ -895,7 +893,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce
**Return value**
| 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**
```js
......@@ -921,7 +919,7 @@ Removes the specified key and its value from this buffer.
**Return value**
| 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**
```js
......@@ -1038,7 +1036,7 @@ Obtains a new iterator object that contains all key-value pairs in this object.
**Return value**
| Type| Description|
| -------- | -------- |
| [K,&nbsp;V] | Iterable array.|
| [K, V] | Iterable array.|
**Example**
```js
......@@ -1059,7 +1057,7 @@ Obtains a two-dimensional array in key-value pairs.
**Return value**
| Type| Description|
| -------- | -------- |
| [K,&nbsp;V] | Two-dimensional array in key-value pairs.|
| [K, V] | Two-dimensional array in key-value pairs.|
**Example**
```js
......@@ -1092,6 +1090,8 @@ Example
```js
class Temperature{
constructor(value){
// If TS is used for development, add the following code:
// private readonly _temp: Temperature;
this._temp = value;
}
comapreTo(value){
......@@ -1183,7 +1183,7 @@ Obtains the intersection of this **Scope** and the given **Scope**.
### 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.
......@@ -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.|
**Example**
```js
var tempLower = new Temperature(30);
var tempUpper = new Temperature(40);
......@@ -1288,7 +1289,7 @@ Obtains the union set of this **Scope** and the given lower and upper limits.
### expand<sup>8+</sup>
expand(range:Scope):Scope
expand(range: Scope): Scope
Obtains the union set of this **Scope** and the given **Scope**.
......@@ -1510,7 +1511,7 @@ Decodes the input content.
**Parameters**
| 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**
| Type| Description|
......@@ -1595,7 +1596,7 @@ Decodes the input content asynchronously.
**Parameters**
| 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**
| Type| Description|
......@@ -1622,7 +1623,7 @@ Decodes the input content asynchronously.
constructor()
A constructor used to create a **types** object.
A constructor used to create a **Types** object.
**System capability**: SystemCapability.Utils.Lang
......
......@@ -319,10 +319,10 @@ vector.add(2);
vector.add(4);
vector.add(5);
vector.add(4);
vector.replaceAllElements((value, index) => {
vector.replaceAllElements((value: number, index: number) => {
return value = 2 * value;
});
vector.replaceAllElements((value, index) => {
vector.replaceAllElements((value: number, index: number) => {
return value = value - 2;
});
```
......@@ -394,8 +394,8 @@ vector.add(2);
vector.add(4);
vector.add(5);
vector.add(4);
vector.sort((a, b) => a - b);
vector.sort((a, b) => b - a);
vector.sort((a: number, b: number) => a - b);
vector.sort((a: number, b: number) => b - a);
vector.sort();
```
......@@ -620,7 +620,7 @@ vector.add(2);
vector.add(4);
vector.add(5);
vector.add(4);
let result = vector.toSting();
let result = vector.toString();
```
### copyToArray
......
# 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.
......@@ -10,10 +11,6 @@
import xml from '@ohos.xml';
```
## System Capabilities
SystemCapability.Utils.Lang
## XmlSerializer
......@@ -23,11 +20,13 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string)
A constructor used to create an **XmlSerializer** instance.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| 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.|
**Example**
......@@ -45,6 +44,8 @@ setAttributes(name: string, value: string): void
Sets an attribute.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -55,6 +56,8 @@ Sets an attribute.
**Example**
```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView);
thatSer.setAttributes("importance", "high");
```
......@@ -66,6 +69,8 @@ addEmptyElement(name: string): void
Adds an empty element.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -75,6 +80,8 @@ Adds an empty element.
**Example**
```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView);
thatSer.addEmptyElement("b"); // => <b/>
```
......@@ -86,9 +93,13 @@ setDeclaration(): void
Sets a declaration.
**System capability**: SystemCapability.Utils.Lang
**Example**
```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView);
thatSer.setDeclaration() // => <?xml version="1.0" encoding="utf-8"?>;
```
......@@ -100,6 +111,8 @@ startElement(name: string): void
Writes the start tag based on the given element name.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -122,9 +135,13 @@ endElement(): void
Writes the end tag of the element.
**System capability**: SystemCapability.Utils.Lang
**Example**
```js
var arrayBuffer = new ArrayBuffer(1024);
var bufView = new DataView(arrayBuffer);
var thatSer = new xml.XmlSerializer(bufView);
thatSer.setNamespace("h", "http://www.w3.org/TR/html4/");
thatSer.startElement("table");
......@@ -140,6 +157,8 @@ setNamespace(prefix: string, namespace: string): void
Sets the namespace for an element tag.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -164,6 +183,8 @@ setComment(text: string): void
Sets the comment.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -187,6 +208,8 @@ setCDATA(text: string): void
Sets CDATA attributes.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -208,6 +231,8 @@ setText(text: string): void
Sets **Text**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -232,6 +257,8 @@ setDocType(text: string): void
Sets **DocType**.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -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).
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| 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.|
**Example**
......@@ -289,6 +318,8 @@ parse(option: ParseOptions): void
Parses XML information.
**System capability**: SystemCapability.Utils.Lang
**Parameters**
| Name| Type| Mandatory| Description|
......@@ -329,14 +360,16 @@ that.parse(options);
Defines the XML parsing options.
**System capability**: SystemCapability.Utils.Lang
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| supportDoctype | boolean | No| Whether to ignore **Doctype**. 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**.|
| attributeValueCallbackFunction | (name:&nbsp;string,&nbsp;value:&nbsp;string)=&gt;&nbsp;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**.|
| tagValueCallbackFunction | (name: string, value: string)=&gt; boolean | No| Callback used to return **tagValue**.|
| attributeValueCallbackFunction | (name: string, value: string)=&gt; boolean | No| Callback used to return **attributeValue**.|
| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=&gt; boolean | No| Callback used to return **tokenValue**.|
## ParseInfo
......@@ -349,6 +382,8 @@ getColumnNumber(): number
Obtains the column line number, which starts from 1.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -362,6 +397,8 @@ getDepth(): number
Obtains the depth of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -375,6 +412,8 @@ getLineNumber(): number
Obtains the current line number, starting from 1.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -388,6 +427,8 @@ getName(): string
Obtains the name of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -401,6 +442,8 @@ getNamespace(): string
Obtains the namespace of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -414,6 +457,8 @@ getPrefix(): string
Obtains the prefix of this element.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -427,6 +472,8 @@ getText(): string
Obtains the text of the current event.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -440,6 +487,8 @@ isEmptyElementTag(): boolean
Checks whether the current element is empty.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -453,6 +502,8 @@ isWhitespace(): boolean
Checks whether the current text event contains only whitespace characters.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
......@@ -466,6 +517,8 @@ getAttributeCount(): number
Obtains the number of attributes for the current start tag.
**System capability**: SystemCapability.Utils.Lang
**Return value**
| Type| Description|
| -------- | -------- |
......@@ -476,6 +529,8 @@ Obtains the number of attributes for the current start tag.
Enumerates the events.
**System capability**: SystemCapability.Utils.Lang
| Name| Value| Description|
| -------- | -------- | -------- |
| START_DOCUMENT | 0 | Indicates a start document event.|
......
# 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
- 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.
Different from private events, universal events can be bound to most components.
| Name | Parameter | Description | Support Bubbling |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------- |
| touchstart | [TouchEvent](js-components-common-events.md) | Triggered when the tapping starts. | Yes<sup>5+</sup> |
| touchmove | [TouchEvent](js-components-common-events.md) | 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> |
| touchend | [TouchEvent](js-components-common-events.md) | Triggered when the tapping ends. | Yes<sup>5+</sup> |
| click | - | Triggered when a component is clicked. | Yes<sup>6+</sup> |
| doubleclick<sup>7+</sup> | | Triggered when a component is double-clicked. | No |
| longpress | - | Triggered when a component is long pressed. | No |
| swipe<sup>5+</sup> | [SwipeEvent](js-components-common-events.md#table111811577714) | Triggered when a user quickly swipes on a component. | 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 |
| pinchstart<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when a pinch operation is started. | No |
| pinchupdate<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | 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 |
| pinchcancel<sup>7+</sup> | [PinchEvent](js-components-common-events.md) | Triggered when the pinch operation is interrupted. | No |
| dragstart<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when dragging starts. | No |
| drag<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when dragging is in progress. | No |
| dragend<sup>7+</sup> | [DragEvent](js-components-common-events.md) | 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 |
| dragover<sup>7+</sup> | [DragEvent](js-components-common-events.md) | 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 |
| drop<sup>7+</sup> | [DragEvent](js-components-common-events.md) | Triggered when a 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
| Attribute | Type | Description |
| --------- | ------ | ----------------------------------------------- |
| type | string | Event type, such as **click** and **longpress** |
| timestamp | number | Timestamp when the event is triggered |
- The event callback can carry additional information through parameters, such as the dataset on the component and event-specific callback parameters.
**Table 2** Attributes of the TouchEvent object (inherited from BaseEvent)
Different from private events, universal events can be bound to most components.
| Attribute | Type | Description |
| -------------- | ----------------- | ------------------------------------------------------------ |
| touches | Array\<TouchInfo> | 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. |
| Name | Parameter | Description | Support Bubbling |
| ------------------------ | ---------- | ---------------------------------------- | ---------------------------------------- |
| touchstart | TouchEvent | Triggered when the tapping starts. For details about **TouchEvent**, see Table 2. | Yes<sup>5+</sup> |
| touchmove | TouchEvent | Triggered when the tapping moves. | Yes<sup>5+</sup> |
| touchcancel | TouchEvent | Triggered when the tapping is interrupted. | 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> |
| 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<br>Bubbling is supported since API version 9.|
| 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 |
| detached<sup>6+</sup> | - | Triggered when the current component node is removed from the render tree. | 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 | Triggered when a pinch operation is in progress. | No |
| pinchend<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is ended. | No |
| pinchcancel<sup>7+</sup> | PinchEvent | Triggered when a pinch operation is interrupted. | No |
| dragstart<sup>7+</sup> | DragEvent | Triggered when dragging starts.<br>For details about **DragEvent**, see Table 6. | No |
| drag<sup>7+</sup> | DragEvent | Triggered when dragging is in progress. | No |
| dragend<sup>7+</sup> | DragEvent | Triggered when dragging is ended. | No |
| dragenter<sup>7+</sup> | DragEvent | Triggered when the dragged component enters 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 | Triggered when the dragged component leaves a drop target. | No |
| drop<sup>7+</sup> | DragEvent | Triggered when the dragged component is dropped on a drop target. | No |
> **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 |
| --------------------- | -------------------- | --------------------------- |
| type | string | Event type, such as **click** and **longpress**.|
| timestamp | number | Timestamp when the event is triggered. |
| deviceId<sup>6+</sup> | number | ID of the device that triggers the event. |
| target<sup>6+</sup> | [Target](#target6)| Target object that triggers the event. |
**Table 2** TouchEvent (inherited from BaseEvent)
| Attribute | Type | Description |
| -------------- | ---------------------- | ---------------------------------------- |
| touches | Array&lt;TouchInfo&gt; | Attribute set of the touch event, including the information array of the touch points on the screen. |
| 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
| Attribute | Type | Description |
| ------------------ | ------ | ------------------------------ |
| 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), which acts as the origin of coordinates.|
| 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, which acts as the origin of coordinates. |
| size | number | Touch area. |
| force<sup>6+</sup> | number | Touch force. |
**Table 4** SwipeEvent (inherited from BaseEvent)
| 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. |
| 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. |
| 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. |
| 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. |
| size | number | Touch area. |
| force<sup>6+</sup> | number | Touch force. |
**Table 4** Attributes of the SwipeEvent object (inherited from BaseEvent)
| Attribute | Type | Description |
| --------------------- | ------ | ---------------------------------------- |
| 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. |
**Table 5** PinchEvent<sup>7+</sup>
| Attribute | Type | Description |
| ------------ | ------ | -------------- |
| scale | number | Scale factor. |
| pinchCenterX | number | X-coordinate of the pinch center, in px.|
| pinchCenterY | number | Y-coordinate of the pinch center, in px.|
| 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 |
| distance<sup>6+</sup> | number | Swiping distance in the swiping direction. |
**Table 6** DragEvent<sup>7+</sup> (inherited from BaseEvent)
**Table 5** Attributes of the PinchEvent object<sup>7+</sup>
| Attribute | Type | Description |
| ------------------------- | -------------------------------- | ---------------- |
| type | string | Event name. |
| 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 upper left corner of the screen, which acts as the origin of coordinates.|
| timestamp | number | Timestamp. |
| Attribute | Type | Description |
| ------------ | ------ | ---------------------------------------- |
| scale | number | Scale factor. |
| pinchCenterX | number | X-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>
| Attribute | Type | Description |
| --------- | ------ | ------------------------------------------------------------ |
| type | string | Event name. |
| globalX | number | Horizontal distance from the origin of the coordinates in the upper left corner of the screen. |
| globalY | number | Vertical distance from the origin of the coordinates in the upper left corner of the screen. |
| 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.
**target object:**
| Attribute | Type | Description |
| -------------------- | ------ | ---------------------------------------- |
| dataSet<sup>6+</sup> | Object | Custom attribute set defined through [data-*](../arkui-js/js-components-common-attributes.md).|
**Example**
| Attribute | Type | Description |
| --------- | ------ | ------------------------------------------------------------ |
| dataSet<sup>6+</sup> | Object | Custom attribute set defined through [data-*](js-components-common-attributes.md). |
**Example:**
```
```html
<!-- xxx.hml -->
<div>
<div data-a="dataA" data-b="dataB"
......@@ -118,7 +110,7 @@ When a component triggers an event, the event callback receives an event object
</div>
```
```
```js
// xxx.js
export default {
touchstartfunc(msg) {
......@@ -128,3 +120,5 @@ export default {
}
```
......@@ -61,8 +61,6 @@
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.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)
- [QRCode](ts-basic-components-qrcode.md)
- [Radio](ts-basic-components-radio.md)
......@@ -98,7 +96,6 @@
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md)
-
- [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md)
......
# 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.
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
......@@ -15,7 +15,7 @@ None
## Child Components
None
Not supported
## APIs
......@@ -37,7 +37,7 @@ ImageAnimator()
| iterations | number | 1 | No | By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. |
- AnimationStatus enums
| Name | Description |
| Name | Description |
| -------- | -------- |
| Initial | The animation is in the initial state. |
| Running | The animation is being played. |
......@@ -45,7 +45,7 @@ ImageAnimator()
| Stopped | The animation is stopped. |
- FillMode enums
| Name | Description |
| Name | Description |
| -------- | -------- |
| None | After the playback is complete, the animation restores to the initial state. |
| Forwards | After the playback is complete, the animation remains in the end state. |
......@@ -78,6 +78,7 @@ struct ImageAnimatorExample {
ImageAnimator()
.images([
{
// The comment folder is at the same level as the pages folder.
src: '/comment/bg1.jpg',
duration: 500,
width: 325,
......
# 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.
......@@ -15,7 +15,7 @@ None
## Child Components
None
Not supported
## APIs
......@@ -23,22 +23,22 @@ None
Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string })
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No| 6 | Scrolling step.|
| loop | number | No| -1 | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.|
| fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes| - | Text to scroll.|
| start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No| 6 | Scrolling step.|
| loop | number | No| -1 | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.|
| fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes| - | Text to scroll.|
## Events
| Name| Description|
| Name| Description|
| -------- | -------- |
| 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.|
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished 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.|
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.|
## Example
......
# 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
> ![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.
......@@ -12,7 +11,7 @@ None
## Child Components
None
Not supported
## APIs
......@@ -20,42 +19,43 @@ None
Toggle(options: { type: ToggleType, isOn?: boolean })
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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. |
| type | ToggleType | Yes| - | Type of the toggle.|
| 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
| 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. |
| Button | A button is provided. If the text setting is available, the corresponding text content is 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. |
| 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. The set text string, if any, will be displayed inside the button.|
| 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
| Name | Type | Default Value | Description |
| Name| Parameter| Default Value| Description|
| -------- | -------- | -------- | -------- |
| selectedColor | Color | - | Background color of the toggle when it is enabled. |
| 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**. |
| selectedColor | Color | - | Background color of the component when it is turned on.|
| 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
| 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
```
```ts
// xxx.ets
@Entry
@Component
struct ToggleExample {
build() {
Column({ space: 10 }) {
Text('type: Switch').fontSize(12).fontColor(0xcccccc).width('90%')
......
# 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.
......@@ -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. |
| 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. |
| 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
......
......@@ -462,8 +462,6 @@
- [LoadingProgress](reference/arkui-ts/ts-basic-components-loadingprogress.md)
- [Marquee](reference/arkui-ts/ts-basic-components-marquee.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)
- [QRCode](reference/arkui-ts/ts-basic-components-qrcode.md)
- [Radio](reference/arkui-ts/ts-basic-components-radio.md)
......@@ -706,7 +704,7 @@
- [@ohos.usb](reference/apis/js-apis-usb.md)
- [@ohos.vibrator](reference/apis/js-apis-vibrator.md)
- Account Management
- [@ohos.account.appAccount](reference/apis/js-apis-appAccount.md)
- [@ohos.account.distributedAccount](reference/apis/js-apis-distributed-account.md)
- [@ohos.account.osAccount](reference/apis/js-apis-osAccount.md)
......
......@@ -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 STORE_CONFIG = {name: "rdbstore.db",}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE)
rdbStore.executeSql(CREATE_TABLE_TEST )
console.info('create table done.')
})
```
......
......@@ -45,7 +45,7 @@
});
```
参考接口API说明,应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。
参考接口API说明[位置服务](../reference/apis/js-apis-geolocation.md),应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。
- 调用getAddressesFromLocationName位置描述转化坐标。
```
......@@ -55,6 +55,6 @@
});
```
参考接口API说明,应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。
参考接口API说明[位置服务](../reference/apis/js-apis-geolocation.md),应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。
如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。
......@@ -24,7 +24,7 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js
| setConfiguration(pipe:&nbsp;USBDevicePipe,&nbsp;config:&nbsp;USBConfig):&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 | 获取接口。 |
| 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 | 关闭设备消息控制通道。 |
| releaseInterface(pipe:&nbsp;USBDevicePipe,&nbsp;iface:&nbsp;USBInterface):&nbsp;number | 释放接口。 |
| getFileDescriptor(pipe:&nbsp;USBDevicePipe):&nbsp;number | 获取文件描述符。 |
......
# 音频管理
> **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> API Version 9当前为Canary版本,仅供试用,不保证接口可稳定调用。
音频管理提供管理音频的一些基础能力,包括对音频音量、音频设备的管理,以及对音频数据的采集和渲染等。
该模块提供以下音频相关的常用功能:
......@@ -11,6 +8,11 @@
- [AudioRenderer](#audiorenderer8):音频渲染,用于播放PCM(Pulse Code Modulation)音频数据。
- [AudioCapturer](#audiocapturer8):音频采集,用于录制PCM音频数据。
> **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> API Version 9当前为Canary版本,仅供试用,不保证接口可稳定调用。
## 导入模块
```
......@@ -551,7 +553,7 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => {
音量改变时,应用接收的事件。
此接口为系统接口,三方应用不支持。
此接口为系统接口,三方应用不支持调用
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Volume
......@@ -626,8 +628,8 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => {
| 名称 | 默认值 | 描述 |
| :--------------------- | :----- | :-------------------------------------------- |
| AUDIO_SCENE_DEFAULT | 0 | 默认音频场景。 |
| AUDIO_SCENE_RINGING | 1 | 响铃模式。<br/>系统接口,三方应用不支持调用。 |
| AUDIO_SCENE_PHONE_CALL | 2 | 电话模式。<br/>系统接口,三方应用不支持调用。 |
| AUDIO_SCENE_RINGING | 1 | 响铃模式。<br/>此接口为系统接口,三方应用不支持调用。 |
| AUDIO_SCENE_PHONE_CALL | 2 | 电话模式。<br/>此接口为系统接口,三方应用不支持调用。 |
| AUDIO_SCENE_VOICE_CHAT | 3 | 语音聊天模式。 |
## AudioManager
......@@ -640,6 +642,8 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l
设置指定流的音量,使用callback方式异步返回结果。
**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY
**系统能力:** SystemCapability.Multimedia.Audio.Volume
**参数:**
......@@ -668,6 +672,8 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt;
设置指定流的音量,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY
**系统能力:** SystemCapability.Multimedia.Audio.Volume
**参数:**
......@@ -1032,6 +1038,8 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void
设置铃声模式,使用callback方式异步返回结果。
**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY
**系统能力:** SystemCapability.Multimedia.Audio.Communication
**参数:**
......@@ -1059,6 +1067,8 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt;
设置铃声模式,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.ACCESS_NOTIFICATION_POLICY
**系统能力:** SystemCapability.Multimedia.Audio.Communication
**参数:**
......@@ -1139,6 +1149,8 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt
本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。
**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS
**系统能力:** SystemCapability.Multimedia.Audio.Core
**参数:**
......@@ -1169,6 +1181,8 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt;
本接口的使用场景为根据硬件设备支持能力扩展音频配置。在不同的设备平台上,所支持的音频参数会存在差异。示例代码内使用样例参数,实际支持的音频配置参数见具体设备平台的资料描述。
**需要权限:** ohos.permission.MODIFY_AUDIO_SETTINGS
**系统能力:** SystemCapability.Multimedia.Audio.Core
**参数:**
......@@ -1425,6 +1439,8 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void
设置麦克风静音状态,使用callback方式异步返回结果。
**需要权限:** ohos.permission.MICROPHONE
**系统能力:** SystemCapability.Multimedia.Audio.Device
**参数:**
......@@ -1452,6 +1468,8 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt;
设置麦克风静音状态,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.MICROPHONE
**系统能力:** SystemCapability.Multimedia.Audio.Device
**参数:**
......@@ -1480,6 +1498,8 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void
获取麦克风静音状态,使用callback方式异步返回结果。
**需要权限:** ohos.permission.MICROPHONE
**系统能力:** SystemCapability.Multimedia.Audio.Device
**参数:**
......@@ -1506,6 +1526,8 @@ isMicrophoneMute(): Promise&lt;boolean&gt;
获取麦克风静音状态,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.MICROPHONE
**系统能力:** SystemCapability.Multimedia.Audio.Device
**返回值:**
......@@ -1529,7 +1551,7 @@ on(type: 'volumeChange', callback: Callback\<VolumeEvent>): void
监听系统音量变化事件。
此接口为系统接口,三方应用不支持。
此接口为系统接口,三方应用不支持调用
**系统能力:** SystemCapability.Multimedia.Audio.Volume
......@@ -1556,7 +1578,7 @@ on(type: 'ringerModeChange', callback: Callback\<AudioRingMode>): void
监听铃声模式变化事件。
此接口为系统接口,三方应用不支持。
此接口为系统接口,三方应用不支持调用
**系统能力:** SystemCapability.Multimedia.Audio.Communication
......@@ -1698,7 +1720,7 @@ setAudioScene\(scene: AudioScene, callback: AsyncCallback<void\>\): void
设置音频场景模式,使用callback方式异步返回结果。
此接口为系统接口,三方应用不支持。
此接口为系统接口,三方应用不支持调用
**系统能力:** SystemCapability.Multimedia.Audio.Communication
......@@ -1727,7 +1749,7 @@ setAudioScene\(scene: AudioScene\): Promise<void\>
设置音频场景模式,使用Promise方式返回异步结果。
此接口为系统接口,三方应用不支持。
此接口为系统接口,三方应用不支持调用
**系统能力:** SystemCapability.Multimedia.Audio.Communication
......
......@@ -233,6 +233,8 @@ cancelPairedDevice(deviceId: string): boolean
删除配对的远程设备。
此接口为系统接口。
**需要权限**:ohos.permission.DISCOVER_BLUETOOTH
**系统能力**:SystemCapability.Communication.Bluetooth.Core。
......@@ -397,7 +399,7 @@ startBluetoothDiscovery(): boolean
开启蓝牙扫描,可以发现远端设备。
**需要权限**:ohos.permission.USE_BLUETOOTH;ohos.permission.LOCATION
**需要权限**:ohos.permission.DISCOVER_BLUETOOTH;ohos.permission.LOCATION
**系统能力**:SystemCapability.Communication.Bluetooth.Core。
......@@ -1110,7 +1112,7 @@ getConnectedBLEDevices(): Array&lt;string&gt;
| 类型 | 说明 |
| ------------------- | ------------------- |
| Array&lt;string&gt; | 返回和当前设备连接BLE设备地址集合。 |
| Array&lt;string&gt; | 返回当前设备作为Server端时连接BLE设备地址集合。 |
**示例:**
......@@ -1125,7 +1127,7 @@ startBLEScan(filters: Array&lt;ScanFilter&gt;, options?: ScanOptions): void
发起BLE扫描流程。
**需要权限**:ohos.permission.DISCOVER_BLUETOOTH;ohos.permission.MANAGE_BLUETOOTH; ohos.permission.LOCATION
**需要权限**:ohos.permission.DISCOVER_BLUETOOTH;ohos.permission.MANAGE_BLUETOOTH;ohos.permission.LOCATION
**系统能力**:SystemCapability.Communication.Bluetooth.Core。
......@@ -1396,7 +1398,7 @@ A2dpSourceProfile.on('connectionStateChange', onReceiveEvent);
### A2dpSourceProfile.off('connectionStateChange')<sup>8+</sup>
off(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
取消订阅a2dp连接状态变化事件。
......@@ -1423,12 +1425,14 @@ A2dpSourceProfile.off('connectionStateChange', onReceiveEvent);
```
### getPlayingState
### getPlayingState<sup>9+</sup>
getPlayingState(device: string): PlayingState
获取设备的播放状态。
**需要权限**:ohos.permission.USE_BLUETOOTH
**系统能力**:SystemCapability.Communication.Bluetooth.Core。
**参数:**
......@@ -1551,7 +1555,7 @@ HandsFreeAudioGatewayProfile.on('connectionStateChange', onReceiveEvent);
### HandsFreeAudioGatewayProfile.off('connectionStateChange')<sup>8+</sup>
off(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
取消订阅HFP连接状态变化事件。
......@@ -1807,6 +1811,16 @@ server端特征值发生变化时,主动通知已连接的client设备。
**示例:**
```js
// 创建descriptors
let descriptors = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
......@@ -2385,14 +2399,9 @@ client端获取蓝牙低功耗设备的所有服务,即服务发现。
```js
// Promise 模式
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
var services = device.getServices();
console.log("bluetooth services size is ", services.length);
for (let i = 0; i < services.length; i++) {
console.log('bluetooth serviceUuid is ' + services[i].serviceUuid);
}
gattClientDevice.getServices().then(result => {
console.info("getServices successfully:" + JSON.stringify(result));
});
```
......@@ -2725,6 +2734,16 @@ setNotifyCharacteristicChanged(characteristic: BLECharacteristic, enable: boolea
**示例:**
```js
// 创建descriptors
let descriptors = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
......
# DataAbility 谓词
DataAbility 谓词用于构造关系型数据库的谓词,提供用于实现不同查询方法的谓词。
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......
# 结果集
结果集是指用户调用关系型数据库查询接口之后返回的结果集合,提供了多种灵活的数据访问方式,以便用户获取各项数据。
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......
......@@ -144,6 +144,8 @@ queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback&lt;Bun
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -180,6 +182,8 @@ queryBundleStateInfos(begin: number, end: number): Promise&lt;BundleActiveInfoRe
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -219,6 +223,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -254,6 +260,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -292,6 +300,8 @@ queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback&lt;A
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -326,6 +336,8 @@ queryBundleActiveStates(begin: number, end: number): Promise&lt;Array&lt;BundleA
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
......@@ -446,8 +458,6 @@ merge(toMerge: BundleStateInfo): void
合并相同包名的应用使用信息。
本接口在OpenHarmony 3.1 Release版本仅为接口定义,暂不支持使用。接口将在OpenHarmony 3.1 MR版本中提供使用支持。
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**参数**
......
......@@ -585,13 +585,12 @@ try {
KVStore数据库类型枚举。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
| 名称 | 值 | 说明 |
| --- | ---- | ----------------------- |
| DEVICE_COLLABORATION | 0 | 表示多设备协同数据库。 |
| SINGLE_VERSION | 1 | 表示单版本数据库。 |
| MULTI_VERSION | 2 | 表示多版本数据库。此类型当前不允许使用。 |
| DEVICE_COLLABORATION | 0 | 表示多设备协同数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| SINGLE_VERSION | 1 | 表示单版本数据库。 <br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| MULTI_VERSION | 2 | 表示多版本数据库。此类型当前不允许使用。 <br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
## SecurityLevel
......
......@@ -2977,7 +2977,7 @@ readSync(): Dirent
```
### close
### close<sup>7+</sup>
close(): Promise&lt;void&gt;
......@@ -2994,7 +2994,7 @@ close(): Promise&lt;void&gt;
```
### close
### close<sup>7+</sup>
close(callback: AsyncCallback&lt;void&gt;): void
......
......@@ -2525,12 +2525,12 @@ function onConsumeCallback(data) {
let wantAgent = data.wantAgent;
wantAgent .getWant(wantAgent)
.then((data1) => {
console.log('===> getWant success want:' + JSON.stringfy(data1));
console.log('===> getWant success want:' + JSON.stringify(data1));
})
.catch((err) => {
console.error('===> getWant failed because' + JSON.stringfy(err));
console.error('===> getWant failed because' + JSON.stringify(err));
});
console.info('===> onConsume callback req.wantAgent:' + JSON.stringfy(req.wantAgent));
console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent));
};
var subscriber = {
......
......@@ -89,7 +89,7 @@
onpaues='pauesCallback' onfinish='finishCallback' onerror='errorCallback'
onseeking='seekingCallback' onseeked='seekedCallback'
ontimeupdate='timeupdateCallback'
style="object-fit:fit; width:80%; height:400px;"
style="object-fit:fill; width:80%; height:400px;"
onclick="change_start_pause">
</video>
</div>
......
......@@ -61,8 +61,6 @@
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.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)
- [QRCode](ts-basic-components-qrcode.md)
- [Radio](ts-basic-components-radio.md)
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册