提交 5919c0fe 编写于 作者: 关明月 提交者: Gitee

Merge branch 'OpenHarmony-3.1-Release' of gitee.com:openharmony/docs into OpenHarmony-3.1-Release

Signed-off-by: N关明月 <guanmingyue@huawei.com>
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
...@@ -43,5 +44,8 @@ ...@@ -43,5 +44,8 @@
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. An ability is the abstraction of a functionality that an application can provide. It is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances.
The ability framework model has two forms. The ability framework model has two forms:
- FA model, which applies to application development using API 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. - FA model, which applies to application development using API version 8 and earlier versions. In the FA model, there is 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. - Stage model, which is introduced since API version 9. In the stage model, there is `Ability` and `ExtensionAbility`. `ExtensionAbility` is further extended to `ServiceExtensionAbility`, `FormExtensionAbility`, `DataShareExtensionAbility`, and more.
The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models. The stage model is designed to make it easier to develop complex applications in the distributed environment. The table below lists the design differences between the two models.
...@@ -14,7 +14,7 @@ The stage model is designed to make it easier to develop complex applications in ...@@ -14,7 +14,7 @@ The stage model is designed to make it easier to develop complex applications in
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported. | Supported. | | Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. 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.| | 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.json5` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). | | Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
In addition, the following differences exist in the development process: In addition, the following differences exist in the development process:
...@@ -27,5 +27,4 @@ In addition, the following differences exist in the development process: ...@@ -27,5 +27,4 @@ In addition, the following differences exist in the development process:
![lifecycle](figures/lifecycle.png) ![lifecycle](figures/lifecycle.png)
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
# Ability Development # Ability Development
## When to Use ## When to Use
Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic: Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json5` and `app.json5` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic:
- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes. - Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page. - Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md). - Call abilities. For details, see [Call Development](stage-call.md).
...@@ -8,7 +8,7 @@ Ability development in the [stage model](stage-brief.md) is significantly differ ...@@ -8,7 +8,7 @@ Ability development in the [stage model](stage-brief.md) is significantly differ
- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md). - Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
### Launch Type ### Launch Type
An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json` file. Depending on the launch type, the action performed when the ability is started differs, as described below. An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json5` file. Depending on the launch type, the action performed when the ability is started differs, as described below.
| Launch Type | Description |Action | | Launch Type | Description |Action |
| ----------- | ------- |---------------- | | ----------- | ------- |---------------- |
...@@ -16,7 +16,7 @@ An ability can be launched in the **standard**, **singleton**, or **specified** ...@@ -16,7 +16,7 @@ An ability can be launched in the **standard**, **singleton**, or **specified**
| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|
By default, the singleton mode is used. The following is an example of the `module.json` file: By default, the singleton mode is used. The following is an example of the `module.json5` file:
```json ```json
{ {
"module": { "module": {
...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h ...@@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h
The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md).
**Table 2** Ability APIs **Table 2** Ability APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.|
...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme ...@@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme
} }
``` ```
### Obtaining AbilityStage and Ability Configurations ### Obtaining AbilityStage and Ability Configurations
Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details.
The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows:
```ts ```ts
import AbilityStage from "@ohos.application.AbilityStage" import AbilityStage from "@ohos.application.AbilityStage"
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
...@@ -145,9 +149,9 @@ export default class MainAbility extends Ability { ...@@ -145,9 +149,9 @@ export default class MainAbility extends Ability {
} }
``` ```
### Requesting Permissions ### Requesting Permissions
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example. If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json5`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example.
Declare the required permission in the `module.json` file. Declare the required permission in the `module.json5` file.
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -269,7 +273,7 @@ function getRemoteDeviceId() { ...@@ -269,7 +273,7 @@ function getRemoteDeviceId() {
``` ```
Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions). Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions).
### Starting an Ability with the Specified Page ### Starting an Ability with the Specified Page
If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback rather than the `onCreate` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows: If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows:
When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information. When using `startAbility` to start an ability again, use the `uri` parameter in the `want` to pass the page information.
```ts ```ts
......
...@@ -61,9 +61,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -61,9 +61,9 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
2. Register the Service Extension ability. 2. Register the Service Extension ability.
Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. Declare the Service Extension ability in the **module.json5** file by setting its **type** attribute to **service**.
**module.json configuration example** **module.json5 configuration example**
```json ```json
"extensionAbilities":[{ "extensionAbilities":[{
......
# Distributed Data Service Overview<a name="EN-US_TOPIC_0000001183067628"></a> # Distributed Data Service Overview
The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. The distributed data service (DDS) implements distributed database collaboration across devices for applications.
## Basic Concepts<a name="section17506141102520"></a> Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices.
You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts
- **KV data model** - **KV data model**
...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati ...@@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati
The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases.
## Working Principles<a name="section315111581616"></a> ## Working Principles
The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following:
...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ...@@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d
![](figures/en-us_image_0000001183386164.png) ![](figures/en-us_image_0000001183386164.png)
## Constraints<a name="section95382010203311"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
- The KV data model specifications supported by the DDS are as follows: - The KV data model specifications supported by the DDS are as follows:
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
A relational database (RDB) store allows you to operate local data with or without native SQL statements based on SQLite. A relational database (RDB) store allows you to manage local data with or without native SQL statements based on SQLite.
## Available APIs ## Available APIs
...@@ -21,11 +21,11 @@ The table below describes the APIs available for creating and deleting an RDB st ...@@ -21,11 +21,11 @@ The table below describes the APIs available for creating and deleting an RDB st
### Managing Data in an RDB Store ### Managing Data in an RDB Store
The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. The **RDB** module provides APIs for inserting, deleting, updating, and querying data in a local RDB store.
- **Inserting Data** - **Inserting Data**
The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. The **RDB** module provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned.
**Table 2** API for inserting data **Table 2** API for inserting data
...@@ -41,7 +41,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -41,7 +41,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data. | | RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -51,7 +51,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -51,7 +51,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data. | | RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data.|
- **Querying data** - **Querying data**
...@@ -69,19 +69,19 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -69,19 +69,19 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
### Using Predicates ### Using Predicates
The RDB provides **RdbPredicates** for you to set database operation conditions. The **RDB** module provides **RdbPredicates** for you to set database operation conditions.
The following lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). The table below lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates).
**Table 6** APIs for using RDB store predicates **Table 6** APIs for using RDB store predicates
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.| | RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.| | RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** object to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
### Using the Result Set ### Using the Result Set
......
# RDB Overview<a name="EN-US_TOPIC_0000001231030607"></a> # RDB Overview
The relational database \(RDB\) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
## Basic Concepts<a name="section1063573420813"></a> You do not need to care about the implementation of the database locking mechanism.
## Basic concepts
- **RDB** - **RDB**
A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store. A type of database created on the basis of relational models. The RDB stores data in rows and columns. A RDB is also called RDB store.
- **Predicate** - **Predicate**
...@@ -14,29 +16,28 @@ The relational database \(RDB\) manages data based on relational models. With th ...@@ -14,29 +16,28 @@ The relational database \(RDB\) manages data based on relational models. With th
- **Result set** - **Result set**
A set of query results used to access the data. You can access the required data in a result set in flexible modes. A set of query results used to access data. You can access the required data in a result set in flexible modes.
- **SQLite database** - **SQLite database**
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability \(ACID\). A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability (ACID).
## Working Principles
## Working Principles<a name="section4810552814"></a> The RDB provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features.
The RDB provides a common operation interface for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. **Figure 1** How RDB works
**Figure 1** How RDB works<a name="fig1826214361535"></a> ![how-rdb-works](figures/how-rdb-works.png)
![](figures/how-rdb-works.png "how-rdb-works")
## Default Settings<a name="section176091243121218"></a> ## Default Settings
- The default database logging mode is write-ahead logging \(WAL\). - The default RDB logging mode is Write Ahead Log (WAL).
- The default database flush mode is Full mode. - The default data flushing mode is **FULL** mode.
- The default shared memory used by the OpenHarmony database is 2 MB. - The default size of the shared memory used by an OpenHarmony database is 2 MB.
## Constraints<a name="section929813398308"></a> ## Constraints
- A maximum of four connection pools can be connected to an RDB to manage read and write operations. - A maximum of four connection pools can be connected to an RDB to manage read and write operations.
- To ensure data accuracy, the RDB supports only one write operation at a time. - To ensure data accuracy, the RDB supports only one write operation at a time.
# Lightweight Data Store Overview<a name="EN-US_TOPIC_0000001230752103"></a> # Lightweight Data Store Overview
Lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight **Storage** instance, data in the **Storage** instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. The lightweight data store is applicable to access and persistence of data in the key-value structure.
## Basic Concepts<a name="section1055404171115"></a> After an application obtains a lightweight store instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
- **Key-Value data structure** You do not need to care about the implementation of the database lock mechanism.
## Basic Concepts
- **Key-value structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
- **Non-relational database** - **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. The data in a non-relational database is independent. A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent.
## Working Principles<a name="section682631371115"></a> ## Working Principles
1. When an application loads data from a specified **Storage** file to a **Storage** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file. 1. An application can load data from a specified **Storage** file to a **Storage** instance. The system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file.
2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method. 2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method.
**Figure 1** How lightweight data store works<a name="fig1657785713509"></a> **Figure 1** Working mechanism
![](figures/en-us_image_0000001199139454.png) ![](figures/en-us_image_0000001199139454.png)
## Constraints<a name="section17243172883219"></a> ## Constraints
- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. - **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters. - The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 bytes.
- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters. - The value of the string type can be empty, but cannot exceed 8192 bytes if not empty.
...@@ -16,7 +16,7 @@ The following table lists the USB APIs currently available. For details, see the ...@@ -16,7 +16,7 @@ The following table lists the USB APIs currently available. For details, see the
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. | | hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. | | requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. | | connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. | | getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
...@@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The ...@@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The
Claim the corresponding interface from deviceList. Claim the corresponding interface from deviceList.
interface1 must be one present in the device configuration. interface1 must be one present in the device configuration.
*/ */
usb.claimInterface(pipe , interface1, true); usb.claimInterface(pipe, interface1, true);
``` ```
4. Perform data transfer. 4. Perform data transfer.
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native_window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
# Brightness # Brightness
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The Brightness module provides an API for setting the screen brightness. The Brightness module provides an API for setting the screen brightness.
> **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 ## Modules to Import
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
## Modules to Import ## Modules to Import
```js ```js
import bytrace from '@ohos.bytrace'; import bytrace from '@ohos.bytrace';
``` ```
...@@ -23,7 +23,7 @@ Marks the start of a timeslice trace task. ...@@ -23,7 +23,7 @@ Marks the start of a timeslice trace task.
> >
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. > If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example.
**System capability**: SystemCapability.Developtools.Bytrace **System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters** **Parameters**
...@@ -36,7 +36,7 @@ Marks the start of a timeslice trace task. ...@@ -36,7 +36,7 @@ Marks the start of a timeslice trace task.
**Example** **Example**
```js ```js
bytrace.startTrace("myTestFunc", 1); bytrace.startTrace("myTestFunc", 1);
bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms. bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms.
``` ```
...@@ -52,7 +52,7 @@ Marks the end of a timeslice trace task. ...@@ -52,7 +52,7 @@ Marks the end of a timeslice trace task.
> >
> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. > To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**System capability**: SystemCapability.Developtools.Bytrace **System capability**: SystemCapability.HiviewDFX.HiTrace
**Parameters** **Parameters**
...@@ -64,7 +64,7 @@ Marks the end of a timeslice trace task. ...@@ -64,7 +64,7 @@ Marks the end of a timeslice trace task.
**Example** **Example**
```js ```js
bytrace.finishTrace("myTestFunc", 1); bytrace.finishTrace("myTestFunc", 1);
``` ```
...@@ -97,7 +97,7 @@ traceByValue(name: string, count: number): void ...@@ -97,7 +97,7 @@ traceByValue(name: string, count: number): void
Defines the variable that indicates the number of timeslice trace tasks. Defines the variable that indicates the number of timeslice trace tasks.
**System capability**: SystemCapability.HiviewDFX.HiTrace **System capability**: HiviewDFX.HiTrace
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -107,7 +107,7 @@ Defines the variable that indicates the number of timeslice trace tasks. ...@@ -107,7 +107,7 @@ Defines the variable that indicates the number of timeslice trace tasks.
**Example** **Example**
```js ```js
let traceCount = 3; let traceCount = 3;
bytrace.traceByValue("myTestCount", traceCount); bytrace.traceByValue("myTestCount", traceCount);
traceCount = 4; traceCount = 4;
......
...@@ -54,7 +54,7 @@ var path; ...@@ -54,7 +54,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
let storage = data_storage.getStorageSync(path + '/mystore'); let storage = data_storage.getStorageSync(path + '/mystore');
...@@ -87,7 +87,7 @@ var path; ...@@ -87,7 +87,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
data_storage.getStorage(path + '/mystore', function (err, storage) { data_storage.getStorage(path + '/mystore', function (err, storage) {
...@@ -130,7 +130,7 @@ var path; ...@@ -130,7 +130,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
let getPromise = data_storage.getStorage(path + '/mystore'); let getPromise = data_storage.getStorage(path + '/mystore');
...@@ -166,7 +166,7 @@ var path; ...@@ -166,7 +166,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
data_storage.deleteStorageSync(path + '/mystore'); data_storage.deleteStorageSync(path + '/mystore');
...@@ -197,7 +197,7 @@ var path; ...@@ -197,7 +197,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
data_storage.deleteStorage(path + '/mystore', function (err) { data_storage.deleteStorage(path + '/mystore', function (err) {
...@@ -238,7 +238,7 @@ var path; ...@@ -238,7 +238,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
let promisedelSt = data_storage.deleteStorage(path + '/mystore'); let promisedelSt = data_storage.deleteStorage(path + '/mystore');
...@@ -273,7 +273,7 @@ var path; ...@@ -273,7 +273,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
data_storage.removeStorageFromCacheSync(path + '/mystore'); data_storage.removeStorageFromCacheSync(path + '/mystore');
...@@ -304,7 +304,7 @@ var path; ...@@ -304,7 +304,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
data_storage.removeStorageFromCache(path + '/mystore', function (err) { data_storage.removeStorageFromCache(path + '/mystore', function (err) {
...@@ -346,7 +346,7 @@ var path; ...@@ -346,7 +346,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
}); });
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
......
# Display # Display
Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. The **Display** module 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** > **NOTE**
> >
...@@ -14,11 +14,11 @@ import display from '@ohos.display'; ...@@ -14,11 +14,11 @@ import display from '@ohos.display';
## DisplayState ## DisplayState
Provides the state of a display. Enumerates the display states.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| STATE_UNKNOWN | 0 | Unknown.| | STATE_UNKNOWN | 0 | Unknown.|
| STATE_OFF | 1 | The display is shut down.| | STATE_OFF | 1 | The display is shut down.|
...@@ -35,163 +35,169 @@ Describes the attributes of a display. ...@@ -35,163 +35,169 @@ Describes the attributes of a display.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Readable| Writable| Description| | Name | Type | Readable | Writable | Description |
| -------- | -------- | -------- | -------- | -------- | | ------------- | ----------------------------- | -------- | -------- | ------------------------------------------------------------ |
| id | number | Yes| No| ID of the display.| | id | number | Yes | No | ID of the display. |
| name | string | Yes| No| Name of the display.| | name | string | Yes | No | Name of the display. |
| alive | boolean | Yes| No| Whether the display is alive.| | alive | boolean | Yes | No | Whether the display is alive. |
| state | [DisplayState](#displaystate) | Yes| No| State of the display.| | state | [DisplayState](#displaystate) | Yes | No | State of the display. |
| refreshRate | number | Yes| No| Refresh rate of the display.| | refreshRate | number | Yes | No | Refresh rate of the display. |
| rotation | number | Yes| No| Screen rotation angle of the display.| | rotation | number | Yes | No | Screen rotation angle of the display. |
| width | number | Yes| No| Width of the display, in pixels.| | width | number | Yes | No | Width of the display, in pixels. |
| height | number | Yes| No| Height of the display, in pixels.| | height | number | Yes | No | Height of the display, in pixels. |
| densityDPI | number | Yes| No| Screen density of the display, in DPI.| | densityDPI | number | Yes | No | Screen density of the display, in DPI. |
| densityPixels | number | Yes| No| Screen density of the display, in pixels.| | densityPixels | number | Yes | No | Screen density of the display, in pixels. |
| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| | scaledDensity | number | Yes | No | Scaling factor for fonts displayed on the display. |
| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| | xDPI | number | Yes | No | Exact physical dots per inch of the screen in the horizontal direction. |
| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| | yDPI | number | Yes | No | Exact physical dots per inch of the screen in the vertical direction. |
## display.getDefaultDisplay ## display.getDefaultDisplay
getDefaultDisplay(callback: AsyncCallback&lt;Display&gt;): void getDefaultDisplay(callback: AsyncCallback&lt;Display&gt;): void
Obtains the default display object. Obtains the default display object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| callback | AsyncCallback&lt;[Display](#display)&gt; | Yes| Callback used to return the default display object.| | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[Display](#display)&gt; | Yes| Callback used to return the default display object.|
**Example** **Example**
```js
var displayClass = null; ```js
display.getDefaultDisplay((err, data) => { var displayClass = null;
display.getDefaultDisplay((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
displayClass = data; displayClass = data;
}); });
``` ```
## display.getDefaultDisplay ## display.getDefaultDisplay
getDefaultDisplay(): Promise&lt;Display&gt; getDefaultDisplay(): Promise&lt;Display&gt;
Obtains the default display object. Obtains the default display object. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ---------------------------------------------- | | ---------------------------------- | ---------------------------------------------- |
| Promise&lt;[Display](#display)&gt; | Promise used to return the default display object.| | Promise&lt;[Display](#display)&gt; | Promise used to return the default display object.|
**Example** **Example**
```js ```js
let promise = display.getDefaultDisplay(); var displayClass = null;
promise.then(() => { let promise = display.getDefaultDisplay();
console.log('getDefaultDisplay success'); promise.then((data) => {
}).catch((err) => { displayClass = data;
console.log('getDefaultDisplay fail: ' + JSON.stringify(err)); console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data));
}); }).catch((err) => {
``` console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
});
```
## display.getAllDisplay ## display.getAllDisplay
getAllDisplay(callback: AsyncCallback&lt;Array&lt;Display&gt;&gt;): void getAllDisplay(callback: AsyncCallback&lt;Array&lt;Display&gt;&gt;): void
Obtains all the display objects. Obtains all display objects. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------- | ---- | ------------------------------- | | -------- | ---------------------------------------------------- | ---- | ------------------------------- |
| callback | AsyncCallback&lt;Array&lt;[Display](#display)&gt;&gt; | Yes | Callback used to return all the display objects.| | callback | AsyncCallback&lt;Array&lt;[Display](#display)&gt;&gt; | Yes | Callback used to return all the display objects.|
**Example** **Example**
```js ```js
display.getAllDisplay((err, data) => { display.getAllDisplay((err, data) => {
if (err.code) { if (err.code) {
console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
return; return;
} }
console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)) console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data));
}); });
``` ```
## display.getAllDisplay ## display.getAllDisplay
getAllDisplay(): Promise&lt;Array&lt;Display&gt;&gt; getAllDisplay(): Promise&lt;Array&lt;Display&gt;&gt;
Obtains all the display objects. Obtains all display objects. This API uses a promise to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------------- | ------------------------------------------------------- | | ----------------------------------------------- | ------------------------------------------------------- |
| Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return all the display objects.| | Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return all the display objects.|
**Example** **Example**
```js ```js
let promise = display.getAllDisplay(); let promise = display.getAllDisplay();
promise.then(() => { promise.then((data) => {
console.log('getAllDisplay success'); console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log('getAllDisplay fail: ' + JSON.stringify(err)); console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err));
}); });
``` ```
## display.on('add'|'remove'|'change') ## display.on('add'|'remove'|'change')
on(type: 'add'|'remove'|'change', callback: Callback&lt;number&gt;): void on(type: 'add'|'remove'|'change', callback: Callback&lt;number&gt;): void
Enables listening. Subscribes to display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| 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.| | type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example** **Example**
```js
var callback = (data) => { ```js
var callback = (data) => {
console.info('Listening enabled. Data: ' + JSON.stringify(data)) console.info('Listening enabled. Data: ' + JSON.stringify(data))
} }
display.on("add", callback); display.on("add", callback);
``` ```
## display.off('add'|'remove'|'change') ## display.off('add'|'remove'|'change')
off(type: 'add'|'remove'|'change', callback?: Callback&lt;number&gt;): void off(type: 'add'|'remove'|'change', callback?: Callback&lt;number&gt;): void
Disables listening. Unsubscribes from display changes.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| 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.| | type | string | Yes| Event type.<br>- **add**, indicating the display addition event.<br>- **remove**, indicating the display removal event.<br>- **change**, indicating the display change event.|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example** **Example**
```js ```js
display.off("remove"); display.off("remove");
``` ```
...@@ -138,7 +138,7 @@ Starts an ability. This API uses a callback to return the execution result when ...@@ -138,7 +138,7 @@ Starts an ability. This API uses a callback to return the execution result when
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant'
featureAbility.startAbilityForResult( featureAbility.startAbilityForResult(
{ {
...@@ -154,6 +154,9 @@ featureAbility.startAbilityForResult( ...@@ -154,6 +154,9 @@ featureAbility.startAbilityForResult(
uri:"" uri:""
}, },
}, },
(err, data) => {
console.info("err: " + JSON.stringify(err) + "data: " + JSON.stringify(data))
}
) )
``` ```
...@@ -180,7 +183,7 @@ Starts an ability. This API uses a promise to return the execution result when t ...@@ -180,7 +183,7 @@ Starts an ability. This API uses a promise to return the execution result when t
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant'
featureAbility.startAbilityForResult( featureAbility.startAbilityForResult(
{ {
...@@ -284,7 +287,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -284,7 +287,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant'
featureAbility.terminateSelfWithResult( featureAbility.terminateSelfWithResult(
{ {
...@@ -335,7 +338,7 @@ Checks whether the main window of this ability has the focus. This API uses a ca ...@@ -335,7 +338,7 @@ Checks whether the main window of this ability has the focus. This API uses a ca
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.hasWindowFocus() featureAbility.hasWindowFocus()
``` ```
...@@ -358,7 +361,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr ...@@ -358,7 +361,7 @@ Checks whether the main window of this ability has the focus. This API uses a pr
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.hasWindowFocus().then((data) => { featureAbility.hasWindowFocus().then((data) => {
console.info("==========================>hasWindowFocus=======================>"); console.info("==========================>hasWindowFocus=======================>");
}); });
...@@ -383,7 +386,7 @@ Obtains the **Want** object sent from this ability. This API uses a callback to ...@@ -383,7 +386,7 @@ Obtains the **Want** object sent from this ability. This API uses a callback to
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.getWant() featureAbility.getWant()
``` ```
...@@ -406,7 +409,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r ...@@ -406,7 +409,7 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.getWant().then((data) => { featureAbility.getWant().then((data) => {
console.info("==========================>getWantCallBack=======================>"); console.info("==========================>getWantCallBack=======================>");
}); });
...@@ -429,7 +432,7 @@ Obtains the application context. ...@@ -429,7 +432,7 @@ Obtains the application context.
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
var context = featureAbility.getContext() var context = featureAbility.getContext()
context.getBundleName() context.getBundleName()
``` ```
...@@ -453,7 +456,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -453,7 +456,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.terminateSelf() featureAbility.terminateSelf()
``` ```
...@@ -476,7 +479,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th ...@@ -476,7 +479,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th
**Example** **Example**
```javascript ```javascript
import featureAbility from '@ohos.ability.featureability'; import featureAbility from '@ohos.ability.featureAbility';
featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelfCallBack=======================>"); featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelfCallBack=======================>");
}); });
``` ```
...@@ -926,6 +929,8 @@ Enumerates operation types of the Data ability. ...@@ -926,6 +929,8 @@ Enumerates operation types of the Data ability.
| action | Read-only | string | No | Action option. | | action | Read-only | string | No | Action option. |
| parameters | Read-only | {[key: string]: any} | No | List of parameters in the **Want** object. | | parameters | Read-only | {[key: string]: any} | No | List of parameters in the **Want** object. |
| entities | Read-only | Array\<string> | No | List of entities. | | entities | Read-only | Array\<string> | No | List of entities. |
| extensionAbilityType<sup>9+</sup> | Read-only | bundle.ExtensionAbilityType | No | Type of the Extension ability. |
| extensionAbilityName<sup>9+<sup> | Read-only | string | No | Description of the Extension ability name in the **Want** object. |
## flags ## flags
......
# HiLog # HiLog
The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. The HiLog module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs.
> **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -23,8 +23,8 @@ Checks whether logs are printable based on the specified service domain, log tag ...@@ -23,8 +23,8 @@ Checks whether logs are printable based on the specified service domain, log tag
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | --------------------- | ---- | ------------------------------------------------------------ | | ------ | --------------------- | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| level | [LogLevel](#loglevel) | Yes | Log level. | | level | [LogLevel](#loglevel) | Yes | Log level. |
**Return value** **Return value**
...@@ -48,7 +48,7 @@ Enumerates the log levels. ...@@ -48,7 +48,7 @@ Enumerates the log levels.
| Name | Default Value| Description | | Name | Default Value| Description |
| ----- | ------ | ------------------------------------------------------------ | | ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| | INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running, for example, no network signal or login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
| WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.| | WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.|
| ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.| | ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.|
| FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified. | | FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified. |
...@@ -67,8 +67,8 @@ DEBUG logs are not recorded in official versions by default. They are available ...@@ -67,8 +67,8 @@ DEBUG logs are not recorded in official versions by default. They are available
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
...@@ -98,8 +98,8 @@ Prints INFO logs. ...@@ -98,8 +98,8 @@ Prints INFO logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
...@@ -129,8 +129,8 @@ Prints WARN logs. ...@@ -129,8 +129,8 @@ Prints WARN logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
...@@ -160,8 +160,8 @@ Prints ERROR logs. ...@@ -160,8 +160,8 @@ Prints ERROR logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
...@@ -191,8 +191,8 @@ Prints FATAL logs. ...@@ -191,8 +191,8 @@ Prints FATAL logs.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.| | domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br/>You can define the value as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.| | tag | string | Yes | Log tag in the string format.<br/>You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.| | format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.| | args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......
# Performance Tracing # Performance Tracing
This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. The Performance Tracing 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> > **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -17,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; ...@@ -17,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter';
startTrace(name: string, taskId: number): void startTrace(name: string, taskId: number): void
Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. Starts a trace task.
If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**.
......
# Log # Log
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** The Log module provides basic log printing capabilities and supports log printing by log level.
> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead.
## console.debug If you want to use more advanced log printing services, for example, filtering logs by the specified ID, you are advised to use [`@ohos.hilog`](js-apis-hilog.md).
debug(message: string): void
Prints debug logs. > **NOTE**
>
- Parameters > The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.log ## console.log
log(message: string): void log(message: string): void
Prints debug logs. Prints logs.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
- Parameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----------- |
| ------- | ------ | ---- | ----------- | | message | string | Yes | Text to print.|
| message | string | Yes | Text to print.|
## console.debug
debug(message: string): void
Prints debug-level logs.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.info ## console.info
...@@ -33,10 +45,13 @@ info(message: string): void ...@@ -33,10 +45,13 @@ info(message: string): void
Prints info-level logs. Prints info-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.warn ## console.warn
...@@ -45,10 +60,13 @@ warn(message: string): void ...@@ -45,10 +60,13 @@ warn(message: string): void
Prints warn-level logs. Prints warn-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## console.error ## console.error
...@@ -57,10 +75,13 @@ error(message: string): void ...@@ -57,10 +75,13 @@ error(message: string): void
Prints error-level logs. Prints error-level logs.
- Parameters **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- | **Parameters**
| message | string | Yes | Text to print.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----------- |
| message | string | Yes | Text to print.|
## Example ## Example
......
...@@ -26,6 +26,7 @@ Sets the media query criteria and returns the corresponding listening handle. ...@@ -26,6 +26,7 @@ Sets the media query criteria and returns the corresponding listening handle.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| | 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).|
...@@ -37,7 +38,7 @@ Sets the media query criteria and returns the corresponding listening handle. ...@@ -37,7 +38,7 @@ Sets the media query criteria and returns the corresponding listening handle.
**Example** **Example**
```js ```js
listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
``` ```
...@@ -66,7 +67,7 @@ Registers a callback with the corresponding query condition by using the handle. ...@@ -66,7 +67,7 @@ Registers a callback with the corresponding query condition by using the handle.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ---------------- | | -------- | -------------------------------- | ---- | ---------------- |
| type | string | Yes | Must enter the string **'change'**.| | type | string | Yes | Must enter the string **change**.|
| callback | Callback&lt;MediaQueryResult&gt; | Yes | Callback registered with media query. | | callback | Callback&lt;MediaQueryResult&gt; | Yes | Callback registered with media query. |
**Example** **Example**
...@@ -88,7 +89,7 @@ Deregisters a callback with the corresponding query condition by using the handl ...@@ -88,7 +89,7 @@ Deregisters a callback with the corresponding query condition by using the handl
| callback | Callback&lt;MediaQueryResult&gt; | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| | callback | Callback&lt;MediaQueryResult&gt; | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.|
**Example** **Example**
```js ```ts
import mediaquery from '@ohos.mediaquery' import mediaquery from '@ohos.mediaquery'
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
...@@ -117,10 +118,9 @@ Deregisters a callback with the corresponding query condition by using the handl ...@@ -117,10 +118,9 @@ Deregisters a callback with the corresponding query condition by using the handl
### Example ### Example
```js ```ts
import mediaquery from '@ohos.mediaquery' import mediaquery from '@ohos.mediaquery'
let portraitFunc = null
@Entry @Entry
@Component @Component
...@@ -140,7 +140,7 @@ struct MediaQueryExample { ...@@ -140,7 +140,7 @@ struct MediaQueryExample {
} }
aboutToAppear() { aboutToAppear() {
portraitFunc = this.onPortrait.bind(this) //bind current js instance let portraitFunc = this.onPortrait.bind(this) // Bind the current JS instance.
this.listener.on('change', portraitFunc) this.listener.on('change', portraitFunc)
} }
......
# Sensor # Sensor
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -1351,8 +1350,6 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback&lt;HumidityRes ...@@ -1351,8 +1350,6 @@ off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback&lt;HumidityRes
Unsubscribes from sensor data changes. Unsubscribes from sensor data changes.
**Required permissions**: ohos.permission.READ_HEALTH_DATA (a system permission)
**System capability**: SystemCapability.Sensors.Sensor **System capability**: SystemCapability.Sensors.Sensor
**Parameters** **Parameters**
...@@ -1405,8 +1402,6 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback); ...@@ -1405,8 +1402,6 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback);
Unsubscribes from sensor data changes. Unsubscribes from sensor data changes.
**Required permissions**: ohos.permission.ACCELEROMETER (a system permission)
**System capability**: SystemCapability.Sensors.Sensor **System capability**: SystemCapability.Sensors.Sensor
**Parameters** **Parameters**
...@@ -1488,6 +1483,8 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback&lt;PedometerR ...@@ -1488,6 +1483,8 @@ off(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback?: Callback&lt;PedometerR
Unsubscribes from sensor data changes. Unsubscribes from sensor data changes.
**Required permissions**: ohos.permission.ACTIVITY_MOTION
**System capability**: SystemCapability.Sensors.Sensor **System capability**: SystemCapability.Sensors.Sensor
**Parameters** **Parameters**
...@@ -1718,7 +1715,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000 ...@@ -1718,7 +1715,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000
console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message);
return; return;
} }
console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + console.info('sensor_getGeomagneticField_callback x: ' + data.x + ',y: ' + data.y + ',z: ' +
data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle +
',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity);
}); });
...@@ -1900,7 +1897,6 @@ Obtains the angle change between two rotation matrices. This API uses a callback ...@@ -1900,7 +1897,6 @@ Obtains the angle change between two rotation matrices. This API uses a callback
err.message); err.message);
return; return;
} }
console.info("SensorJsAPI--->Successed to get getAngleModifiy interface get data: " + data.x);
for (var i=0; i < data.length; i++) { for (var i=0; i < data.length; i++) {
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
...@@ -1968,7 +1964,6 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r ...@@ -1968,7 +1964,6 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r
err.message); err.message);
return; return;
} }
console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x);
for (var i=0; i < data.length; i++) { for (var i=0; i < data.length; i++) {
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
...@@ -2035,7 +2030,6 @@ Converts a rotation vector into a quaternion. This API uses a callback to return ...@@ -2035,7 +2030,6 @@ Converts a rotation vector into a quaternion. This API uses a callback to return
err.message); err.message);
return; return;
} }
console.info("SensorJsAPI--->Successed to get createQuaternion interface get data: " + data.x);
for (var i=0; i < data.length; i++) { for (var i=0; i < data.length; i++) {
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
...@@ -2102,7 +2096,6 @@ Obtains the device direction based on the rotation matrix. This API uses a callb ...@@ -2102,7 +2096,6 @@ Obtains the device direction based on the rotation matrix. This API uses a callb
err.message); err.message);
return; return;
} }
console.info("SensorJsAPI--->Successed to get getDirection interface get data: " + data);
for (var i = 1; i < data.length; i++) { for (var i = 1; i < data.length; i++) {
console.info("sensor_getDirection_callback" + data[i]); console.info("sensor_getDirection_callback" + data[i]);
} }
...@@ -2170,7 +2163,6 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th ...@@ -2170,7 +2163,6 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th
err.message); err.message);
return; return;
} }
console.info("SensorJsAPI--->Successed to get createRotationMatrix interface get data: " + data.x);
for (var i=0; i < data.rotation.length; i++) { for (var i=0; i < data.rotation.length; i++) {
console.info("data[" + i + "]: " + data[i]) console.info("data[" + i + "]: " + data[i])
} }
...@@ -2419,9 +2411,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response). ...@@ -2419,9 +2411,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response).
**System capability**: SystemCapability.Sensors.Sensor **System capability**: SystemCapability.Sensors.Sensor
| Name | Type | Readable | Writable | Description | | Name | Type| Readable| Writable| Description |
| ------ | ------ | ---- | ---- | --------------------------------- | | ------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| | status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field does not exist, and a value greater than **0** means the opposite.|
## MagneticFieldResponse ## MagneticFieldResponse
......
# Battery Level # Battery Level
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. > - The APIs of this module are no longer maintained since API version 6. You are advised to use [`@ohos.batteryInfo`](js-apis-battery-info.md).
> >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -22,20 +22,13 @@ Obtains the current charging state and battery level. ...@@ -22,20 +22,13 @@ Obtains the current charging state and battery level.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core **System capability**: SystemCapability.PowerManager.BatteryManager.Core
**Parameter** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;check&nbsp;result&nbsp;is&nbsp;obtained | | success | (data: [BatteryResponse](#batteryresponse)) => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;check&nbsp;result&nbsp;fails&nbsp;to&nbsp;be&nbsp;obtained | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete | | complete | () => void | No| Called when API call is complete.|
The following value will be returned when the check result is obtained.
| Name | Type | Description |
| -------- | -------- | -------- |
| charging | boolean | Whether&nbsp;the&nbsp;battery&nbsp;is&nbsp;being&nbsp;charged |
| level | number | Current&nbsp;battery&nbsp;level,&nbsp;which&nbsp;ranges&nbsp;from&nbsp;0.00&nbsp;to&nbsp;1.00. |
**Example** **Example**
...@@ -53,3 +46,10 @@ export default { ...@@ -53,3 +46,10 @@ export default {
}, },
} }
``` ```
## BatteryResponse
| Name| Type| Description|
| -------- | -------- | -------- |
| charging | boolean | Whether the battery is being charged.|
| level | number | Current battery level, which ranges from **0.00** to **1.00**.|
# Screen Brightness # Screen Brightness
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** > **NOTE**
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.brightness`](js-apis-brightness.md).
> >
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -24,22 +24,23 @@ Obtains the current screen brightness. ...@@ -24,22 +24,23 @@ Obtains the current screen brightness.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | (data: [BrightnessResponse](#brightnessresponse)) => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete | | complete | () => void | No| Called when API call is complete.|
The following values will be returned when the operation is successful. **Return value of success()**
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| value | number | Screen&nbsp;brightness,&nbsp;which&nbsp;ranges&nbsp;from&nbsp;1&nbsp;to&nbsp;255. | | value | number | Screen brightness. The value is an integer ranging from **1** to **255**.|
**Example** **Example**
```js ```js
export default { export default {
getValue() { getValue() {
brightness.getValue({ brightness.getValue({
success: function(data){ success: function(data){
...@@ -50,8 +51,8 @@ export default { ...@@ -50,8 +51,8 @@ export default {
}, },
}); });
}, },
} }
``` ```
## brightness.setValue ## brightness.setValue
...@@ -64,17 +65,17 @@ Sets the screen brightness. ...@@ -64,17 +65,17 @@ Sets the screen brightness.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes | Screen&nbsp;brightness.&nbsp;The&nbsp;value&nbsp;is&nbsp;an&nbsp;integer&nbsp;ranging&nbsp;from&nbsp;1&nbsp;to&nbsp;255.<br/>-&nbsp;If&nbsp;the&nbsp;value&nbsp;is&nbsp;less&nbsp;than&nbsp;or&nbsp;equal&nbsp;to&nbsp;**0**,&nbsp;value&nbsp;**1**&nbsp;will&nbsp;be&nbsp;used.<br/>-&nbsp;If&nbsp;the&nbsp;value&nbsp;is&nbsp;greater&nbsp;than&nbsp;**255**,&nbsp;value&nbsp;**255**&nbsp;will&nbsp;be&nbsp;used.<br/>-&nbsp;If&nbsp;the&nbsp;value&nbsp;contains&nbsp;decimals,&nbsp;the&nbsp;integral&nbsp;part&nbsp;of&nbsp;the&nbsp;value&nbsp;will&nbsp;be&nbsp;used.&nbsp;For&nbsp;example,&nbsp;if&nbsp;value&nbsp;**8.1**&nbsp;is&nbsp;set,&nbsp;value&nbsp;**8**&nbsp;will&nbsp;be&nbsp;used. | | value | number | Yes| Screen brightness. The value is an integer ranging from **1** to **255**.<br>- If the value is less than or equal to **0**, value **1** will be used.<br>- If the value is greater than **255**, value **255** will be used.<br>- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.|
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | () => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete. | | complete | () => void | No| Called when API call is complete.|
**Example** **Example**
```js ```js
export default { export default {
setValue() { setValue() {
brightness.setValue({ brightness.setValue({
value: 100, value: 100,
...@@ -86,8 +87,8 @@ export default { ...@@ -86,8 +87,8 @@ export default {
}, },
}); });
}, },
} }
``` ```
## brightness.getMode ## brightness.getMode
...@@ -100,22 +101,22 @@ Obtains the screen brightness adjustment mode. ...@@ -100,22 +101,22 @@ Obtains the screen brightness adjustment mode.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete | | complete | () => void | No| Called when API call is complete.|
The following values will be returned when the operation is successful. **Return value of success()**
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| mode | number | The&nbsp;value&nbsp;can&nbsp;be&nbsp;**0**&nbsp;or&nbsp;**1**.<br/>-&nbsp;**0**:&nbsp;The&nbsp;screen&nbsp;brightness&nbsp;is&nbsp;manually&nbsp;adjusted.<br/>-&nbsp;**1**:&nbsp;The&nbsp;screen&nbsp;brightness&nbsp;is&nbsp;automatically&nbsp;adjusted. | | mode | number | The value can be **0** or **1**.<br>- **0**: manual adjustment<br>- **1**: automatic adjustment|
**Example** **Example**
```js ```js
export default { export default {
getMode() { getMode() {
brightness.getMode({ brightness.getMode({
success: function(data){ success: function(data){
...@@ -126,8 +127,8 @@ export default { ...@@ -126,8 +127,8 @@ export default {
}, },
}); });
}, },
} }
``` ```
## brightness.setMode ## brightness.setMode
...@@ -139,18 +140,17 @@ Sets the screen brightness adjustment mode. ...@@ -139,18 +140,17 @@ Sets the screen brightness adjustment mode.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager **System capability**: SystemCapability.PowerManager.DisplayPowerManager
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mode | number | Yes | The&nbsp;value&nbsp;can&nbsp;be&nbsp;**0**&nbsp;or&nbsp;**1**.<br/>-&nbsp;**0**:&nbsp;The&nbsp;screen&nbsp;brightness&nbsp;is&nbsp;manually&nbsp;adjusted.<br/>-&nbsp;**1**:&nbsp;The&nbsp;screen&nbsp;brightness&nbsp;is&nbsp;automatically&nbsp;adjusted. | | mode | number | Yes| The value can be **0** or **1**.<br>- **0**: manual adjustment<br>- **1**: automatic adjustment|
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | () => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete. | | complete | () => void | No| Called when API call is complete.|
**Example** **Example**
```js ```js
export default { export default {
setMode() { setMode() {
brightness.setMode({ brightness.setMode({
mode: 1, mode: 1,
...@@ -162,8 +162,8 @@ export default { ...@@ -162,8 +162,8 @@ export default {
}, },
}); });
}, },
} }
``` ```
## brightness.setKeepScreenOn ## brightness.setKeepScreenOn
...@@ -175,18 +175,17 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. ...@@ -175,18 +175,17 @@ Sets whether to always keep the screen on. Call this API in **onShow()**.
**System capability**: SystemCapability.PowerManager.DisplayPowerManager **System capability**: SystemCapability.PowerManager.DisplayPowerManager
**Parameters** **Parameters**
| Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| keepScreenOn | boolean | Yes | Whether&nbsp;to&nbsp;always&nbsp;keep&nbsp;the&nbsp;screen&nbsp;on | | keepScreenOn | boolean | Yes| Whether to keep the screen on.|
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. | | success | () => void | No| Called when API call is successful.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. | | fail | (data: string, code: number) => void | No| Called when API call has failed.|
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete. | | complete | () => void | No| Called when API call is complete.|
**Example** **Example**
```js ```js
export default { export default {
setKeepScreenOn() { setKeepScreenOn() {
brightness.setKeepScreenOn({ brightness.setKeepScreenOn({
keepScreenOn: true, keepScreenOn: true,
...@@ -198,5 +197,18 @@ export default { ...@@ -198,5 +197,18 @@ export default {
}, },
}); });
}, },
} }
``` ```
\ No newline at end of file ##
## BrightnessResponse
| Name| Type | Description|
| -------- | -------- | -------- |
| value | number | Screen brightness. The value is an integer ranging from **1** to **255**.|
## BrightnessModeResponse
| Name| Type | Description|
| -------- | -------- | -------- |
| mode | number | The value can be **0** or **1**.<br> - **0**: manual adjustment<br>- **0**: manual adjustment|
# Timer # Timer
The **Timer** module provides basic timer capabilities. You can use the APIs of this module to execute functions at the specified time.
> **NOTE**
>
> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## setTimeout ## setTimeout
...@@ -7,6 +12,8 @@ setTimeout(handler[,delay[,…args]]): number ...@@ -7,6 +12,8 @@ setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off. Sets a timer for the system to call a function after the timer goes off.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -23,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off. ...@@ -23,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off.
**Example** **Example**
```js ```js
export default { export default {
setTimeOut() { setTimeOut() {
var timeoutID = setTimeout(function() { var timeoutID = setTimeout(function() {
console.log('delay 1s'); console.log('delay 1s');
}, 1000); }, 1000);
} }
} }
``` ```
## clearTimeout ## clearTimeout
...@@ -40,6 +47,8 @@ clearTimeout(timeoutID: number): void ...@@ -40,6 +47,8 @@ clearTimeout(timeoutID: number): void
Cancels the timer created via **setTimeout()**. Cancels the timer created via **setTimeout()**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -48,16 +57,16 @@ Cancels the timer created via **setTimeout()**. ...@@ -48,16 +57,16 @@ Cancels the timer created via **setTimeout()**.
**Example** **Example**
```js ```js
export default { export default {
clearTimeOut() { clearTimeOut() {
var timeoutID = setTimeout(function() { var timeoutID = setTimeout(function() {
console.log('do after 1s delay.'); console.log('do after 1s delay.');
}, 1000); }, 1000);
clearTimeout(timeoutID); clearTimeout(timeoutID);
} }
} }
``` ```
## setInterval ## setInterval
...@@ -66,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number ...@@ -66,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number
Sets a repeating timer for the system to repeatedly call a function at a fixed interval. Sets a repeating timer for the system to repeatedly call a function at a fixed interval.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -82,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i ...@@ -82,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i
**Example** **Example**
```js ```js
export default { export default {
setInterval() { setInterval() {
var intervalID = setInterval(function() { var intervalID = setInterval(function() {
console.log('do very 1s.'); console.log('do very 1s.');
}, 1000); }, 1000);
} }
} }
``` ```
## clearInterval ## clearInterval
...@@ -99,6 +110,8 @@ clearInterval(intervalID: number): void ...@@ -99,6 +110,8 @@ clearInterval(intervalID: number): void
Cancels the repeating timer set via **setInterval()**. Cancels the repeating timer set via **setInterval()**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -107,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**. ...@@ -107,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**.
**Example** **Example**
```js ```js
export default { export default {
clearInterval() { clearInterval() {
var intervalID = setInterval(function() { var intervalID = setInterval(function() {
console.log('do very 1s.'); console.log('do very 1s.');
}, 1000); }, 1000);
clearInterval(intervalID); clearInterval(intervalID);
} }
} }
``` ```
\ No newline at end of file
...@@ -10,7 +10,6 @@ This module provides the following common window-related functions: ...@@ -10,7 +10,6 @@ This module provides the following common window-related functions:
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```js
...@@ -36,7 +35,7 @@ Enumerates the types of the area where the window cannot be displayed. ...@@ -36,7 +35,7 @@ Enumerates the types of the area where the window cannot be displayed.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Value | Description | | Name | Value | Description |
| ----------- | ---- | ------------------ | |----------------------------------|-----| ----------------- |
| TYPE_SYSTEM | 0 | Default area of the system.| | TYPE_SYSTEM | 0 | Default area of the system.|
| TYPE_CUTOUT | 1 | Notch. | | TYPE_CUTOUT | 1 | Notch. |
...@@ -64,11 +63,11 @@ Describes the properties of the status bar and navigation bar. ...@@ -64,11 +63,11 @@ Describes the properties of the status bar and navigation bar.
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | | -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ |
| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| isStatusBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the status bar is highlighted. | | isStatusBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the status bar is highlighted. |
| statusBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the status bar. | | statusBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the status bar. |
| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| isNavigationBarLightIcon<sup>7+</sup> | boolean | No | No | Whether any icon on the navigation bar is highlighted. | | isNavigationBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. |
| navigationBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the navigation bar. | | navigationBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the navigation bar. |
## SystemBarRegionTint<sup>8+</sup> ## SystemBarRegionTint<sup>8+</sup>
...@@ -81,11 +80,11 @@ Describes the callback for a single system bar. ...@@ -81,11 +80,11 @@ Describes the callback for a single system bar.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| type | [WindowType](#windowtype) | Yes | Yes | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| | type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.|
| isEnable | boolean | Yes | Yes | Whether the system bar is displayed. | | isEnable | boolean | Yes | No | Whether the system bar is displayed. |
| region | [Rect](#rect) | Yes | Yes | Current position and size of the system bar. | | region | [Rect](#rect) | Yes | No | Current position and size of the system bar. |
| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| contentColor | string | Yes | Yes | Color of the text on the system bar. | | contentColor | string | Yes | No | Color of the text on the system bar. |
## SystemBarTintState<sup>8+</sup> ## SystemBarTintState<sup>8+</sup>
...@@ -98,7 +97,7 @@ Describes the callback for the current system bar. ...@@ -98,7 +97,7 @@ Describes the callback for the current system bar.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- | | ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- |
| displayId | number | Yes | No | ID of the current physical screen. | | displayId | number | Yes | No | ID of the current physical screen. |
| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information that has been changed.| | regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | No | All system bar information that has been changed.|
## Rect<sup>7+</sup> ## Rect<sup>7+</sup>
...@@ -126,6 +125,7 @@ Describes the area where the window cannot be displayed. ...@@ -126,6 +125,7 @@ Describes the area where the window cannot be displayed.
| rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| | rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.|
| bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.| | bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.|
## Size<sup>7+</sup> ## Size<sup>7+</sup>
Describes the window size. Describes the window size.
...@@ -144,7 +144,7 @@ Describes the window properties. ...@@ -144,7 +144,7 @@ Describes the window properties.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | | ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| windowRect<sup>7+</sup> | [Rect](#rect) | Yes | Yes | Window size. | | windowRect<sup>7+</sup> | [Rect](#rect) | Yes | Yes | Window size. |
| type<sup>7+</sup> | [WindowType](#windowtype) | Yes | Yes | Window type. | | type<sup>7+</sup> | [WindowType](#windowtype) | Yes | Yes | Window type. |
| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | | isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. |
...@@ -152,7 +152,7 @@ Describes the window properties. ...@@ -152,7 +152,7 @@ Describes the window properties.
| focusable<sup>7+</sup> | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | | focusable<sup>7+</sup> | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. |
| touchable<sup>7+</sup> | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | | touchable<sup>7+</sup> | boolean | Yes | No | Whether the window is touchable. The default value is `true`. |
| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | | brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. |
| dimBehindValue<sup>7+</sup> | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.| | dimBehindValue<sup>7+</sup> | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness. |
| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | | isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. |
| isPrivacyMode<sup>7+</sup> | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | | isPrivacyMode<sup>7+</sup> | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. |
| isRoundCorner<sup>7+</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | | isRoundCorner<sup>7+</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. |
...@@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous ...@@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| ctx | [Context](js-apis-Context.md) | Yes | Current application context. | | ctx | [Context](js-apis-Context.md) | Yes | Current application context.|
| callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the top window obtained. | | callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the top window obtained. |
**Example** **Example**
...@@ -938,7 +938,7 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -938,7 +938,7 @@ Obtains the area where this window cannot be displayed, for example, the system
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.|
| callback | AsyncCallback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. | | callback | AsyncCallback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. |
...@@ -966,19 +966,20 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -966,19 +966,20 @@ Obtains the area where this window cannot be displayed, for example, the system
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | ------------------------------------------------------------ | | ------ |----------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------------------------------- | ----------------------------------- | |-----------------------------------------| ----------------------------------- |
| Promise&lt;[AvoidArea](#avoidarea)&gt; | Promise used to return the area.| | Promise&lt;[AvoidArea](#avoidarea)&gt; | Promise used to return the area.|
**Example** **Example**
```js ```js
let promise = windowClass.getAvoidArea(); var type = window.AvoidAreaType.TYPE_SYSTEM;
let promise = windowClass.getAvoidArea(type);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
}).catch((err)=>{ }).catch((err)=>{
...@@ -1315,7 +1316,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback ...@@ -1315,7 +1316,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.|
**Example** **Example**
...@@ -1341,7 +1342,7 @@ Checks whether this window is displayed. This API uses a promise to return the r ...@@ -1341,7 +1342,7 @@ Checks whether this window is displayed. This API uses a promise to return the r
| Type | Description | | Type | Description |
| ---------------------- | ------------------------------------------------------------ | | ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.|
**Example** **Example**
...@@ -1409,7 +1410,7 @@ Enables listening for changes to the area where the window cannot be displayed. ...@@ -1409,7 +1410,7 @@ Enables listening for changes to the area where the window cannot be displayed.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |------------------------------------------| ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| | type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.|
| callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. | | callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. |
...@@ -1432,7 +1433,7 @@ Disables listening for changes to the area where the window cannot be displayed. ...@@ -1432,7 +1433,7 @@ Disables listening for changes to the area where the window cannot be displayed.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |------------------------------------------| ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| | type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.|
| callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | No | Callback used to return the area. | | callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | No | Callback used to return the area. |
...@@ -1658,7 +1659,7 @@ Sets the background color for this window. This API uses an asynchronous callbac ...@@ -1658,7 +1659,7 @@ Sets the background color for this window. This API uses an asynchronous callbac
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1686,7 +1687,7 @@ Sets the background color for this window. This API uses a promise to return the ...@@ -1686,7 +1687,7 @@ Sets the background color for this window. This API uses a promise to return the
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
**Return value** **Return value**
...@@ -1772,8 +1773,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback&lt;void&gt;): void ...@@ -1772,8 +1773,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback&lt;void&gt;): void
Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1802,8 +1804,9 @@ setDimBehind(dimBehindValue: number): Promise&lt;void&gt; ...@@ -1802,8 +1804,9 @@ setDimBehind(dimBehindValue: number): Promise&lt;void&gt;
Sets the dimness of the window that is not on top. This API uses a promise to return the result. Sets the dimness of the window that is not on top. This API uses a promise to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1956,8 +1959,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback&lt;void&gt;): vo ...@@ -1956,8 +1959,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback&lt;void&gt;): vo
Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1986,8 +1990,9 @@ setOutsideTouchable(touchable: boolean): Promise&lt;void&gt; ...@@ -1986,8 +1990,9 @@ setOutsideTouchable(touchable: boolean): Promise&lt;void&gt;
Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
......
# Search # Search
The **\<Search>** component provides an input area for users to search.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
## Required Permissions ## Required Permissions
None None
...@@ -18,34 +18,34 @@ Not supported ...@@ -18,34 +18,34 @@ Not supported
Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController }) Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | ----------- | ---------------- | ---- | ---- | ---------------------------------------- |
| value | string | No| - | Text input in the search text box. | | value | string | No | - | Text input in the search text box. |
| placeholder | string | No | - | Text displayed when there is no input. | | placeholder | string | No | - | Text displayed when there is no input. |
| icon | string | No| - | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png. | | icon | string | No | - | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png.|
| controller | SearchController | No| - | Controller. | | controller | SearchController | No | - | Controller. |
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | ----------------------- | ---------------------------------------- | ---- | --------------------- |
| searchButton | string | –| Text on the search button located next to the search text box. By default, there is no search button. | | searchButton | string | – | Text on the search button located next to the search text box. By default, there is no search button.|
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Placeholder text color. |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. | | placeholderFont | [Font](ts-types.md#font) | - | Placeholder text style. |
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. | | textFont | [Font](ts-types.md#font) | - | Text font for the search text box. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or tap the search button on a soft keyboard.<br> - **value**: current text input. | | onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or touch the search button on a soft keyboard.<br> -**value**: current text input.|
| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br> - **value**: current text input. | | onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br> -**value**: current text input. |
| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.<br> - **value**: text copied. | | onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.<br> -**value**: text copied. |
| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.<br> - **value**: text cut. | | onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.<br> -**value**: text cut. |
| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br> - **value**: text pasted. | | onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br> -**value**: text pasted. |
## SearchController ## SearchController
...@@ -61,11 +61,11 @@ caretPosition(value: number): void ...@@ -61,11 +61,11 @@ caretPosition(value: number): void
Sets the position of the caret. Sets the position of the caret.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- | | ----- | ------ | ---- | ---- | ----------------- |
| value | number | Yes | - | Length from the start of the text string to the position where the caret is located. | | value | number | Yes | - | Length from the start of the character string to the position where the caret is located.|
...@@ -76,29 +76,30 @@ Sets the position of the caret. ...@@ -76,29 +76,30 @@ Sets the position of the caret.
@Entry @Entry
@Component @Component
struct SearchExample { struct SearchExample {
@State changevalue: string = '' @State changeValue: string = ''
@State submitvalue: string = '' @State submitValue: string = ''
controller: SearchController = new SearchController() controller: SearchController = new SearchController()
build() { build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text(this.submitvalue) Text(this.submitValue)
Text(this.changevalue) Text(this.changeValue)
Search({value: '', placeholder: 'Type to search', controller: this.controller}) Search({value: this.changeValue, placeholder: 'Type to search', controller: this.controller})
.searchButton('Search') .searchButton('Search')
.width(400) .width(400)
.height(35) .height(35)
.backgroundColor(Color.White) .backgroundColor(Color.White)
.placeholderColor(Color.Grey) .placeholderColor(Color.Grey)
.placeholderFont({ size: 50, weight: 10, family: 'serif', style: FontStyle.Normal }) .placeholderFont({ size: 26, weight: 10, family: 'serif', style: FontStyle.Normal })
.onSubmit((value: string) => { .onSubmit((value: string) => {
this.submitvalue = value this.submitValue = value
}) })
.onChange((value: string) => { .onChange((value: string) => {
this.changevalue = value this.changeValue = value
}) })
.margin({ top: 30 }) .margin({ top: 30, left:10, right:10 })
} }
} }
} }
``` ```
![search](figures/search.png)
...@@ -33,23 +33,23 @@ Swiper(value:{controller?: SwiperController}) ...@@ -33,23 +33,23 @@ Swiper(value:{controller?: SwiperController})
[Menu control](ts-universal-attributes-menu.md) is not supported. [Menu control](ts-universal-attributes-menu.md) is not supported.
| Name | Type | Description | | Name | Type | Default Value | Description |
| --------------------------- | ---------------------------------------- | ---------------------------------------- | | --------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| index | number | Index of the child component currently displayed in the container.<br>Default value: **0** | | index | number | 0 | Index of the child component currently displayed in the container. |
| autoPlay | boolean | Whether to enable automatic playback for child component switching. If this attribute is **true**, the navigation dots indicator does not take effect.<br>Default value: **false** | | autoPlay | boolean | false | Whether to enable automatic playback for child component switching. If this attribute is **true**, the navigation dots indicator does not take effect. |
| interval | number | Interval for automatic playback, in ms.<br>Default value: **3000** | | interval | number | 3000 | Interval for automatic playback, in ms. |
| indicator | boolean | Whether to enable the navigation dots indicator.<br>Default value: **true** | | indicator | boolean | true | Whether to enable the navigation dots indicator. |
| loop | boolean | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.<br>Default value: **true**| | loop | boolean | true | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5. |
| duration | number | Duration of the animation for switching child components, in ms.<br>Default value: **400** | | duration | number | 400 | Duration of the animation for switching child components, in ms. |
| vertical | boolean | Whether vertical swiping is used.<br>Default value: **false** | | vertical | boolean | false | Whether vertical swiping is used. |
| itemSpace | Length | Space between child components.<br>Default value: **0** | | itemSpace | number \| string | 0 | Space between child components. |
| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**| | displayMode | SwiperDisplayMode | SwiperDisplayMode.Stretch | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set. |
| cachedCount<sup>8+</sup> | number | Number of child components to be cached.<br>Default value: **1** | | cachedCount<sup>8+</sup> | number | 1 | Number of child components to be cached. |
| disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** | | disableSwipe<sup>8+</sup> | boolean | false | Whether to disable the swipe feature. |
| curve<sup>8+</sup> | [Curve](ts-animatorproperty.md#Curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve enums](ts-animatorproperty.md#curve-enums). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module.<br>Default value: **Curve.Ease**| | displayCount<sup>8+</sup> | number \| string | 1 | Number of elements to display. |
| indicatorStyle<sup>8+</sup> | {<br>left?:&nbsp;Length,<br>top?:&nbsp;Length,<br>right?:&nbsp;Length,<br>bottom?:&nbsp;Length,<br>size?:&nbsp;Length,<br>color?:&nbsp;Color,<br>selectedColor?:&nbsp;Color<br>} | Style of the navigation dots indicator.<br>- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>- **size**: diameter of the navigation dots indicator.<br>- **color**: color of the navigation dots indicator.<br>- **selectedColor**: color of the selected navigation dot.| | effectMode<sup>8+</sup> | EdgeEffect | EdgeEffect.Spring | Swipe effect. For details, see **EdgeEffect**. |
| displayCount<sup>8+</sup> | number\|string | Number of elements to display.<br>Default value: **1** | | curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Curve.Ease | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module. |
| effectMode<sup>8+</sup> | EdgeEffect | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**| | indicatorStyle<sup>8+</sup> | {<br/>left?: [Length](ts-types.md#length),<br/>top?: [Length](ts-types.md#length),<br/>right?: [Length](ts-types.md#length),<br/>bottom?: [Length](ts-types.md#length),<br/>size?: [Length](ts-types.md#length),<br/>mask?: boolean,<br/>color?: [ResourceColor](ts-types.md#resourcecolor8),<br/>selectedColor?: [ResourceColor](ts-types.md#resourcecolor8)<br/>} | - | Style of the navigation dots indicator.<br>- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>- **size**: diameter of the navigation dots indicator.<br>- **color**: color of the navigation dots indicator.<br>- **selectedColor**: color of the selected navigation dot.|
## SwiperDisplayMode ## SwiperDisplayMode
...@@ -98,7 +98,7 @@ Stops this animation. ...@@ -98,7 +98,7 @@ Stops this animation.
### onChange ### onChange
onChange(&nbsp;index:&nbsp;number)&nbsp;=&gt;&nbsp;void onChange( index: number) =&gt; void
Triggered when the index of the currently displayed component changes. Triggered when the index of the currently displayed component changes.
......
# Image Effect Configuration # Image Effects
Image effects include background blur, content blur, grayscale, and much more.
> **NOTE** > **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -15,28 +17,30 @@ None ...@@ -15,28 +17,30 @@ None
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| blur | number | - | Adds the content blurring for the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | | blur | number | - | Adds the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. |
| backdropBlur | number | - | Adds the background blur effect for the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | backdropBlur | number | - | Adds the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. |
| shadow | {<br/>radius: number,<br/>color?: Color,<br/>offsetX?: number,<br/>offsetY?: number<br/>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), X-axis offset (optional and 0 by default), and Y-axis offset (optional; 0 by default). The offset unit is px. | | shadow | {<br/>radius: number,<br/>color?: Color \| string \| [Resource](../../ui/ts-types.md#resource-type),<br/>offsetX?: number,<br/>offsetY?: number<br/>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), X-axis offset (optional and 0 by default), and Y-axis offset (optional; 0 by default). The offset unit is px. |
| grayscale | number | 0.0 | The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage. The unit is percentage. | | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage. The unit is percentage. |
| brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness. | | brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness. |
| saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage. | | saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage. |
| contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage. | | contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage. |
| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. | | invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. |
| colorBlend <sup>8+</sup> | Color | - | Adds the color blend effect to the current component. The input parameter is the blended color. | | colorBlend<sup>8+</sup> | Color | - | Adds the color blend effect to the current component. The input parameter is the blended color. |
| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. | | sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. |
| hueRotate | 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**.| | hueRotate | number \| string | '0deg' | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. If the input value is **0deg**, the image does not change (because the default rotation angle is **0deg**). The input parameter does not have the maximum value. If the value exceeds **360deg**, the image is rotated for one more circle. In other words, the value **370deg** has the same effect as **10deg**.|
## Example ## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ImageEffectsExample { struct ImageEffectsExample {
build() { build() {
Column({space: 10}) { Column({space: 10}) {
// Blur the font. // Blur the font.
Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%')
Text('text').blur(3).width('90%').height(40) Text('text').blur(3).width('90%').height(40)
......
# Standard Libraries Supported by Native APIs # Standard Libraries Supported by Native APIs
- [Standard Libraries](third_party_libc/musl.md)
- [Node_API](third_party_napi/napi.md) - [Node_API](third_party_napi/napi.md)
- [libuv](third_party_libuv/libuv.md) - [libuv](third_party_libuv/libuv.md)
- [Standard Libraries](third_party_libc/musl.md)
- Appendix
- [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md) - [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md)
- [EGL Symbols Exported from Native APIs](third_party_opengl/egl-symbol.md)
- [OpenGL ES 3.0 Symbols Exported from Native APIs](third_party_opengl/openglesv3-symbol.md)
\ No newline at end of file
# UI Development # UI Development
- [ArkUI Overview](arkui-overview.md) - [ArkUI Overview](arkui-overview.md)
- TypeScript-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["js" Tag](ts-framework-js-tag.md)
- Resource Management
- [Resource File Categories](ui-ts-basic-resource-file-categories.md)
- [Accessing Resources](ts-resource-access.md)
- [Pixel Units](ts-pixel-units.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
- General UI Description Specifications
- [Basic Concepts](ts-general-ui-concepts.md)
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
- Componentization
- [@Component](ts-component-based-component.md)
- [@Entry](ts-component-based-entry.md)
- [@Preview](ts-component-based-preview.md)
- [@Builder](ts-component-based-builder.md)
- [@Extend](ts-component-based-extend.md)
- [@CustomDialog](ts-component-based-customdialog.md)
- [@Styles](ts-component-based-styles.md)
- About UI State Management
- [Basic Concepts](ts-ui-state-mgmt-concepts.md)
- Managing Component States
- [@State](ts-component-states-state.md)
- [@Prop](ts-component-states-prop.md)
- [@Link](ts-component-states-link.md)
- Managing Application States
- [AppStorage](ts-application-states-appstorage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md)
- Managing Other States
- [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md)
- [@Consume and @Provide](ts-other-states-consume-provide.md)
- [@Watch](ts-other-states-watch.md)
- About Rendering Control Syntax
- [if/else](ts-rending-control-syntax-if-else.md)
- [ForEach](ts-rending-control-syntax-foreach.md)
- [LazyForEach](ts-rending-control-syntax-lazyforeach.md)
- About @Component
- [build Function](ts-function-build.md)
- [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md)
- [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md)
- [Component Creation and Re-initialization](ts-component-creation-re-initialization.md)
- [About Syntactic Sugar](ts-syntactic-sugar.md)
- Common Component Development Guidelines
- [Button](ui-ts-basic-components-button.md)
- [Web](ui-ts-components-web.md)
- Common Layout Development Guidelines
- [Flex Layout](ui-ts-layout-flex.md)
- [Grid Layout](ui-ts-layout-grid-container.md)
- [Media Query](ui-ts-layout-mediaquery.md)
- Experiencing the Declarative UI
- [Creating a Declarative UI Project](ui-ts-creating-project.md)
- [Getting to Know Components](ui-ts-components.md)
- [Creating a Simple Page](ui-ts-creating-simple-page.md)
- Defining Page Layout and Connection
- [Building a Food Data Model](ui-ts-building-data-model.md)
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
- JavaScript-based Web-like Development Paradigm - JavaScript-based Web-like Development Paradigm
- [Overview](ui-js-overview.md) - [Overview](ui-js-overview.md)
- Framework - Framework
...@@ -73,73 +142,3 @@ ...@@ -73,73 +142,3 @@
- [Animation Effect](ui-js-animate-dynamic-effects.md) - [Animation Effect](ui-js-animate-dynamic-effects.md)
- [Animation Frame](ui-js-animate-frame.md) - [Animation Frame](ui-js-animate-frame.md)
- [Custom Components](ui-js-custom-components.md) - [Custom Components](ui-js-custom-components.md)
- TypeScript-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["js" Tag](ts-framework-js-tag.md)
- Resource Management
- [Resource File Categories](ui-ts-basic-resource-file-categories.md)
- [Accessing Resources](ts-resource-access.md)
- [Pixel Units](ts-pixel-units.md)
- [Types](ts-types.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
- General UI Description Specifications
- [Basic Concepts](ts-general-ui-concepts.md)
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
- Componentization
- [@Component](ts-component-based-component.md)
- [@Entry](ts-component-based-entry.md)
- [@Preview](ts-component-based-preview.md)
- [@Builder](ts-component-based-builder.md)
- [@Extend](ts-component-based-extend.md)
- [@CustomDialog](ts-component-based-customdialog.md)
- [@Styles](ts-component-based-styles.md)
- About UI State Management
- [Basic Concepts](ts-ui-state-mgmt-concepts.md)
- Managing Component States
- [@State](ts-component-states-state.md)
- [@Prop](ts-component-states-prop.md)
- [@Link](ts-component-states-link.md)
- Managing Application States
- [AppStorage](ts-application-states-appstorage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md)
- Managing Other States
- [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md)
- [@Consume and @Provide](ts-other-states-consume-provide.md)
- [@Watch](ts-other-states-watch.md)
- About Rendering Control Syntax
- [if/else](ts-rending-control-syntax-if-else.md)
- [ForEach](ts-rending-control-syntax-foreach.md)
- [LazyForEach](ts-rending-control-syntax-lazyforeach.md)
- About @Component
- [build Function](ts-function-build.md)
- [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md)
- [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md)
- [Component Creation and Re-initialization](ts-component-creation-re-initialization.md)
- [About Syntactic Sugar](ts-syntactic-sugar.md)
- Common Component Development Guidelines
- [Button](ui-ts-basic-components-button.md)
- [Web](ui-ts-components-web.md)
- Common Layout Development Guidelines
- [Flex Layout](ui-ts-layout-flex.md)
- [Grid Layout](ui-ts-layout-grid-container.md)
- [Media Query](ui-ts-layout-mediaquery.md)
- Experiencing the Declarative UI
- [Creating a Declarative UI Project](ui-ts-creating-project.md)
- [Getting to Know Components](ui-ts-components.md)
- [Creating a Simple Page](ui-ts-creating-simple-page.md)
- Defining Page Layout and Connection
- [Building a Food Data Model](ui-ts-building-data-model.md)
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
...@@ -85,11 +85,11 @@ The following is an example: ...@@ -85,11 +85,11 @@ The following is an example:
```css ```css
/* Page style xxx.css */ /* Page style xxx.css */
/\* Set the style for all <div> components. \*/ /* Set the style for all <div> components. */
div { div {
flex-direction: column; flex-direction: column;
} }
/* Set the style for the component whose class is title. */ /* Set the style for the component whose class is title.*/
.title { .title {
font-size: 30px; font-size: 30px;
} }
...@@ -101,13 +101,13 @@ div { ...@@ -101,13 +101,13 @@ div {
.title, .content { .title, .content {
padding: 5px; padding: 5px;
} }
/\* Set the style for all texts of components whose class is container.\*/ /* Set the style for all texts of components whose class is container.*/
.container text { .container text {
color: \#007dff; color: \#007dff;
} }
/\* Set the style for direct descendant texts of components whose class is container.\*/ /* Set the style for direct descendant texts of components whose class is container.*/
.container &gt; text { .container &gt; text {
color: \#fa2a2d; color: #fa2a2d;
} }
``` ```
...@@ -128,7 +128,7 @@ When multiple selectors point to the same element, their priorities are as follo ...@@ -128,7 +128,7 @@ When multiple selectors point to the same element, their priorities are as follo
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :disabled can be used to select the element whose disabled attribute is true. A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :disabled can be used to select the element whose disabled attribute is true.
In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, **:focus:checked** selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority. In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, :focus:checked selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority.
| Pseudo-class | Available Components | Description | | Pseudo-class | Available Components | Description |
......
...@@ -21,7 +21,7 @@ By default, the attributes in the AppStorage are changeable. If needed, AppStora ...@@ -21,7 +21,7 @@ By default, the attributes in the AppStorage are changeable. If needed, AppStora
| Set | key: string,<br/>newValue: T | void | Replaces the value of a saved key. | | Set | key: string,<br/>newValue: T | void | Replaces the value of a saved key. |
| Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. | | Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. |
| SetAndProp | propName: string,<br/>defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. | | SetAndProp | propName: string,<br/>defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. |
| Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:<br/>> The attribute value used in the prop method must be of a simple type. | | Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.<br/>**NOTE**<br/>The attribute value used in the prop method must be of a simple type. |
| SetOrCreate | key: string,<br/>newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.<br/>If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. | | SetOrCreate | key: string,<br/>newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.<br/>If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. |
| Get | key: string | T or undefined | Obtains the value of the specified key. | | Get | key: string | T or undefined | Obtains the value of the specified key. |
| Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. | | Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. |
...@@ -51,9 +51,8 @@ One-way data binding can be established between components and the AppStorage th ...@@ -51,9 +51,8 @@ One-way data binding can be established between components and the AppStorage th
## Example ## Example
``` ```ts
let varA = AppStorage.Link('varA') // xxx.ets
let envLang = AppStorage.Prop('languageCode')
@Entry @Entry
@Component @Component
......
...@@ -5,10 +5,13 @@ ...@@ -5,10 +5,13 @@
To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource. To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
When referencing resources in the **rawfile** sub-directory, use the `"$rawfile('filename')"` format. Currently, **$rawfile** allows only the **\<Image>** component to reference image resources. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/). When referencing resources in the **rawfile** sub-directory, use the ```"$rawfile('filename')"``` format. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/).
> **NOTE** > **NOTE**
>
> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined. > Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
>
> `$r` returns a **Resource** object. To obtain the corresponding string, use [getString](../reference/apis/js-apis-resource-manager.md#getstring).
In the **.ets** file, you can use the resources defined in the **resources** directory. In the **.ets** file, you can use the resources defined in the **resources** directory.
...@@ -47,7 +50,7 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile direc ...@@ -47,7 +50,7 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile direc
System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style. System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
To reference a system resource, use the "$r('sys.type.resource_id')" format. Wherein: sys indicates a system resource; type indicates the resource type, which can be color, float, string, or media; resource_id indicates the resource ID, which is determined when the system resource is provided. For details about available system resource IDs. To reference a system resource, use the ```"$r('sys.type.resource_id')"``` format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID.
```ts ```ts
Text('Hello') Text('Hello')
......
# About Syntactic Sugar # About Syntactic Sugar
## Decorators ## Decorators
A decorator @Decorator can decorate a class, structure, or class attribute. Multiple decorators can be applied to the same target element and defined on a single line or multiple lines. It is recommended that the decorators be defined on multiple lines.
In the example below, the elements decorated by @Component take on the form of a component, and the variables decorated by @State can be used to represent states. A decorator **@Decorator** can decorate a class, structure, or class attribute. Multiple decorators can be applied to the same target element and defined on a single line or multiple lines. It is recommended that the decorators be defined on multiple lines.
``` In the example below, the elements decorated by **@Component** take on the form of a component, and the variables decorated by **@State** can be used to represent states.
```ts
@Component @Component
struct MyComponent { struct MyComponent {
@State count: number = 0 @State count: number = 0
} }
``` ```
Multiple decorators can be defined on a single line, as shown below: Multiple decorators can be defined on a single line, as shown below:
``` ```ts
@Entry @Component struct MyComponent { @Entry @Component struct MyComponent {
} }
``` ```
However, you are advised to define the decorators on multiple lines, as shown below: However, you are advised to define the decorators on multiple lines, as shown below:
``` ```ts
@Entry @Entry
@Component @Component
struct MyComponent { struct MyComponent {
...@@ -36,30 +39,29 @@ struct MyComponent { ...@@ -36,30 +39,29 @@ struct MyComponent {
### Supported Decorators ### Supported Decorators
| Decorator | Decorates... | Description | | Decorator | Decorates... | Description |
| -------- | -------- | -------- | | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| @Component | struct | The decorated structure has the component-based capability. The build method must be implemented to update the UI. | | @Component | struct | The decorated structure has the component-based capability. The **build** method must be implemented to update the UI.|
| @Entry | struct | The decorated component is used as the entry of a page. The component is rendered and displayed when the page is loaded. | | @Entry | struct | The decorated component is used as the entry of a page. The component is rendered and displayed when the page is loaded. |
| @Preview | struct | Custom components decorated by @Preview can be previewed in the Previewer of DevEco Studio. When the page is loaded, the custom components decorated by @Preview are created and displayed. | | @Preview | struct | Custom components decorated by **@Preview** can be previewed in DevEco Studio. When the target page is loaded, the custom components decorated by **@Preview** are created and displayed.|
| @Builder | Methods | In the decorated method, you can use the declarative UI description to quickly generate multiple layouts in a custom component. | | @Builder | Methods | In the decorated method, you can use the declarative UI description to quickly generate multiple layouts in a custom component.|
| @Extend | Methods | This decorator adds new attribute functions to a preset component, allowing you to quickly define and reuse the custom style of the component. | | @Extend | Methods | This decorator adds attribute functions to a preset component, allowing you to quickly define and reuse the custom style of the component.|
| @CustomDialog | struct | This decorator is used to decorate custom pop-up dialog boxes. | | @CustomDialog | struct | This decorator is used to decorate custom pop-up dialog boxes. |
| @State | Primitive data types, classes, and arrays | If the decorated state data is modified, the build method of the component will be called to update the UI. | | @State | Primitive data types, classes, and arrays | If the decorated state data is modified, the **build** method of the component will be called to update the UI. |
| @Prop | Primitive data types | This decorator is used to establish one-way data binding between the parent and child components. When the data associated with the parent component is modified, the UI of the current component is updated. | | @Prop | Primitive data types | This decorator is used to establish one-way data binding between the parent and child components. When the data associated with the parent component is modified, the UI of the current component is updated.|
| @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other. | | @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other.|
| @Observed | Classes | This decorator is used to indicate that the data changes in the class will be managed by the UI page. | | @Observed | Classes | This decorator is used to indicate that the data changes in the class will be managed by the UI page. |
| @ObjectLink | Objects of @Observed decorated classes | When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering. | | @ObjectLink | Objects of **@Observed** decorated classes | When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering.|
| @Consume | Primitive data types, classes, and arrays | When the @Consume decorated variable detects the update of the @Provide decorated variable, the re-rendering of the current custom component is triggered. | | @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.|
| @Provide | Primitive data types, classes, and arrays | As the data provider, @Provide can update the data of child nodes and trigger page rendering. | | @Provide | Primitive data types, classes, and arrays | As the data provider, **@Provide** can update the data of child nodes and trigger page rendering.|
| @Watch | Variables decorated by @State, @Prop, @Link, @ObjectLink, @Provide, @Consume, @StorageProp, or @StorageLink | This decorator is used to listen for the changes of the state variables. The application can register a callback method through @Watch. | | @Watch | Variables decorated by **@State**, **@Prop**, **@Link**, **@ObjectLink**, **@Provide**, **@Consume**, **@StorageProp**, or **@StorageLink** | This decorator is used to listen for the changes of the state variables. The application can register a callback method through **@Watch**. |
## Chain Call ## Chain Call
You can configure the UI structure and its attributes and events and separate them with a dot(.) to implement chain call. You can configure the UI structure and its attributes and events and separate them with a dot(.) to implement chain call.
```ts
```
Column() { Column() {
Image('1.jpg') Image('1.jpg')
.alt('error.jpg') .alt('error.jpg')
...@@ -71,10 +73,9 @@ Column() { ...@@ -71,10 +73,9 @@ Column() {
## struct ## struct
Components can be implemented based on structs. Components cannot inherit from each other. The structs implemented components can be created and destroyed more quickly than class implemented components. Components can be implemented based on **struct**s. Components cannot inherit from each other. The **struct**s implemented components can be created and destroyed more quickly than **class** implemented components.
```ts
```
@Component @Component
struct MyComponent { struct MyComponent {
@State data: string = '' @State data: string = ''
...@@ -87,10 +88,9 @@ struct MyComponent { ...@@ -87,10 +88,9 @@ struct MyComponent {
## Instantiating a struct Without the new Keyword ## Instantiating a struct Without the new Keyword
You can omit the new keyword when instantiating a struct. You can omit the **new** keyword when instantiating a **struct**.
```ts
```
// Definition // Definition
@Component @Component
struct MyComponent { struct MyComponent {
...@@ -98,7 +98,7 @@ struct MyComponent { ...@@ -98,7 +98,7 @@ struct MyComponent {
} }
} }
// Use // Usage
Column() { Column() {
MyComponent() MyComponent()
} }
...@@ -114,23 +114,22 @@ new Column() { ...@@ -114,23 +114,22 @@ new Column() {
TypeScript has the following restrictions on generators: TypeScript has the following restrictions on generators:
- Expressions can be used only in character strings (${expression}), if conditions, ForEach parameters, and component parameters. - Expressions can be used only in character strings (${expression}), **if** conditions, **ForEach** parameters, and component parameters.
- No expressions should cause any application state variables (@State, @Link, and @Prop) to change. Otherwise, undefined and potentially unstable framework behavior may occur. - No expressions should cause any application state variables (**@State**, **@Link**, and **@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur.
- The generator function cannot contain local variables. - The generator function cannot contain local variables.
None of the above restrictions apply to anonymous function implementations of event-handling functions (such as onClick) None of the above restrictions apply to anonymous function implementations of event-handling functions (such as **onClick**)
Incorrect: Incorrect:
```ts
```
build() { build() {
let a: number = 1 // invalid: variable declaration not allowed let a: number = 1 // invalid: variable declaration not allowed
Column() { Column() {
Text('Hello ${this.myName.toUpperCase()}') // ok. Text(`Hello ${this.myName.toUpperCase()}`) // ok.
ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place
} }
buildSpecial() // invalid: no function calls buildSpecial() // invalid: no function calls
Text(this.calcTextValue()) // this function call is ok. Text(this.calcTextValue()) // this function call is ok.
...@@ -139,11 +138,13 @@ build() { ...@@ -139,11 +138,13 @@ build() {
## $$ ## $$
$$ supports two-way binding for simple variables and @State, @Link, and @Prop decorated variables. **$$** supports two-way binding for simple variables and **@State**, **@Link**, and **@Prop** decorated variables.
Currently, $$ supports only the rendering between the show parameter of the bindPopup attribute and the @State decorated variable, and the checked attribute of the \<Radio> component. Currently, **$$** supports only the rendering between the **show** parameter of the **[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)** attribute and the **@State** decorated variable, and the **checked** attribute of the **\<Radio>** component.
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct bindPopup { struct bindPopup {
...@@ -166,3 +167,29 @@ struct bindPopup { ...@@ -166,3 +167,29 @@ struct bindPopup {
} }
``` ```
## Restrictions on Declaring Multiple Data Types of State Variables
If a **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variable supports multiple data types, they must be all simple data types or references at one time.
Example:
```ts
@Entry
@Component
struct Index {
// Incorrect: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${ this.message }`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
# Types
## Length Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Length | string \| number | Length unit. If the input is a number, use vp. If the input is a string, explicitly specify the unit, for example, '10px', or specify the length in percentage, for example, '100%'.|
## Angle Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Angle | string \| number | Angle unit. If the input is a number, use deg. If the input is a string, use either of the following angle units:<br>- deg: for example, '100deg'<br>- rad: for example, '3.14rad' |
## Point Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Point | [Length, Length] | Coordinates of a point. The first value is the x-axis coordinate, and the second value is the y-axis coordinate.|
## Color Type
The Color type used by component attribute methods is described as follows:
| Name| Type| Description|
| -------- | -------- | -------- |
| Color | string \| number \| Color | Color information. If the input is a string, use rgb or rgba to specify the color. If the input is a number, use Hex format to specify the color. If the input is a Color enum, use a color value to specify the color.<br>- 'rgb(255, 255, 255)'<br>- 'rgba(255, 255, 255, 1.0)'<br>- Hex format: 0xrrggbb, 0xaarrggbb, '\#FFFFFF'<br>- Enum: Color.Black, Color.White |
The supported Color enums are described as follows:
| Color| Value| Illustration|
| -------- | -------- | -------- |
| Black | 0x000000 | ![en-us_image_0000001219864153](figures/en-us_image_0000001219864153.png) |
| Blue | 0x0000ff | ![en-us_image_0000001174104404](figures/en-us_image_0000001174104404.png) |
| Brown | 0xa52a2a | ![en-us_image_0000001219744201](figures/en-us_image_0000001219744201.png) |
| Gray | 0x808080 | ![en-us_image_0000001174264376](figures/en-us_image_0000001174264376.png) |
| Green | 0x008000 | ![en-us_image_0000001174422914](figures/en-us_image_0000001174422914.png) |
| Orange | 0xffa500 | ![en-us_image_0000001219662661](figures/en-us_image_0000001219662661.png) |
| Pink | 0xffc0cb | ![en-us_image_0000001219662663](figures/en-us_image_0000001219662663.png) |
| Red | 0xff0000 | ![en-us_image_0000001219662665](figures/en-us_image_0000001219662665.png) |
| White | 0xffffff | ![en-us_image_0000001174582866](figures/en-us_image_0000001174582866.png) |
| Yellow | 0xffff00 | ![en-us_image_0000001174582864](figures/en-us_image_0000001174582864.png) |
## ColorStop Type
ColorStop is used to describe the progressive color stop.
| Name| Type| Description|
| -------- | -------- | -------- |
| ColorStop | [Color, number] | Type of the progressive color stop. The first parameter specifies the color value, and the second parameter specifies the ratio of 0 to 1.|
## Resource Type
The Resource type is used to reference resources for setting the value of a component attribute.
You can use ` $r ` or ` $rawfile ` to create a Resource object. For details, see [Resource Access](ts-application-resource-access.md).
- ` $r('belonging.type.name') `
` belonging ` : system or application resource. The value can be 'sys' or 'app'.
` type ` : resource type, which can be 'color', 'float', 'string', or 'media'.
` name ` : resource name, which is determined during resource definition.
- ` $rawfile('filename') `
` filename ` : name of the file in resources/rawfile of the project.
| Name| Type| Description|
| -------- | -------- | -------- |
| Resource | {<br>readonly id: [number];<br>readonly type: [number];<br>readonly params?: any[];<br>} | **id**: resource ID.<br>**type**: resource type (enumerated value).<br>**params**: optional parameters.<br>After a **Resource** object is created using `$r` or `$rawfile`, modifying attribute values of the object is prohibited. |
## ResourceStr Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceStr | string \| Resource| Resource string.|
## ResourceColor Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceColor | Color \| number \| string \| Resource | Resource color.|
## Font Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| Font | {<br>size?: Length;<br>weight?: FontWeight \| number \| string;<br>family?: string \| Resource;<br>style?: FontStyle;<br>} | Text style.<br>**size**: font size. For the number type, use the unit fp.<br>weight: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is 400. A larger value indicates a larger font weight.<br>**family**: font family. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, sans-serif'**.<br>**style**: font style. |
## CustomBuilder Type<sup>8+</sup>
You can use CustomBuilder to define custom UI descriptions in component attribute methods.
| Name| Type| Description|
| -------- | -------- | -------- |
| CustomBuilder | () => any | Builder of component attribute methods for defining custom UI descriptions. This type of method must be decorated by @Builder. For details, see [@Builder](ts-component-based-builder.md).|
## Example
```
@Entry
@Component
struct dataTypeExample {
build() {
Column({ space: 5 }) {
Text('Length').fontColor(0xCCCCCC).fontSize(9).width('90%')
Text('90%').width('90%').height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('320').width(320).height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('1000px').width('1000px').height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('Angle').fontColor(0xCCCCCC).fontSize(9).width('90%')
Text('45deg')
.width(40).height(40)
.rotate({ x: 0, y: 0, z: 1, angle: 45, centerX: '50%', centerY: '50%' })
.fontColor(Color.White)
.backgroundColor(0xF9CF93).textAlign(TextAlign.Center)
Text('45rad')
.width(40).height(40)
.rotate({ x: 0, y: 0, z: 1, angle: '45rad', centerX: '50%', centerY: '50%' })
.fontColor(Color.White)
.backgroundColor(0xF9CF93).textAlign(TextAlign.Center).margin({ top: 30 })
Text('Point').fontColor(0xCCCCCC).fontSize(9).width('90%')
Line().width(300).height(40).startPoint([0, 20]).endPoint([300, 20])
Text('Color').fontColor('#CCCCCC').fontSize(9).width('90%')
Text('0xF9CF93')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor(0xF9CF93)
Text('#F9CF93')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('#F9CF93')
Text('rgb(249, 207, 147)')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('rgb(249, 207, 147)')
Text('rgba(249, 207, 147, 1.0)')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('rgba(249, 207, 147, 1.0)')
Text('Color.Yellow')
.textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor(Color.Yellow)
}
.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001219982719](figures/en-us_image_0000001219982719.png)
...@@ -9,14 +9,15 @@ The **&lt;switch&gt;** component is used to switch between the on and off states ...@@ -9,14 +9,15 @@ The **&lt;switch&gt;** component is used to switch between the on and off states
Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
``` ```html
<!-- xxx.hml -->
<div class="container"> <div class="container">
<switch></switch> <switch></switch>
</div> </div>
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
flex-direction: column; flex-direction: column;
...@@ -31,9 +32,9 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -31,9 +32,9 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
## Adding Attributes and Methods ## Adding Attributes and Methods
Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off). Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off).
``` ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch> <switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch>
...@@ -41,7 +42,7 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -41,7 +42,7 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%; width: 100%;
...@@ -51,18 +52,16 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -51,18 +52,16 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
align-items: center; align-items: center;
background-color: #F1F3F5; background-color: #F1F3F5;
} }
switch{ switch {
// Color of the selected text
texton-color: #002aff; texton-color: #002aff;
// Color of the unselected text textoff-color: silver;
textoff-color: silver;
text-padding: 20px; text-padding: 20px;
font-size: 50px; font-size: 50px;
} }
``` ```
``` ```js
// xxx.js // xxx.js
import prompt from '@system.prompt'; import prompt from '@system.prompt';
export default { export default {
...@@ -84,7 +83,8 @@ export default { ...@@ -84,7 +83,8 @@ export default {
![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif) ![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**
>
> The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**. > The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**.
...@@ -94,7 +94,7 @@ Turn on the switch and the default delivery address is used. When the switch is ...@@ -94,7 +94,7 @@ Turn on the switch and the default delivery address is used. When the switch is
Implementation method: Create a **&lt;switch&gt;** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color. Implementation method: Create a **&lt;switch&gt;** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color.
``` ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<div class="change"> <div class="change">
...@@ -113,7 +113,7 @@ Turn on the switch and the default delivery address is used. When the switch is ...@@ -113,7 +113,7 @@ Turn on the switch and the default delivery address is used. When the switch is
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%; width: 100%;
...@@ -168,7 +168,7 @@ switch{ ...@@ -168,7 +168,7 @@ switch{
``` ```
``` ```js
// xxx.js // xxx.js
import prompt from '@system.prompt'; import prompt from '@system.prompt';
export default { export default {
......
...@@ -11,7 +11,6 @@ ...@@ -11,7 +11,6 @@
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- Development - Development
- Ability Development - Ability Development
...@@ -43,12 +42,11 @@ ...@@ -43,12 +42,11 @@
- [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md) - [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md)
- ["js" Tag](ui/ts-framework-js-tag.md) - ["js" Tag](ui/ts-framework-js-tag.md)
- Resource Access - Resource Access
- [Accessing Application Resources](ui/ts-application-resource-access.md) - [Resource File Categories](ui/ui-ts-basic-resource-file-categories.md)
- [Accessing System Resources](ui/ts-system-resource-access.md) - [Accessing Application Resources](ui/ts-resource-access.md)
- [Media Resource Types](ui/ts-media-resource-type.md)
- [Pixel Units](ui/ts-pixel-units.md) - [Pixel Units](ui/ts-pixel-units.md)
- [Types](ui/ts-types.md)
- Declarative Syntax - Declarative Syntax
- [Overview](ui/ts-syntax-intro.md) - [Overview](ui/ts-syntax-intro.md)
- General UI Description Specifications - General UI Description Specifications
- [Basic Concepts](ui/ts-general-ui-concepts.md) - [Basic Concepts](ui/ts-general-ui-concepts.md)
...@@ -180,22 +178,15 @@ ...@@ -180,22 +178,15 @@
- [Custom Components](ui/ui-js-custom-components.md) - [Custom Components](ui/ui-js-custom-components.md)
- Common Event and Notification - Common Event and Notification
- [Common Event and Notification Overview](notification/notification-brief.md) - [Common Event and Notification Overview](notification/notification-brief.md)
- Common Event
- [Common Event Development](notification/common-event.md) - [Common Event Development](notification/common-event.md)
- Notification - [Notification Development](notification/notification-guidelines.md)
- [Notification Development](notification/notification.md) - Agent-Powered Scheduled Reminder
- Debugging Tools - [Agent-Powered Scheduled Reminder Overview](notification/background-agent-scheduled-reminder-overview.md)
- [Agent-Powered Scheduled Reminder Development](notification/background-agent-scheduled-reminder-guide.md)
- [Debugging Assistant Usage](notification/assistant-guidelines.md) - [Debugging Assistant Usage](notification/assistant-guidelines.md)
- Window Manager - Window Manager
- Window
- [Window Overview](windowmanager/window-overview.md) - [Window Overview](windowmanager/window-overview.md)
- [Window Development](windowmanager/window-guidelines.md) - [Window Development](windowmanager/window-guidelines.md)
- Display
- [Display Overview](windowmanager/display-overview.md)
- [Display Development](windowmanager/display-guidelines.md)
- Screenshot
- [Screenshot Overview](windowmanager/screenshot-overview.md)
- [Screenshot Development](windowmanager/screenshot-guidelines.md)
- WebGL - WebGL
- [WebGL Overview](webgl/webgl-overview.md) - [WebGL Overview](webgl/webgl-overview.md)
- [WebGL Development](webgl/webgl-guidelines.md) - [WebGL Development](webgl/webgl-guidelines.md)
...@@ -212,6 +203,10 @@ ...@@ -212,6 +203,10 @@
- Image - Image
- [Image Development](media/image.md) - [Image Development](media/image.md)
- Security - Security
- Access Control
- [Access Control Overview](security/accesstoken-overview.md)
- [Access Control Development](security/accesstoken-guidelines.md)
- [Permission List](security/permission-list.md)
- User Authentication - User Authentication
- [User Authentication Overview](security/userauth-overview.md) - [User Authentication Overview](security/userauth-overview.md)
- [User Authentication Development](security/userauth-guidelines.md) - [User Authentication Development](security/userauth-guidelines.md)
...@@ -220,9 +215,6 @@ ...@@ -220,9 +215,6 @@
- [HUKS Development](security/huks-guidelines.md) - [HUKS Development](security/huks-guidelines.md)
- hapsigner - hapsigner
- [hapsigner Guide](security/hapsigntool-guidelines.md) - [hapsigner Guide](security/hapsigntool-guidelines.md)
- Access Control
- [Access Control Overview](security/accesstoken-overview.md)
- [Access Control Development](security/accesstoken-guidelines.md)
- Connectivity - Connectivity
- Network Management - Network Management
- [Network Management Overview](connectivity/net-mgmt-overview.md) - [Network Management Overview](connectivity/net-mgmt-overview.md)
...@@ -250,15 +242,13 @@ ...@@ -250,15 +242,13 @@
- Distributed Data Object - Distributed Data Object
- [Distributed Data Object Overview](database/database-distributedobject-overview.md) - [Distributed Data Object Overview](database/database-distributedobject-overview.md)
- [Distributed Data Object Development](database/database-distributedobject-guidelines.md) - [Distributed Data Object Development](database/database-distributedobject-guidelines.md)
- Agent-Powered Scheduled Reminders - Task Management
- [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md)
- [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md)
- Background Task Management - Background Task Management
- [Background Task Management Overview](background-task-management/background-task-overview.md) - [Background Task Management Overview](background-task-management/background-task-overview.md)
- [Background Task Management Development](background-task-management/background-task-dev-guide.md) - [Background Task Management Development](background-task-management/background-task-dev-guide.md)
- Work Scheduler - Work Scheduler
- [Work Scheduler Overview](work-scheduler/work-scheduler-overview.md) - [Work Scheduler Overview](task-management/work-scheduler-overview.md)
- [Work Scheduler Development](work-scheduler/work-scheduler-dev-guide.md) - [Work Scheduler Development](task-management/work-scheduler-dev-guide.md)
- Device - Device
- USB Service - USB Service
- [USB Service Overview](device/usb-overview.md) - [USB Service Overview](device/usb-overview.md)
...@@ -292,6 +282,9 @@ ...@@ -292,6 +282,9 @@
- [Internationalization Development (i18n)](internationalization/i18n-guidelines.md) - [Internationalization Development (i18n)](internationalization/i18n-guidelines.md)
- Native APIs - Native APIs
- [Using Native APIs in Application Projects](napi/napi-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md)
- [Drawing Development](napi/drawing-guidelines.md)
- [Raw File Development](napi/rawfile-guidelines.md)
- [NativeWindow Development](napi/native-window-guidelines.md)
- Tools - Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
...@@ -562,8 +555,8 @@ ...@@ -562,8 +555,8 @@
- [@ohos.application.formError](reference/apis/js-apis-formerror.md) - [@ohos.application.formError](reference/apis/js-apis-formerror.md)
- [@ohos.application.formHost](reference/apis/js-apis-formhost.md) - [@ohos.application.formHost](reference/apis/js-apis-formhost.md)
- [@ohos.application.formInfo](reference/apis/js-apis-formInfo.md) - [@ohos.application.formInfo](reference/apis/js-apis-formInfo.md)
- [@ohos.application.missionManager](reference/apis/js-apis-missionManager.md)
- [@ohos.application.formProvider](reference/apis/js-apis-formprovider.md) - [@ohos.application.formProvider](reference/apis/js-apis-formprovider.md)
- [@ohos.application.missionManager](reference/apis/js-apis-missionManager.md)
- [@ohos.ability.particleAbility](reference/apis/js-apis-particleAbility.md) - [@ohos.ability.particleAbility](reference/apis/js-apis-particleAbility.md)
- [@ohos.application.ServiceExtensionAbility](reference/apis/js-apis-service-extension-ability.md) - [@ohos.application.ServiceExtensionAbility](reference/apis/js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](reference/apis/js-apis-application-StartOptions.md) - [@ohos.application.StartOptions](reference/apis/js-apis-application-StartOptions.md)
...@@ -575,19 +568,23 @@ ...@@ -575,19 +568,23 @@
- [AbilityContext](reference/apis/js-apis-ability-context.md) - [AbilityContext](reference/apis/js-apis-ability-context.md)
- [abilityDelegator](reference/apis/js-apis-application-abilityDelegator.md) - [abilityDelegator](reference/apis/js-apis-application-abilityDelegator.md)
- [abilityDelegatorArgs](reference/apis/js-apis-application-abilityDelegatorArgs.md) - [abilityDelegatorArgs](reference/apis/js-apis-application-abilityDelegatorArgs.md)
- [AbilityManager](reference/apis/js-apis-abilityManager.md)
- [abilityMonitor](reference/apis/js-apis-application-abilityMonitor.md) - [abilityMonitor](reference/apis/js-apis-application-abilityMonitor.md)
- [AbilityRunningInfo](reference/apis/js-apis-abilityrunninginfo.md) - [AbilityRunningInfo](reference/apis/js-apis-abilityrunninginfo.md)
- [AbilityStageContext](reference/apis/js-apis-abilitystagecontext.md) - [AbilityStageContext](reference/apis/js-apis-abilitystagecontext.md)
- [Context](reference/apis/js-apis-application-context.md) - [Context](reference/apis/js-apis-application-context.md)
- [ExtensionAbilityContext](reference/apis/js-apis-extension-ability-context.md)
- [ExtensionAbilityInfo](reference/apis/js-apis-extensionAbilityInfo.md)
- [ExtensionContext](reference/apis/js-apis-extension-context.md) - [ExtensionContext](reference/apis/js-apis-extension-context.md)
- [ExtensionRunningInfo](reference/apis/js-apis-extensionrunninginfo.md) - [ExtensionRunningInfo](reference/apis/js-apis-extensionrunninginfo.md)
- [FormExtensionContext](reference/apis/js-apis-formextensioncontext.md) - [FormExtensionContext](reference/apis/js-apis-formextensioncontext.md)
- [MissionInfo](reference/apis/js-apis-application-missionInfo.md)
- [MissionSnapshot](reference/apis/js-apis-application-MissionSnapshot.md) - [MissionSnapshot](reference/apis/js-apis-application-MissionSnapshot.md)
- [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md)
- [ProcessRunningInfo](reference/apis/js-apis-processrunninginfo.md) - [ProcessRunningInfo](reference/apis/js-apis-processrunninginfo.md)
- [ServiceExtAbilityContext](reference/apis/js-apis-serviceExtAbilityContext.md)
- [ServiceExtensionContext](reference/apis/js-apis-service-extension-context.md) - [ServiceExtensionContext](reference/apis/js-apis-service-extension-context.md)
- [shellCmdResult](reference/apis/js-apis-application-shellCmdResult.md) - [shellCmdResult](reference/apis/js-apis-application-shellCmdResult.md)
- [AbilityStageContext](reference/apis/js-apis-abilityStageContext.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](reference/apis/js-apis-commonEvent.md) - [@ohos.commonEvent](reference/apis/js-apis-commonEvent.md)
- [@ohos.events.emitter](reference/apis/js-apis-emitter.md) - [@ohos.events.emitter](reference/apis/js-apis-emitter.md)
...@@ -598,6 +595,14 @@ ...@@ -598,6 +595,14 @@
- [@ohos.bundle](reference/apis/js-apis-Bundle.md) - [@ohos.bundle](reference/apis/js-apis-Bundle.md)
- [@ohos.bundleState ](reference/apis/js-apis-deviceUsageStatistics.md) - [@ohos.bundleState ](reference/apis/js-apis-deviceUsageStatistics.md)
- [@ohos.zlib](reference/apis/js-apis-zlib.md) - [@ohos.zlib](reference/apis/js-apis-zlib.md)
- [AbilityInfo](reference/apis/js-apis-bundle-AbilityInfo.md)
- [ApplicationInfo](reference/apis/js-apis-bundle-ApplicationInfo.md)
- [BundleInfo](reference/apis/js-apis-bundle-BundleInfo.md)
- [CustomizeData](reference/apis/js-apis-bundle-CustomizeData.md)
- [ExtensionAbilityInfo](reference/apis/js-apis-bundle-ExtensionAbilityInfo.md)
- [HapModuleInfo](reference/apis/js-apis-bundle-HapModuleInfo.md)
- [Metadata](reference/apis/js-apis-bundle-Metadata.md)
- [ModuleInfo](reference/apis/js-apis-bundle-ModuleInfo.md)
- UI Page - UI Page
- [@ohos.animator](reference/apis/js-apis-animator.md) - [@ohos.animator](reference/apis/js-apis-animator.md)
- [@ohos.mediaquery](reference/apis/js-apis-mediaquery.md) - [@ohos.mediaquery](reference/apis/js-apis-mediaquery.md)
...@@ -611,7 +616,6 @@ ...@@ -611,7 +616,6 @@
- [webgl2](reference/apis/js-apis-webgl2.md) - [webgl2](reference/apis/js-apis-webgl2.md)
- Media - Media
- [@ohos.multimedia.audio](reference/apis/js-apis-audio.md) - [@ohos.multimedia.audio](reference/apis/js-apis-audio.md)
- [@ohos.multimedia.camera](reference/apis/js-apis-camera.md)
- [@ohos.multimedia.image](reference/apis/js-apis-image.md) - [@ohos.multimedia.image](reference/apis/js-apis-image.md)
- [@ohos.multimedia.media](reference/apis/js-apis-media.md) - [@ohos.multimedia.media](reference/apis/js-apis-media.md)
- [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md)
...@@ -635,7 +639,6 @@ ...@@ -635,7 +639,6 @@
- [@ohos.data.distributedData](reference/apis/js-apis-distributed-data.md) - [@ohos.data.distributedData](reference/apis/js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](reference/apis/js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](reference/apis/js-apis-data-distributedobject.md)
- [@ohos.data.rdb](reference/apis/js-apis-data-rdb.md) - [@ohos.data.rdb](reference/apis/js-apis-data-rdb.md)
- [@ohos.settings](reference/apis/js-apis-settings.md)
- [@ohos.data.storage](reference/apis/js-apis-data-storage.md) - [@ohos.data.storage](reference/apis/js-apis-data-storage.md)
- [resultSet](reference/apis/js-apis-data-resultset.md) - [resultSet](reference/apis/js-apis-data-resultset.md)
- File Management - File Management
...@@ -643,6 +646,7 @@ ...@@ -643,6 +646,7 @@
- [@ohos.environment](reference/apis/js-apis-environment.md) - [@ohos.environment](reference/apis/js-apis-environment.md)
- [@ohos.fileio](reference/apis/js-apis-fileio.md) - [@ohos.fileio](reference/apis/js-apis-fileio.md)
- [@ohos.fileManager](reference/apis/js-apis-filemanager.md) - [@ohos.fileManager](reference/apis/js-apis-filemanager.md)
- [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md)
- [@ohos.statfs](reference/apis/js-apis-statfs.md) - [@ohos.statfs](reference/apis/js-apis-statfs.md)
- [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md) - [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md)
- [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md) - [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md)
...@@ -657,12 +661,15 @@ ...@@ -657,12 +661,15 @@
- Network Management - Network Management
- [@ohos.net.connection](reference/apis/js-apis-net-connection.md) - [@ohos.net.connection](reference/apis/js-apis-net-connection.md)
- [@ohos.net.http](reference/apis/js-apis-http.md) - [@ohos.net.http](reference/apis/js-apis-http.md)
- [@ohos.request](reference/apis/js-apis-request.md)
- [@ohos.net.socket](reference/apis/js-apis-socket.md) - [@ohos.net.socket](reference/apis/js-apis-socket.md)
- [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md) - [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md)
- [@ohos.request](reference/apis/js-apis-request.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md) - [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md)
- [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md) - [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation](reference/apis/js-apis-cardEmulation.md)
- [@ohos.nfc.controller](reference/apis/js-apis-nfcController.md)
- [@ohos.nfc.tag](reference/apis/js-apis-nfcTag.md)
- [@ohos.rpc](reference/apis/js-apis-rpc.md) - [@ohos.rpc](reference/apis/js-apis-rpc.md)
- [@ohos.wifi](reference/apis/js-apis-wifi.md) - [@ohos.wifi](reference/apis/js-apis-wifi.md)
- [@ohos.wifiext](reference/apis/js-apis-wifiext.md) - [@ohos.wifiext](reference/apis/js-apis-wifiext.md)
...@@ -681,6 +688,7 @@ ...@@ -681,6 +688,7 @@
- [@ohos.screenLock](reference/apis/js-apis-screen-lock.md) - [@ohos.screenLock](reference/apis/js-apis-screen-lock.md)
- [@ohos.systemTime](reference/apis/js-apis-system-time.md) - [@ohos.systemTime](reference/apis/js-apis-system-time.md)
- [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md) - [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md)
- [console](reference/apis/js-apis-logs.md)
- [Timer](reference/apis/js-apis-timer.md) - [Timer](reference/apis/js-apis-timer.md)
- Device Management - Device Management
- [@ohos.batteryInfo ](reference/apis/js-apis-battery-info.md) - [@ohos.batteryInfo ](reference/apis/js-apis-battery-info.md)
...@@ -695,6 +703,7 @@ ...@@ -695,6 +703,7 @@
- [@ohos.power](reference/apis/js-apis-power.md) - [@ohos.power](reference/apis/js-apis-power.md)
- [@ohos.runningLock](reference/apis/js-apis-runninglock.md) - [@ohos.runningLock](reference/apis/js-apis-runninglock.md)
- [@ohos.sensor](reference/apis/js-apis-sensor.md) - [@ohos.sensor](reference/apis/js-apis-sensor.md)
- [@ohos.settings](reference/apis/js-apis-settings.md)
- [@ohos.systemParameter](reference/apis/js-apis-system-parameter.md) - [@ohos.systemParameter](reference/apis/js-apis-system-parameter.md)
- [@ohos.thermal](reference/apis/js-apis-thermal.md) - [@ohos.thermal](reference/apis/js-apis-thermal.md)
- [@ohos.update](reference/apis/js-apis-update.md) - [@ohos.update](reference/apis/js-apis-update.md)
...@@ -751,4 +760,3 @@ ...@@ -751,4 +760,3 @@
- [@system.sensor](reference/apis/js-apis-system-sensor.md) - [@system.sensor](reference/apis/js-apis-system-sensor.md)
- [@system.storage](reference/apis/js-apis-system-storage.md) - [@system.storage](reference/apis/js-apis-system-storage.md)
- [@system.vibrator](reference/apis/js-apis-system-vibrate.md) - [@system.vibrator](reference/apis/js-apis-system-vibrate.md)
- [console](reference/apis/js-apis-logs.md)
\ No newline at end of file
# Window Manager # Window Manager
* Window - [Window Overview](window-overview.md)
* [Window Overview](window-overview.md) - [Window Development](window-guidelines.md)
* [Window Development](window-guidelines.md)
* Display
* [Display Overview](display-overview.md)
* [Display Development](display-guidelines.md)
* Screenshot
* [Screenshot Overview](screenshot-overview.md)
* [Screenshot Development](screenshot-guidelines.md)
# Display Development
## When to Use
An application can obtain the default display object or all display objects by calling the **Display** APIs.
## Available APIs
For details about the APIs, see [Display](../reference/apis/js-apis-display.md).
## How to Develop
Call **getDefaultDisplay(): Promise\<Display>** to obtain the default display object. An example code snippet is as follows:
```js
import display from '@ohos.display' // Import the module.
let disp; // disp is used to save the default display object.
display.getDefaultDisplay().then((disp) => {
console.log('display.getDefaultDisplay success, display :' + JSON.stringify(disp));
}, (err) => {
console.log('display.getDefaultDisplay failed, error : ' + JSON.stringify(err));
})
```
# Display Overview
The **Display** APIs present the window layout of an application. The display attributes include the display ID, name, active status, state, refresh rate, rotation angle, width, height, pixel density, font scaling factor, and exact physical dots per inch.
## Basic Concepts
**Display**: a screen visible to an application. It can be used as a window container. It is an abstract concept that is different from a physical screen.
# Screenshot Development
## When to Use
You can specify a display device to take screenshots, with screenshot parameters specified.
## Available APIs
For details about the APIs, see [Screenshot](../reference/apis/js-apis-screenshot.md).
## How to Develop
Call **save(options?: ScreenshotOptions): Promise<image.PixelMap>** to take a screenshot. In this API, **options** is a predefined screenshot parameter. If **options** is unspecified, the entire screen is captured by default. An example code snippet is as follows:
```js
import screenshot from '@ohos.screenshot' // Import the module.
// Set screenshot parameters.
var ScreenshotOptions = {
"screenRect": {
"left": 200,
"top": 100,
"width": 200,
"height": 200},
"imageSize": {
"width": 300,
"height": 300},
"rotation": 0
};
let image; // image is used to save the screenshot.
screenshot.save(ScreenshotOptions).then((image) => {
console.log('screenshot.save success, screenshot image :' + JSON.stringify(image));
}, (err) => {
console.log('screenshot.save failed, error : ' + JSON.stringify(err));
})
```
# Screenshot Overview
The screenshot APIs, with parameters, enable you to take screenshots on display devices.
## Basic Concepts
Screenshot: provides the screenshot capability.
...@@ -36,12 +36,12 @@ struct UartHostMethod { ...@@ -36,12 +36,12 @@ struct UartHostMethod {
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| Init | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Initializes a UART device.| | Init | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Initializes a UART device.|
| Deinit | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Deinitializes a UART device.| | Deinit | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Deinitializes a UART device.|
| Read | **host**: structure pointer to the UART controller at the core layer.<br>**size**: data size, which is of the uint32_t type.| **data**: pointer to the output data. The value is of the uint8_t type.| HDF_STATUS| Reads data.| | Read | **host**: structure pointer to the UART controller at the core layer.<br>**size**: data size, which is of the uint32_t type.| **data**: pointer to the data read. The value is of the uint8_t type. | HDF_STATUS| Reads data.|
| Write | **host**: structure pointer to the UART controller at the core layer.<br>**data**: pointer to the input data. The value is of the uint8_t type.<br>**size**: data size, which is of the uint32_t type.| –| HDF_STATUS| Writes data.| | Write | **host**: structure pointer to the UART controller at the core layer.<br>**data**: pointer to the data to write. The value is of the uint8_t type.<br>**size**: data size, which is of the uint32_t type. | –| HDF_STATUS| Writes data.|
| SetBaud | **host**: structure pointer to the UART controller at the core layer.<br>**baudRate**: pointer to the input baud rate. The value is of the uint32_t type. | –| HDF_STATUS| Sets the baud rate.| | SetBaud | **host**: structure pointer to the UART controller at the core layer.<br>**baudRate**: pointer to the baud rate to set. The value is of the uint32_t type. | –| HDF_STATUS| Sets the baud rate.|
| GetBaud | **host**: structure pointer to the UART controller at the core layer.| **baudRate**: pointer to the output baud rate. The value is of the uint32_t type.| HDF_STATUS| Obtains the current baud rate.| | GetBaud | **host**: structure pointer to the UART controller at the core layer.| **baudRate**: pointer to the baud rate obtained. The value is of the uint32_t type. | HDF_STATUS| Obtains the current baud rate.|
| GetAttribute | **host**: structure pointer to the UART controller at the core layer.| **attribute**: structure pointer to the UART attributes. For details, see **UartAttribute** in **uart_if.h**.| HDF_STATUS| Obtains UART attributes.| | GetAttribute | **host**: structure pointer to the UART controller at the core layer.| **attribute**: structure pointer to the attribute obtained. For details, see **UartAttribute** in **uart_if.h**. | HDF_STATUS| Obtains UART attributes.|
| SetAttribute | **host**: structure pointer to the UART controller at the core layer.<br>**attribute**: structure pointer to the UART attributes to set.| –| HDF_STATUS| Sets UART attributes.| | SetAttribute | **host**: structure pointer to the UART controller at the core layer.<br>**attribute**: structure pointer to the attribute to set. | –| HDF_STATUS| Sets UART attributes.|
| SetTransMode | **host**: structure pointer to the UART controller at the core layer.<br>**mode**: transfer mode to set. For details, see **UartTransMode** in **uart_if.h**.| –| HDF_STATUS| Sets the UART transfer mode.| | SetTransMode | **host**: structure pointer to the UART controller at the core layer.<br>**mode**: transfer mode to set. For details, see **UartTransMode** in **uart_if.h**.| –| HDF_STATUS| Sets the UART transfer mode.|
| PollEvent | **host**: structure pointer to the UART controller at the core layer.<br>**filep**: void pointer to a file.<br>**table**: void pointer to poll_table.| –| HDF_STATUS| Polls for pending events.| | PollEvent | **host**: structure pointer to the UART controller at the core layer.<br>**filep**: void pointer to a file.<br>**table**: void pointer to poll_table.| –| HDF_STATUS| Polls for pending events.|
...@@ -61,10 +61,11 @@ The UART module adaptation involves the following steps: ...@@ -61,10 +61,11 @@ The UART module adaptation involves the following steps:
3. Instantiate the UART controller object. 3. Instantiate the UART controller object.
- Initialize **UartHost**. - Initialize **UartHost**.
- Instantiate **UartHostMethod** in the **UartHost** object. - Instantiate **UartHostMethod** in the **UartHost** object.
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> For details about the functions in **UartHostMethod**, see [Available APIs](#available-apis). > For details about the functions in **UartHostMethod**, see [Available APIs](#available-apis).
4. Debug the driver.<br> 4. Debug the driver.
(Optional) For new drivers, verify the basic functions, such as the UART status control and response to interrupts. (Optional) For new drivers, verify the basic functions, such as the UART status control and response to interrupts.
...@@ -72,7 +73,12 @@ The UART module adaptation involves the following steps: ...@@ -72,7 +73,12 @@ The UART module adaptation involves the following steps:
The following uses **uart_hi35xx.c** as an example to present the information required for implementing device functions. The following uses **uart_hi35xx.c** as an example to present the information required for implementing device functions.
1. Instantiate the driver entry.<br/>The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke. 1. Instantiate the driver entry.
The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**.
In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit. Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
UART driver entry example: UART driver entry example:
...@@ -89,9 +95,13 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -89,9 +95,13 @@ The following uses **uart_hi35xx.c** as an example to present the information re
HDF_INIT(g_hdfUartDevice); HDF_INIT(g_hdfUartDevice);
``` ```
2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **uart_config.hcs** file.<br> The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer. 2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **uart_config.hcs** file.
The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer.
In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **uart_config** file for each controller. In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **uart_config** file for each controller.
- **device_info.hcs** configuration example
- **device_info.hcs** configuration example:
``` ```
...@@ -107,7 +117,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -107,7 +117,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
priority = 40; // Driver startup priority. priority = 40; // Driver startup priority.
permission = 0644; // Permission for the driver to create a device node. permission = 0644; // Permission for the driver to create a device node.
moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as moduleName in the HdfDriverEntry structure. moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as moduleName in the HdfDriverEntry structure.
serviceName = "HDF_PLATFORM_UART_0";// Unique name of the service published by the driver. The name is in the HDF_PLATFORM_UART_X format. X indicates the UART controller number. serviceName = "HDF_PLATFORM_UART_0"; // Unique name of the service published by the driver. The name is in the HDF_PLATFORM_UART_X format. X indicates the UART controller number.
deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
} }
device1 :: deviceNode { device1 :: deviceNode {
...@@ -133,7 +143,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -133,7 +143,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
platform { platform {
template uart_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes. template uart_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes.
match_attr = ""; match_attr = "";
num = 0; // (Mandatory) Device number num = 0; // (Mandatory) Device number.
baudrate = 115200; // (Mandatory) Baud rate. Set the value based on service requirements. baudrate = 115200; // (Mandatory) Baud rate. Set the value based on service requirements.
fifoRxEn = 1; // (Mandatory) Enable FIFOs to be received. fifoRxEn = 1; // (Mandatory) Enable FIFOs to be received.
fifoTxEn = 1; // (Mandatory) Enable FIFOs to be transferred. fifoTxEn = 1; // (Mandatory) Enable FIFOs to be transferred.
...@@ -159,6 +169,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -159,6 +169,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
``` ```
3. Initialize the **UartHost** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **UartHostMethod** in **UartHost** (so that the underlying driver functions can be called). 3. Initialize the **UartHost** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **UartHostMethod** in **UartHost** (so that the underlying driver functions can be called).
- Defining a custom structure - Defining a custom structure
To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **uart_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number, to the **UartHost** object at the core layer. To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **uart_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number, to the **UartHost** object at the core layer.
...@@ -169,8 +180,8 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -169,8 +180,8 @@ The following uses **uart_hi35xx.c** as an example to present the information re
int32_t enable; int32_t enable;
unsigned long physBase; // Physical address unsigned long physBase; // Physical address
uint32_t irqNum; // Interrupt number uint32_t irqNum; // Interrupt number
uint32_t defaultBaudrate;// Default baud rate uint32_t defaultBaudrate; // Default baud rate
uint32_t flags; // Flags related to the following three macros. uint32_t flags; // Flags related to the following three macros
#define PL011_FLG_IRQ_REQUESTED (1 << 0) #define PL011_FLG_IRQ_REQUESTED (1 << 0)
#define PL011_FLG_DMA_RX_REQUESTED (1 << 1) #define PL011_FLG_DMA_RX_REQUESTED (1 << 1)
#define PL011_FLG_DMA_TX_REQUESTED (1 << 2) #define PL011_FLG_DMA_TX_REQUESTED (1 << 2)
...@@ -180,7 +191,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -180,7 +191,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
struct UartDriverData { // Structure related to data transfer struct UartDriverData { // Structure related to data transfer
uint32_t num; uint32_t num;
uint32_t baudrate; // Baud rate (configurable) uint32_t baudrate; // Baud rate (configurable)
struct UartAttribute attr; // Attributes, such as the data bit and stop bit, related to data transfer struct UartAttribute attr; // Attributes, such as the data bit and stop bit, related to data transfer.
struct UartTransfer *rxTransfer; // Buffer (FIFO structure) struct UartTransfer *rxTransfer; // Buffer (FIFO structure)
wait_queue_head_t wait; // Queuing signal related to conditional variables wait_queue_head_t wait; // Queuing signal related to conditional variables
int32_t count; // Data count int32_t count; // Data count
...@@ -193,7 +204,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -193,7 +204,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
#define UART_FLG_DMA_RX (1 << 0) #define UART_FLG_DMA_RX (1 << 0)
#define UART_FLG_DMA_TX (1 << 1) #define UART_FLG_DMA_TX (1 << 1)
#define UART_FLG_RD_BLOCK (1 << 2) #define UART_FLG_RD_BLOCK (1 << 2)
RecvNotify recv; // Pointer to the function that receives serial port data RecvNotify recv; // Pointer to the function that receives serial port data.
struct UartOps *ops; // Custom function pointer structure. For details, see device/hisilicon/drivers/uart/uart_pl011.c. struct UartOps *ops; // Custom function pointer structure. For details, see device/hisilicon/drivers/uart/uart_pl011.c.
void *private; // It stores the pointer to the start address of UartPl011Port for easy invocation. void *private; // It stores the pointer to the start address of UartPl011Port for easy invocation.
}; };
...@@ -208,6 +219,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -208,6 +219,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
struct UartHostMethod *method; // Hook at the core layer. You need to implement and instantiate its member functions. struct UartHostMethod *method; // Hook at the core layer. You need to implement and instantiate its member functions.
}; };
``` ```
- Instantiating **UartHostMethod** in **UartHost** (other members are initialized by **Bind**) - Instantiating **UartHostMethod** in **UartHost** (other members are initialized by **Bind**)
...@@ -229,15 +241,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -229,15 +241,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re
- **Bind** function - **Bind** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
HDF_STATUS<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **/drivers/framework/include/utils/hdf_base.h** file. **HDF_STATUS**<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **/drivers/framework/include/utils/hdf_base.h** file.
**Table 2** HDF_STATUS **Table 2** Description of HDF_STATUS
| Status| Description| | Status| Description|
| -------- | -------- | | -------- | -------- |
...@@ -248,7 +260,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -248,7 +260,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
| HDF_SUCCESS | Initialization successful.| | HDF_SUCCESS | Initialization successful.|
| HDF_FAILURE | Initialization failed.| | HDF_FAILURE | Initialization failed.|
Function description: **Function description**:
Initializes the custom structure object and **UartHost**. Initializes the custom structure object and **UartHost**.
...@@ -267,9 +279,9 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -267,9 +279,9 @@ The following uses **uart_hi35xx.c** as an example to present the information re
... ...
host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Allocate memory. host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Allocate memory.
... ...
host->device = device; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost host->device = device; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost.
device->service = &(host->service; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost device->service = &(host->service; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost.
host->device->service->Dispatch = UartIoDispatch;// Assign values to Dispatch of service. host->device->service->Dispatch = UartIoDispatch; // Assign values to Dispatch of service.
OsalAtomicSet(&host->atom, 0); // Initialize or set the atomic services. OsalAtomicSet(&host->atom, 0); // Initialize or set the atomic services.
host->priv = NULL; host->priv = NULL;
host->method = NULL; host->method = NULL;
...@@ -279,15 +291,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -279,15 +291,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re
- **Init** function - **Init** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
HDF_STATUS **HDF_STATUS**
Function description: **Function description**:
Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to the VFS. Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to the VFS.
...@@ -303,7 +315,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -303,7 +315,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
... ...
ret = Hi35xxAttach(host, device); // Initialize the UartHost object. ret = Hi35xxAttach(host, device); // Initialize the UartHost object.
... ...
host->method = &g_uartHostMethod; // Hook the UartHostMethod instance. host->method = &g_uartHostMethod; // Attach the UartHostMethod instance.
return ret; return ret;
} }
// Initialize UartHost. // Initialize UartHost.
...@@ -351,17 +363,21 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -351,17 +363,21 @@ The following uses **uart_hi35xx.c** as an example to present the information re
``` ```
- **Release** function - **Release** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
No value is returned. No value is returned.
Function description: **Function description**:
Releases the memory and deletes the controller. This function assigns values to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources.
Releases the memory and deletes the controller. This function assigns values to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations.
``` ```
...@@ -369,7 +385,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -369,7 +385,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
{ {
struct UartHost *host = NULL; struct UartHost *host = NULL;
... ...
host = UartHostFromDevice(device);// Forcibly convert HdfDeviceObject to UartHost by using service. For details about the value assignment, see the Bind function. host = UartHostFromDevice(device); // Forcibly convert HdfDeviceObject to UartHost by using service. For details about the value assignment, see the Bind function.
... ...
if (host->priv != NULL) { if (host->priv != NULL) {
Hi35xxDetach(host); // Customized memory release function. Hi35xxDetach(host); // Customized memory release function.
...@@ -382,10 +398,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -382,10 +398,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re
struct UartDriverData *udd = NULL; struct UartDriverData *udd = NULL;
struct UartPl011Port *port = NULL; struct UartPl011Port *port = NULL;
... ...
udd = host->priv; // Convert UartHost to UartDriverData. udd = host->priv; // The conversion from UartHost to UartDriverData is involved.
... ...
UartRemoveDev(host);// Remove the VFS. UartRemoveDev (host); // Remove the VFS.
port = udd->private;// Convert UartDriverData to UartPl011Port. port = udd->private; // The conversion from UartDriverData to UartPl011Port is involved.
if (port != NULL) { if (port != NULL) {
if (port->physBase != 0) { if (port->physBase != 0) {
OsalIoUnmap((void *)port->physBase);// Unmap addresses. OsalIoUnmap((void *)port->physBase);// Unmap addresses.
...@@ -393,7 +409,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -393,7 +409,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
OsalMemFree(port); OsalMemFree(port);
udd->private = NULL; udd->private = NULL;
} }
OsalMemFree(udd);//Release UartDriverData. OsalMemFree (udd); // Release UartDriverData.
host->priv = NULL; host->priv = NULL;
} }
``` ```
...@@ -19,13 +19,13 @@ ...@@ -19,13 +19,13 @@
- [Software Timer](kernel-mini-basic-soft.md) - [Software Timer](kernel-mini-basic-soft.md)
- Extended Components - Extended Components
- [C++ Support](kernel-mini-extend-support.md) - [C++ Support](kernel-mini-extend-support.md)
- [PUP](kernel-mini-extend-cpup.md) - [CPUP](kernel-mini-extend-cpup.md)
- [Dynamic Loading](kernel-mini-extend-dynamic-loading.md) - [Dynamic Loading](kernel-mini-extend-dynamic-loading.md)
- [File System](kernel-mini-extend-file.md) - File System
- [FAT](kernel-mini-extend-file-fat.md) - [FAT](kernel-mini-extend-file-fat.md)
- [LittleFS](kernel-mini-extend-file-lit.md) - [LittleFS](kernel-mini-extend-file-lit.md)
- Kernel Debugging - Kernel Debugging
- [Memory Debugging](kernel-mini-memory-debug.md) - Memory Debugging
- [Memory Information Statistics](kernel-mini-memory-debug-mes.md) - [Memory Information Statistics](kernel-mini-memory-debug-mes.md)
- [Memory Leak Check](kernel-mini-memory-debug-det.md) - [Memory Leak Check](kernel-mini-memory-debug-det.md)
- [Memory Corruption Check](kernel-mini-memory-debug-cet.md) - [Memory Corruption Check](kernel-mini-memory-debug-cet.md)
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
- [Dynamic Loading and Linking](kernel-small-bundles-linking.md) - [Dynamic Loading and Linking](kernel-small-bundles-linking.md)
- [Virtual Dynamic Shared Object](kernel-small-bundles-share.md) - [Virtual Dynamic Shared Object](kernel-small-bundles-share.md)
- [LiteIPC](kernel-small-bundles-ipc.md) - [LiteIPC](kernel-small-bundles-ipc.md)
- [File Systems](kernel-small-bundles-fs.md) - File Systems
- [Virtual File System](kernel-small-bundles-fs-virtual.md) - [Virtual File System](kernel-small-bundles-fs-virtual.md)
- Supported File Systems - Supported File Systems
- [FAT](kernel-small-bundles-fs-support-fat.md) - [FAT](kernel-small-bundles-fs-support-fat.md)
...@@ -160,7 +160,7 @@ ...@@ -160,7 +160,7 @@
- [Working Principles](kernel-small-debug-user-function.md) - [Working Principles](kernel-small-debug-user-function.md)
- Usage - Usage
- [Available APIs](kernel-small-debug-user-guide-api.md) - [Available APIs](kernel-small-debug-user-guide-api.md)
- [How to Use](kernel-small-debug-user-guide-use.md) - How to Use
- [Calling APIs](kernel-small-debug-user-guide-use-api.md) - [Calling APIs](kernel-small-debug-user-guide-use-api.md)
- [Using the CLI](kernel-small-debug-user-guide-use-cli.md) - [Using the CLI](kernel-small-debug-user-guide-use-cli.md)
- [Typical Memory Problems](kernel-small-debug-user-faqs.md) - [Typical Memory Problems](kernel-small-debug-user-faqs.md)
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
- [Burning](quickstart-ide-lite-steps-hi3516-burn.md) - [Burning](quickstart-ide-lite-steps-hi3516-burn.md)
- [Running](quickstart-ide-lite-steps-hi3516-running.md) - [Running](quickstart-ide-lite-steps-hi3516-running.md)
- Appendix - Appendix
- Introduction to Development Boards
- [Introduction to the Hi3861 Development Board](quickstart-ide-lite-introduction-hi3861.md) - [Introduction to the Hi3861 Development Board](quickstart-ide-lite-introduction-hi3861.md)
- [Introduction to the Hi3516 Development Board](quickstart-ide-lite-introduction-hi3516.md) - [Introduction to the Hi3516 Development Board](quickstart-ide-lite-introduction-hi3516.md)
- Getting Started with Mini and Small Systems (Installation Package Mode) - Getting Started with Mini and Small Systems (Installation Package Mode)
...@@ -67,7 +66,6 @@ ...@@ -67,7 +66,6 @@
- [Burning](quickstart-ide-standard-running-rk3568-burning.md) - [Burning](quickstart-ide-standard-running-rk3568-burning.md)
- [Running](quickstart-ide-standard-running-rk3568-running.md) - [Running](quickstart-ide-standard-running-rk3568-running.md)
- Appendix - Appendix
- Introduction to Development Boards
- [Introduction to the Hi3516 Development Board](quickstart-ide-standard-board-introduction-hi3516.md) - [Introduction to the Hi3516 Development Board](quickstart-ide-standard-board-introduction-hi3516.md)
- [Introduction to the RK3568 Development Board](quickstart-ide-standard-board-introduction-rk3568.md) - [Introduction to the RK3568 Development Board](quickstart-ide-standard-board-introduction-rk3568.md)
- Getting Started with Standard System (Installation Package Mode) - Getting Started with Standard System (Installation Package Mode)
......
...@@ -14,13 +14,13 @@ ...@@ -14,13 +14,13 @@
| 接口名称 | 描述 | | 接口名称 | 描述 |
| ------------------------------------------------------------ | ----------------------------------------------- | | ------------------------------------------------------------ | ----------------------------------------------- |
| createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br/>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | 创建一个`KVManager`对象实例,用于管理数据库对象。 | | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br/>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | 创建一个`KVManager`对象实例,用于管理数据库对象。 |
| getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options,callback:AsyncCallback&lt;T&gt;):void<br/>getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options):Promise&lt;T&gt; | 指定`Options``storeId`,创建并获取`KVStore`数据库。 | | getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br/>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | 指定`Options``storeId`,创建并获取`KVStore`数据库。 |
| put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback&lt;void&gt;):void<br/>put(key:string,value:Uint8Array\|string\|number\|boolean):Promise&lt;void> | 插入和更新数据。 | | put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br/>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | 插入和更新数据。 |
| delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br/>delete(key:string):Promise&lt;void> | 删除数据。 | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br/>delete(key: string): Promise&lt;void> | 删除数据。 |
| get(key:string,callback:AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;):void<br/>get(key:string):Promise&lt;Uint8Array\|string\|boolean\|number> | 查询数据。 | | get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br/>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | 查询数据。 |
| on(event:'dataChange',type:SubscribeType,observer:Callback&lt;ChangeNotification&gt;):void<br/>on(event:'syncComplete',syncCallback:Callback&lt;Array&lt;[string,number]&gt;&gt;):void | 订阅数据库中数据的变化。 | | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br/>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): void | 订阅数据库中数据的变化。 |
| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | 在手动模式下,触发数据库同步。 | | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | 在手动模式下,触发数据库同步。 |
...@@ -34,8 +34,40 @@ ...@@ -34,8 +34,40 @@
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedData from '@ohos.data.distributedData';
``` ```
2. 请求权限(同步操作时进行该步骤)。
2. 根据配置构造分布式数据库管理类实例。 需要在`config.json`文件里进行配置请求权限,示例代码如下:
```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
这个权限还需要在应用首次启动的时候弹窗获取用户授权,可以通过如下代码实现:
```js
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
3. 根据配置构造分布式数据库管理类实例。
1. 根据应用上下文创建`kvManagerConfig`对象。 1. 根据应用上下文创建`kvManagerConfig`对象。
2. 创建分布式数据库管理器实例。 2. 创建分布式数据库管理器实例。
...@@ -64,7 +96,7 @@ ...@@ -64,7 +96,7 @@
} }
``` ```
3. 获取/创建分布式数据库。 4. 获取/创建分布式数据库。
1. 声明需要创建的分布式数据库ID描述。 1. 声明需要创建的分布式数据库ID描述。
2. 创建分布式数据库,建议关闭自动同步功能(`autoSync:false`),需要同步时主动调用`sync`接口。 2. 创建分布式数据库,建议关闭自动同步功能(`autoSync:false`),需要同步时主动调用`sync`接口。
...@@ -98,7 +130,7 @@ ...@@ -98,7 +130,7 @@
> >
> 组网设备间同步数据的场景,建议在应用启动时打开分布式数据库,获取数据库的句柄。在该句柄(如示例中的`kvStore`)的生命周期内无需重复创建数据库,可直接使用句柄对数据库进行数据的插入等操作。 > 组网设备间同步数据的场景,建议在应用启动时打开分布式数据库,获取数据库的句柄。在该句柄(如示例中的`kvStore`)的生命周期内无需重复创建数据库,可直接使用句柄对数据库进行数据的插入等操作。
4. 订阅分布式数据变化。 5. 订阅分布式数据变化。
以下为订阅单版本分布式数据库数据变化通知的代码示例: 以下为订阅单版本分布式数据库数据变化通知的代码示例:
```js ```js
...@@ -107,7 +139,7 @@ ...@@ -107,7 +139,7 @@
}); });
``` ```
5. 将数据写入分布式数据库。 6. 将数据写入分布式数据库。
1. 构造需要写入分布式数据库的`Key`(键)和`Value`(值)。 1. 构造需要写入分布式数据库的`Key`(键)和`Value`(值)。
2. 将键值数据写入分布式数据库。 2. 将键值数据写入分布式数据库。
...@@ -130,7 +162,7 @@ ...@@ -130,7 +162,7 @@
} }
``` ```
6. 查询分布式数据库数据。 7. 查询分布式数据库数据。
1. 构造需要从单版本分布式数据库中查询的`Key`(键)。 1. 构造需要从单版本分布式数据库中查询的`Key`(键)。
2. 从单版本分布式数据库中获取数据。 2. 从单版本分布式数据库中获取数据。
...@@ -155,7 +187,7 @@ ...@@ -155,7 +187,7 @@
} }
``` ```
7. 同步数据到其他设备。 8. 同步数据到其他设备。
选择同一组网环境下的设备以及同步模式,进行数据同步。 选择同一组网环境下的设备以及同步模式,进行数据同步。
......
...@@ -9,65 +9,69 @@ ...@@ -9,65 +9,69 @@
## 基本概念 ## 基本概念
- **KV数据模型** ### KV数据模型
“KV数据模型”是“Key-Value数据模型”的简称,“Key-Value”即“键-值”;其数据以键值对的形式进行组织、索引和存储。
KV数据模型适合不涉及过多数据关系和业务关系的业务数据存储,比SQL数据库存储拥有更好的读写性能,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。分布式数据库也是基于KV数据模型,对外提供KV类型的访问接口 “KV数据模型”是“Key-Value数据模型”的简称,“Key-Value”即“键-值”;其数据以键值对的形式进行组织、索引和存储
- **分布式数据库事务性** KV数据模型适合不涉及过多数据关系和业务关系的业务数据存储,比SQL数据库存储拥有更好的读写性能,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。分布式数据库也是基于KV数据模型,对外提供KV类型的访问接口。
分布式数据库事务支持本地事务(和传统数据库的事务概念一致)和同步事务。同步事务是指在设备之间同步数据时,以本地事务为单位进行同步,一次本地事务的修改要么都同步成功,要么都同步失败。
- **分布式数据库一致性** ### 分布式数据库事务性
在分布式场景中一般会涉及多个设备,组网内设备之间看到的数据是否一致称为分布式数据库的一致性。分布式数据库一致性可以分为**强一致性****弱一致性****最终一致性**
- **强一致性**:是指某一设备成功增、删、改数据后,组网内设备对该数据的读取操作都将得到更新后的值。 分布式数据库事务支持本地事务(和传统数据库的事务概念一致)和同步事务。同步事务是指在设备之间同步数据时,以本地事务为单位进行同步,一次本地事务的修改要么都同步成功,要么都同步失败。
- **弱一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取到本次更新数据,也可能读取不到,不能保证在多长时间后每个设备的数据一定是一致的。
- **最终一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取不到本次更新数据,但在某个时间窗口之后组网内设备的数据能够达到一致状态。
强一致性对分布式数据的管理要求非常高,在服务器的分布式场景可能会遇到。因为移动终端设备的不常在线、以及无中心的特性,分布式数据服务不支持强一致性,只支持最终一致性。 ### 分布式数据库一致性
- **分布式数据库同步** 在分布式场景中一般会涉及多个设备,组网内设备之间看到的数据是否一致称为分布式数据库的一致性。分布式数据库一致性可以分为**强一致性****弱一致性****最终一致性**
底层通信组件完成设备发现和认证,会通知上层应用程序(包括分布式数据服务)设备上线。收到设备上线的消息后分布式数据服务可以在两个设备之间建立加密的数据传输通道,利用该通道在两个设备之间进行数据同步。
分布式数据服务提供了两种同步方式:**手动同步****自动同步** - **强一致性**:是指某一设备成功增、删、改数据后,组网内设备对该数据的读取操作都将得到更新后的值。
- **弱一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取到本次更新数据,也可能读取不到,不能保证在多长时间后每个设备的数据一定是一致的。
- **最终一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取不到本次更新数据,但在某个时间窗口之后组网内设备的数据能够达到一致状态。
- **手动同步**:由应用程序调用sync接口来触发,需要指定同步的设备列表和同步模式。同步模式分为PULL_ONLY(将远端数据拉到本端)、PUSH_ONLY(将本端数据推送到远端)和PUSH_PULL(将本端数据推送到远端同时也将远端数据拉取到本端)。内部接口支持按条件过滤同步,将符合条件的数据同步到远端。 强一致性对分布式数据的管理要求非常高,在服务器的分布式场景可能会遇到。因为移动终端设备的不常在线、以及无中心的特性,分布式数据服务不支持强一致性,只支持最终一致性。
- **自动同步**:包括全量同步和按条件订阅同步。全量同步由分布式数据库自动将本端数据推送到远端,同时也将远端数据拉取到本端来完成数据同步,同步时机包括设备上线、应用程序更新数据等,应用不需要主动调用sync接口;内部接口支持按条件订阅同步,将远端符合订阅条件的数据自动同步到本端。
- **单版本分布式数据库** ### 分布式数据库同步
单版本是指数据在本地保存是以单个KV条目为单位的方式保存,对每个Key最多只保存一个条目项,当数据在本地被用户修改时,不管它是否已经被同步出去,均直接在这个条目上进行修改。同步也以此为基础,按照它在本地被写入或更改的顺序将当前最新一次修改逐条同步至远端设备。
- **设备协同分布式数据库** 底层通信组件完成设备发现和认证,会通知上层应用程序(包括分布式数据服务)设备上线。收到设备上线的消息后分布式数据服务可以在两个设备之间建立加密的数据传输通道,利用该通道在两个设备之间进行数据同步。
设备协同分布式数据库建立在单版本分布式数据库之上,对应用程序存入的KV数据中的Key前面拼接了本设备的DeviceID标识符,这样能保证每个设备产生的数据严格隔离,底层按照设备的维度管理这些数据,设备协同分布式数据库支持以设备的维度查询分布式数据,但是不支持修改远端设备同步过来的数据。
- **分布式数据库冲突解决策略** 分布式数据服务提供了两种同步方式:**手动同步****自动同步**
分布式数据库多设备提交冲突场景,在给提交冲突做合并的过程中,如果多个设备同时修改了同一数据,则称这种场景为数据冲突。数据冲突采用默认冲突解决策略(Last-write-wins),基于提交时间戳,取时间戳较大的提交数据,当前不支持定制冲突解决策略。
- **数据库Schema化管理与谓词查询** - **手动同步**:由应用程序调用sync接口来触发,需要指定同步的设备列表和同步模式。同步模式分为PULL_ONLY(将远端数据拉到本端)、PUSH_ONLY(将本端数据推送到远端)和PUSH_PULL(将本端数据推送到远端同时也将远端数据拉取到本端)。内部接口支持按条件过滤同步,将符合条件的数据同步到远端。
单版本数据库支持在创建和打开数据库时指定Schema,数据库根据Schema定义感知KV记录的Value格式,以实现对Value值结构的检查,并基于Value中的字段实现索引建立和谓词查询 - **自动同步**:包括全量同步和按条件订阅同步。全量同步由分布式数据库自动将本端数据推送到远端,同时也将远端数据拉取到本端来完成数据同步,同步时机包括设备上线、应用程序更新数据等,应用不需要主动调用sync接口;内部接口支持按条件订阅同步,将远端符合订阅条件的数据自动同步到本端
- **分布式数据库备份能力** ### 单版本分布式数据库
提供分布式数据库备份能力,业务通过设置backup属性为true,可以触发分布式数据服务每日备份。当分布式数据库发生损坏,分布式数据服务会删除损坏数据库,并且从备份数据库中恢复上次备份的数据。如果不存在备份数据库,则创建一个新的数据库。同时支持加密数据库的备份能力。
单版本是指数据在本地保存是以单个KV条目为单位的方式保存,对每个Key最多只保存一个条目项,当数据在本地被用户修改时,不管它是否已经被同步出去,均直接在这个条目上进行修改。同步也以此为基础,按照它在本地被写入或更改的顺序将当前最新一次修改逐条同步至远端设备。
### 设备协同分布式数据库
设备协同分布式数据库建立在单版本分布式数据库之上,对应用程序存入的KV数据中的Key前面拼接了本设备的DeviceID标识符,这样能保证每个设备产生的数据严格隔离,底层按照设备的维度管理这些数据,设备协同分布式数据库支持以设备的维度查询分布式数据,但是不支持修改远端设备同步过来的数据。
### 分布式数据库冲突解决策略
分布式数据库多设备提交冲突场景,在给提交冲突做合并的过程中,如果多个设备同时修改了同一数据,则称这种场景为数据冲突。数据冲突采用默认冲突解决策略(Last-write-wins),基于提交时间戳,取时间戳较大的提交数据,当前不支持定制冲突解决策略。
### 数据库Schema化管理与谓词查询
单版本数据库支持在创建和打开数据库时指定Schema,数据库根据Schema定义感知KV记录的Value格式,以实现对Value值结构的检查,并基于Value中的字段实现索引建立和谓词查询。
### 分布式数据库备份能力
提供分布式数据库备份能力,业务通过设置backup属性为true,可以触发分布式数据服务每日备份。当分布式数据库发生损坏,分布式数据服务会删除损坏数据库,并且从备份数据库中恢复上次备份的数据。如果不存在备份数据库,则创建一个新的数据库。同时支持加密数据库的备份能力。
## 运作机制 ## 运作机制
分布式数据服务支撑OpenHarmony系统上应用程序数据库数据分布式管理,支持数据在相同帐号的多端设备之间相互同步,为用户在多端设备上提供一致的用户体验,分布式数据服务包含五部分: 分布式数据服务支撑OpenHarmony系统上应用程序数据库数据分布式管理,支持数据在相同帐号的多端设备之间相互同步,为用户在多端设备上提供一致的用户体验,分布式数据服务包含五部分:
- **服务接口** - **服务接口:** 分布式数据服务提供专门的数据库创建、数据访问、数据订阅等接口给应用程序调用,接口支持KV数据模型,支持常用的数据类型,同时确保接口的兼容性、易用性和可发布性。
分布式数据服务提供专门的数据库创建、数据访问、数据订阅等接口给应用程序调用,接口支持KV数据模型,支持常用的数据类型,同时确保接口的兼容性、易用性和可发布性。
- **服务组件** - **服务组件:** 服务组件负责服务内元数据管理、权限管理、加密管理、备份和恢复管理以及多用户管理等、同时负责初始化底层分布式DB的存储组件、同步组件和通信适配层。
服务组件负责服务内元数据管理、权限管理、加密管理、备份和恢复管理以及多用户管理等、同时负责初始化底层分布式DB的存储组件、同步组件和通信适配层。
- **存储组件** - **存储组件:** 存储组件负责数据的访问、数据的缩减、事务、快照、数据库加密,以及数据合并和冲突解决等特性。
存储组件负责数据的访问、数据的缩减、事务、快照、数据库加密,以及数据合并和冲突解决等特性。
- **同步组件** - **同步组件:** 同步组件连结了存储组件与通信组件,其目标是保持在线设备间的数据库数据一致性,包括将本地产生的未同步数据同步给其他设备,接收来自其他设备发送过来的数据,并合并到本地设备中。
同步组件连结了存储组件与通信组件,其目标是保持在线设备间的数据库数据一致性,包括将本地产生的未同步数据同步给其他设备,接收来自其他设备发送过来的数据,并合并到本地设备中。
- **通信适配层** - **通信适配层:** 通信适配层负责调用底层公共通信层的接口完成通信管道的创建、连接,接收设备上下线消息,维护已连接和断开设备列表的元数据,同时将设备上下线信息发送给上层同步组件,同步组件维护连接的设备列表,同步数据时根据该列表,调用通信适配层的接口将数据封装并发送给连接的设备。
通信适配层负责调用底层公共通信层的接口完成通信管道的创建、连接,接收设备上下线消息,维护已连接和断开设备列表的元数据,同时将设备上下线信息发送给上层同步组件,同步组件维护连接的设备列表,同步数据时根据该列表,调用通信适配层的接口将数据封装并发送给连接的设备。
应用程序通过调用分布式数据服务接口实现分布式数据库创建、访问、订阅功能,服务接口通过操作服务组件提供的能力,将数据存储至存储组件,存储组件调用同步组件实现将数据同步,同步组件使用通信适配层将数据同步至远端设备,远端设备通过同步组件接收数据,并更新至本端存储组件,通过服务接口提供给应用程序使用。 应用程序通过调用分布式数据服务接口实现分布式数据库创建、访问、订阅功能,服务接口通过操作服务组件提供的能力,将数据存储至存储组件,存储组件调用同步组件实现将数据同步,同步组件使用通信适配层将数据同步至远端设备,远端设备通过同步组件接收数据,并更新至本端存储组件,通过服务接口提供给应用程序使用。
...@@ -83,6 +87,7 @@ ...@@ -83,6 +87,7 @@
- 分布式数据服务的数据模型仅支持KV数据模型,不支持外键、触发器等关系型数据库中的功能。 - 分布式数据服务的数据模型仅支持KV数据模型,不支持外键、触发器等关系型数据库中的功能。
- 分布式数据服务支持的KV数据模型规格: - 分布式数据服务支持的KV数据模型规格:
- 设备协同数据库,针对每条记录,Key的长度≤896 Byte,Value的长度&lt;4 MB。 - 设备协同数据库,针对每条记录,Key的长度≤896 Byte,Value的长度&lt;4 MB。
- 单版本数据库,针对每条记录,Key的长度≤1 KB,Value的度&lt;4 MB。 - 单版本数据库,针对每条记录,Key的长度≤1 KB,Value的度&lt;4 MB。
- 每个应用程序最多支持同时打开16个分布式数据库。 - 每个应用程序最多支持同时打开16个分布式数据库。
......
...@@ -16,8 +16,8 @@ ...@@ -16,8 +16,8 @@
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
|getRdbStore(config:StoreConfig,version:number):Promise&lt;RdbStore&gt; | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。<br/>-config:与此RDB存储相关的数据库配置。<br/>-version:数据库版本。 | |getRdbStore(config: StoreConfig, version: number): Promise&lt;RdbStore&gt; | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。<br/>-config:与此RDB存储相关的数据库配置。<br/>-version:数据库版本。 |
| deleteRdbStore(name:string):Promise&lt;void&gt; | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。<br/>-name:数据库名称。 | | deleteRdbStore(name: string): Promise&lt;void&gt; | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。<br/>-name:数据库名称。 |
### 数据库的增删改查 ### 数据库的增删改查
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | insert(name:string,values:ValuesBucket):Promise&lt;number&gt; | 向目标表中插入一行数据,使用Promise异步回调。<br>如果操作成功,返回行ID;否则返回-1。<br/>-name:指定的目标表名。<br/>-values:表示要插入到表中的数据行。 | | RdbStore | insert(name: string, values: ValuesBucket): Promise&lt;number&gt; | 向目标表中插入一行数据,使用Promise异步回调。<br>如果操作成功,返回行ID;否则返回-1。<br/>-name:指定的目标表名。<br/>-values:表示要插入到表中的数据行。 |
- **更新** - **更新**
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-values:以ValuesBucket存储的要更新的数据。<br/>-rdbPredicates:表示RdbPredicates的实例对象指定的更新条件。 | | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise\<number> | 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-values:以ValuesBucket存储的要更新的数据。<br/>-rdbPredicates:表示RdbPredicates的实例对象指定的更新条件。 |
- **删除** - **删除**
...@@ -51,7 +51,7 @@ ...@@ -51,7 +51,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | 根据rdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-rdbPredicates:RdbPredicates的实例对象指定的删除条件。 | | RdbStore | delete(rdbPredicates: RdbPredicates): Promise\<number> | 根据rdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-rdbPredicates:RdbPredicates的实例对象指定的删除条件。 |
- **查询** - **查询**
...@@ -64,8 +64,8 @@ ...@@ -64,8 +64,8 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | query(rdbPredicates:RdbPredicates,columns:Array):Promise&lt;ResultSet&gt; | 根据指定条件查询数据库中的数据,使用Promise异步回调。<br/>-rdbPredicates:表示RdbPredicates的实例对象指定的查询条件。<br/>-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise&lt;ResultSet&gt; | 根据指定条件查询数据库中的数据,使用Promise异步回调。<br/>-rdbPredicates:表示RdbPredicates的实例对象指定的查询条件。<br/>-columns:表示要查询的列。如果值为空,则查询应用于所有列。 |
| RdbStore | querySql(sql:string,bindArgs?:Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。<br/>-sql:指定要查询的SQL语句。<br/>-bindArgs:SQL语句中参数的值。 | | RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;): Promise&lt;ResultSet&gt; | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。<br/>-sql:指定要查询的SQL语句。<br/>-bindArgs:SQL语句中参数的值。 |
### 数据库谓词的使用 ### 数据库谓词的使用
...@@ -77,11 +77,11 @@ ...@@ -77,11 +77,11 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 | | RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 | | RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicates | or():RdbPredicates | 将或条件添加到谓词中。<br/>-RdbPredicates:返回带有或条件的谓词。 | | RdbPredicates | or(): RdbPredicates | 将或条件添加到谓词中。<br/>-RdbPredicates:返回带有或条件的谓词。 |
| RdbPredicates | and():RdbPredicates | 向谓词添加和条件。<br/>-RdbPredicates:返回带有和条件的谓词。 | | RdbPredicates | and(): RdbPredicates | 向谓词添加和条件。<br/>-RdbPredicates:返回带有和条件的谓词。 |
| RdbPredicates | contains(field:string,value:string):RdbPredicats | 配置谓词以匹配数据字段为String且value包含指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回带有包含条件的谓词。 | | RdbPredicates | contains(field: string, value: string): RdbPredicats | 配置谓词以匹配数据字段为String且value包含指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回带有包含条件的谓词。 |
### 查询结果集的使用 ### 查询结果集的使用
...@@ -97,12 +97,12 @@ ...@@ -97,12 +97,12 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ResultSet | goToFirstRow():boolean | 将结果集移动到第一行。 | | ResultSet | goToFirstRow(): boolean | 将结果集移动到第一行。 |
| ResultSet | getString(columnIndex:number):string | 获取当前行指定列的值,以String类型返回。 | | ResultSet | getString(columnIndex:number): string | 获取当前行指定列的值,以String类型返回。 |
| ResultSet | getBlob(columnIndex:number):Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 | | ResultSet | getBlob(columnIndex:number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 |
| ResultSet | getDouble(columnIndex:number):number | 获取当前行指定列的值,以double型返回。 | | ResultSet | getDouble(columnIndex:number): number | 获取当前行指定列的值,以double型返回。 |
| ResultSet | getLong(columnIndex:number):number | 获取当前行指定列的值,以Long形式返回。 | | ResultSet | getLong(columnIndex:number): number | 获取当前行指定列的值,以Long形式返回。 |
| ResultSet | close():void | 关闭结果集。 | | ResultSet | close(): void | 关闭结果集。 |
......
...@@ -17,19 +17,19 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js ...@@ -17,19 +17,19 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js
| 接口名 | 描述 | | 接口名 | 描述 |
| -------- | -------- | | -------- | -------- |
| hasRight(deviceName:string):boolean | 如果“使用者”(如各种App或系统)有权访问设备则返回true;无权访问设备则返回false。 | | hasRight(deviceName: string): boolean | 如果“使用者”(如各种App或系统)有权访问设备则返回true;无权访问设备则返回false。 |
| requestRight(deviceName:string):Promise&lt;boolean&gt; | 请求给定软件包的临时权限以访问设备。 | | requestRight(deviceName: string): Promise&lt;boolean&gt; | 请求给定软件包的临时权限以访问设备。 |
| connectDevice(device:USBDevice):Readonly&lt;USBDevicePipe&gt; | 根据`getDevices()`返回的设备信息打开USB设备。 | | connectDevice(device: USBDevice): Readonly&lt;USBDevicePipe&gt; | 根据`getDevices()`返回的设备信息打开USB设备。 |
| getDevices():Array&lt;Readonly&lt;USBDevice&gt;&gt; | 返回USB设备列表。 | | getDevices(): Array&lt;Readonly&lt;USBDevice&gt;&gt; | 返回USB设备列表。 |
| setConfiguration(pipe:USBDevicePipe,config:USBConfig):number | 设置设备的配置。 | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | 设置设备的配置。 |
| setInterface(pipe:USBDevicePipe,iface:USBInterface):number | 设置设备的接口。 | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | 设置设备的接口。 |
| claimInterface(pipe:USBDevicePipe,iface:USBInterface,force?:boolean):number | 获取接口。 | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | 获取接口。 |
|bulkTransfer(pipe:USBDevicePipe,endpoint:USBEndpoint,buffer:Uint8Array,timeout?:number):Promise&lt;number&gt; | 批量传输。 | |bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise&lt;number&gt; | 批量传输。 |
| closePipe(pipe:USBDevicePipe):number | 关闭设备消息控制通道。 | | closePipe(pipe: USBDevicePipe): number | 关闭设备消息控制通道。 |
| releaseInterface(pipe:USBDevicePipe,iface:USBInterface):number | 释放接口。 | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | 释放接口。 |
| getFileDescriptor(pipe:USBDevicePipe):number | 获取文件描述符。 | | getFileDescriptor(pipe: USBDevicePipe): number | 获取文件描述符。 |
| getRawDescriptor(pipe:USBDevicePipe):Uint8Array | 获取原始的USB描述符。 | | getRawDescriptor(pipe: USBDevicePipe): Uint8Array | 获取原始的USB描述符。 |
| controlTransfer(pipe:USBDevicePipe,contrlparam:USBControlParams,timeout?:number):Promise&lt;number&gt; | 控制传输。 | | controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise&lt;number&gt; | 控制传输。 |
## 开发步骤 ## 开发步骤
...@@ -39,7 +39,7 @@ USB设备可作为Host设备连接Device设备进行数据传输。开发示例 ...@@ -39,7 +39,7 @@ USB设备可作为Host设备连接Device设备进行数据传输。开发示例
1. 获取设备列表。 1. 获取设备列表。
```js ```js
// 导入usb接口api包。 // 导入USB接口api包。
import usb from '@ohos.usb'; import usb from '@ohos.usb';
// 获取设备列表。 // 获取设备列表。
var deviceList = usb.getDevices(); var deviceList = usb.getDevices();
......
...@@ -9,7 +9,7 @@ USB服务是应用访问底层的一种设备抽象概念。开发者根据提 ...@@ -9,7 +9,7 @@ USB服务是应用访问底层的一种设备抽象概念。开发者根据提
USB服务系统包含USB API、USB Service、USB HAL。 USB服务系统包含USB API、USB Service、USB HAL。
**图2** USB服务运作机制 **图1** USB服务运作机制
![zh-cn_image_0000001237821727](figures/zh-cn_image_0000001237821727.png) ![zh-cn_image_0000001237821727](figures/zh-cn_image_0000001237821727.png)
......
# Vibrator开发概述 # Vibrator开发概述
马达振动服务最大化开放硬工最新马达器件能力,通过拓展原生马达服务实现振动与交互融合设计,打造细腻精致的一体化振动体验和差异化体验,提升用户交互效率和易用性、提升用户体验、增强品牌竞争力。 振动器模块服务最大化开放硬工最新马达器件能力,通过拓展原生马达服务实现振动与交互融合设计,打造细腻精致的一体化振动体验和差异化体验,提升用户交互效率和易用性、提升用户体验、增强品牌竞争力。
## 运作机制 ## 运作机制
...@@ -23,7 +23,7 @@ Vibrator属于控制类小器件,主要包含以下四个模块:Vibrator API ...@@ -23,7 +23,7 @@ Vibrator属于控制类小器件,主要包含以下四个模块:Vibrator API
## 约束与限制 ## 约束与限制
在使用振动器时,开发者需要配置请求振动器的权限ohos.permission.VIBRATE,才能控制振动器振动,敏感级别是system_grant。 在使用振动器时,开发者需要配置请求振动器的权限ohos.permission.VIBRATE,才能控制振动器振动,权限类型是system_grant。
...@@ -191,6 +191,5 @@ export class AudioRecorderDemo { ...@@ -191,6 +191,5 @@ export class AudioRecorderDemo {
针对音频录制开发,有以下相关实例可供参考: 针对音频录制开发,有以下相关实例可供参考:
- [`Recorder:`录音机(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Recorder) - [`Recorder:`录音机(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Recorder)
- [`JsRecorder`:录音机(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) - [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) - [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -86,7 +86,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建 ...@@ -86,7 +86,7 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建
SkImageInfo imageInfo = ... SkImageInfo imageInfo = ...
bitmap.setInfo(imageInfo, bufferHandle->stride); bitmap.setInfo(imageInfo, bufferHandle->stride);
bitmap.setPixels(bufferHandle->virAddr); bitmap.setPixels(bufferHandle->virAddr);
//创建 Skia Canvas 并将内容写入naitve window //创建 Skia Canvas 并将内容写入native window
... ...
//写入完成后,通过OH_NativeWindwo_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上 //写入完成后,通过OH_NativeWindwo_NativeWindowFlushBuffer 提交给消费者使用,例如:显示在屏幕上
...@@ -101,7 +101,13 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建 ...@@ -101,7 +101,13 @@ NativeWindow是`OpenHarmony`**本地平台化窗口**,包括从`Surface`构建
OH_NativeXComponent_Callback &callback_; OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB; callback_->OnSurfaceCreated = OnSufaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB; callback_->OnSurfaceChanged = OnSufaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB; callback_->OnSurfaceDestroyed = OnSufaceDestroyedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB; callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_) OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
``` ```
## 相关实例
针对NativeWindow的使用,有以下相关实例可供参考:
- [使用NativeWindow接口获取Buffer](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/hello_native_window/hello_native_window.cpp)
\ No newline at end of file
# 开发参考 # 开发参考
- [组件参考(基于TS扩展的声明式开发范式)](arkui-ts/Readme-CN.md) - [组件参考(基于eTS的声明式开发范式)](arkui-ts/Readme-CN.md)
- [组件参考(基于JS扩展的类Web开发范式)](arkui-js/Readme-CN.md) - [组件参考(兼容JS的类Web开发范式)](arkui-js/Readme-CN.md)
- [JS服务卡片UI组件参考](js-service-widget-ui/Readme-CN.md) - [JS服务卡片UI组件参考](js-service-widget-ui/Readme-CN.md)
- [接口参考(JS及TS API)](apis/Readme-CN.md) - [接口参考(JS及TS API)](apis/Readme-CN.md)
- 接口参考(Native API) - 接口参考(Native API)
......
...@@ -13,17 +13,6 @@ import bluetooth from '@ohos.bluetooth'; ...@@ -13,17 +13,6 @@ import bluetooth from '@ohos.bluetooth';
``` ```
## 权限
ohos.permission.USE_BLUETOOTH
ohos.permission.MANAGE_BLUETOOTH
ohos.permission.DISCOVER_BLUETOOTH
ohos.permission.LOCATION
## bluetooth.enableBluetooth<sup>8+</sup><a name="enableBluetooth"></a> ## bluetooth.enableBluetooth<sup>8+</sup><a name="enableBluetooth"></a>
enableBluetooth(): boolean enableBluetooth(): boolean
...@@ -1962,7 +1951,7 @@ server端订阅特征值写请求事件。 ...@@ -1962,7 +1951,7 @@ server端订阅特征值写请求事件。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | -------------------------------------- | | -------- | ---------------------------------------- | ---- | -------------------------------------- |
| type | string | 是 | 填写"characteristicWrite"字符串,表示特征值写请求事件。 | | type | string | 是 | 填写"characteristicWrite"字符串,表示特征值写请求事件。 |
| callback | Callback&lt;[DescriptorWriteReq](#descriptorwritereq)&gt; | 是 | 表示回调函数的入参,client端发送的写请求数据。 | | callback | Callback&lt;[CharacteristicWriteReq](#characteristicwritereq)&gt; | 是 | 表示回调函数的入参,client端发送的写请求数据。 |
**返回值:** **返回值:**
......
...@@ -29,7 +29,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number, callback: As ...@@ -29,7 +29,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number, callback: As
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文。 <br>API version 9之前的Context定义见[Context](js-apis-Context.md)<br>API version 9及之后的Context定义见[Context](js-apis-ability-context.md)。| | context | [Context](js-apis-Context.md) | 是 | 应用上下文。|
| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 |
| version | number | 是 | 数据库版本。 | | version | number | 是 | 数据库版本。 |
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | 是 | 指定callback回调函数,返回一个RdbStore。 | | callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | 是 | 指定callback回调函数,返回一个RdbStore。 |
...@@ -37,8 +37,13 @@ getRdbStore(context: Context, config: StoreConfig, version: number, callback: As ...@@ -37,8 +37,13 @@ getRdbStore(context: Context, config: StoreConfig, version: number, callback: As
**示例:** **示例:**
```js ```js
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// 获取context后调用getRdbStore
const STORE_CONFIG = { name: "RdbTest.db"} const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
if (err) { if (err) {
console.info("Get RdbStore failed, err: " + err) console.info("Get RdbStore failed, err: " + err)
return return
...@@ -59,7 +64,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt; ...@@ -59,7 +64,7 @@ getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文。 <br>API version 9之前的Context定义见[Context](js-apis-Context.md)<br>API version 9及之后的Context定义见[Context](js-apis-ability-context.md)。 | | context | [Context](js-apis-Context.md) | 是 | 应用上下文。 |
| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 |
| version | number | 是 | 数据库版本。 | | version | number | 是 | 数据库版本。 |
...@@ -72,8 +77,13 @@ getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt; ...@@ -72,8 +77,13 @@ getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;
**示例:** **示例:**
```js ```js
// 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// 获取context后调用getRdbStore
const STORE_CONFIG = { name: "RdbTest.db" } const STORE_CONFIG = { name: "RdbTest.db" }
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
console.log("Get RdbStore successfully.") console.log("Get RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -92,13 +102,18 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&g ...@@ -92,13 +102,18 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&g
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文。 <br>API version 9之前的Context定义见[Context](js-apis-Context.md)<br>API version 9及之后的Context定义见[Context](js-apis-ability-context.md)。| | context | [Context](js-apis-Context.md) | 是 | 应用上下文。|
| name | string | 是 | 数据库名称。 | | name | string | 是 | 数据库名称。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**示例:** **示例:**
```js ```js
data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { // 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// 获取context后调用deleteRdbStore
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Delete RdbStore failed, err: " + err) console.info("Delete RdbStore failed, err: " + err)
return return
...@@ -118,7 +133,7 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt; ...@@ -118,7 +133,7 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
**参数** **参数**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文。 <br>API version 9之前的Context定义见[Context](js-apis-Context.md)<br>API version 9及之后的Context定义见[Context](js-apis-ability-context.md)。| | context | [Context](js-apis-Context.md) | 是 | 应用上下文。|
| name | string | 是 | 数据库名称。 | | name | string | 是 | 数据库名称。 |
**返回值** **返回值**
...@@ -128,7 +143,12 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt; ...@@ -128,7 +143,12 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
**示例:** **示例:**
```js ```js
let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") // 获取context
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// 获取context后调用deleteRdbStore
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Delete RdbStore successfully.") console.log("Delete RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
......
...@@ -53,7 +53,7 @@ var path; ...@@ -53,7 +53,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
let storage = data_storage.getStorageSync(path + '/mystore'); let storage = data_storage.getStorageSync(path + '/mystore');
storage.putSync('startup', 'auto'); storage.putSync('startup', 'auto');
...@@ -86,7 +86,7 @@ var path; ...@@ -86,7 +86,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
data_storage.getStorage(path + '/mystore', function (err, storage) { data_storage.getStorage(path + '/mystore', function (err, storage) {
if (err) { if (err) {
...@@ -129,7 +129,7 @@ var path; ...@@ -129,7 +129,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
let getPromise = data_storage.getStorage(path + '/mystore'); let getPromise = data_storage.getStorage(path + '/mystore');
getPromise.then((storage) => { getPromise.then((storage) => {
...@@ -165,7 +165,7 @@ var path; ...@@ -165,7 +165,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
data_storage.deleteStorageSync(path + '/mystore'); data_storage.deleteStorageSync(path + '/mystore');
}); });
...@@ -195,7 +195,7 @@ var path; ...@@ -195,7 +195,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
data_storage.deleteStorage(path + '/mystore', function (err) { data_storage.deleteStorage(path + '/mystore', function (err) {
if (err) { if (err) {
...@@ -237,7 +237,7 @@ var path; ...@@ -237,7 +237,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
let promisedelSt = data_storage.deleteStorage(path + '/mystore'); let promisedelSt = data_storage.deleteStorage(path + '/mystore');
promisedelSt.then(() => { promisedelSt.then(() => {
...@@ -271,7 +271,7 @@ var path; ...@@ -271,7 +271,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
data_storage.removeStorageFromCacheSync(path + '/mystore'); data_storage.removeStorageFromCacheSync(path + '/mystore');
}); });
...@@ -302,7 +302,7 @@ var path; ...@@ -302,7 +302,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
data_storage.removeStorageFromCache(path + '/mystore', function (err) { data_storage.removeStorageFromCache(path + '/mystore', function (err) {
if (err) { if (err) {
...@@ -344,7 +344,7 @@ var path; ...@@ -344,7 +344,7 @@ var path;
var context = featureAbility.getContext(); var context = featureAbility.getContext();
context.getFilesDir().then((filePath) => { context.getFilesDir().then((filePath) => {
path = filePath; path = filePath;
console.info("======================>getFilesDirPromsie====================>"); console.info("======================>getFilesDirPromise====================>");
let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore')
promiserevSt.then(() => { promiserevSt.then(() => {
......
...@@ -596,16 +596,15 @@ KVStore数据库类型枚举。 ...@@ -596,16 +596,15 @@ KVStore数据库类型枚举。
数据库的安全级别枚举。 数据库的安全级别枚举。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| --- | ---- | ----------------------- | | --- | ---- | ----------------------- |
| NO_LEVEL | 0 | 表示数据库不设置安全级别。 | | NO_LEVEL | 0 | 表示数据库不设置安全级别。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| S0 | 1 | 表示数据库的安全级别为公共级别。 | | S0 | 1 | 表示数据库的安全级别为公共级别。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S1 | 2 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | | S1 | 2 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S2 | 3 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | | S2 | 3 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S3 | 5 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | | S3 | 5 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S4 | 6 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | | S4 | 6 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
## Constants ## Constants
......
# 弹窗 # 弹窗
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明** 创建并显示文本提示框、对话框和操作菜单。
> **说明:**
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
``` ```js
import prompt from '@ohos.prompt' import prompt from '@ohos.prompt'
``` ```
## 权限列表
## prompt.showToast ## prompt.showToast
...@@ -21,32 +21,31 @@ showToast(options: ShowToastOptions): void ...@@ -21,32 +21,31 @@ showToast(options: ShowToastOptions): void
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------- | ---- | ------- | | ------- | ------------------------------------- | ---- | ------- |
| options | [ShowToastOptions](#showtoastoptions) | 是 | 文本弹窗选项。 | | options | [ShowToastOptions](#showtoastoptions) | 是 | 文本弹窗选项。 |
**示例:** **示例:**
```
export default { ```js
showToast() { prompt.showToast({
prompt.showToast({
message: 'Message Info', message: 'Message Info',
duration: 2000, duration: 2000,
}); });
} ```
}
```
## ShowToastOptions ## ShowToastOptions
文本提示框的选项。 文本提示框的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full。
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------------- | ---- | ---------------------------------------- | | -------- | --------------- | ---- | ---------------------------------------- |
| message | string | 是 | 显示的文本信息。 | | message | string | 是 | 显示的文本信息。 |
| duration | number | 否 | 默认值1500ms,建议区间:1500ms-10000ms,若小于1500ms则取默认值。 | | duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 |
| bottom | &lt;length&gt; | 否 | 设置弹窗边框距离屏幕底部的位置。 | | bottom | string\| number | 否 | 设置弹窗边框距离屏幕底部的位置。 |
## prompt.showDialog ## prompt.showDialog
...@@ -57,6 +56,7 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt; ...@@ -57,6 +56,7 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt;
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------ | | ------- | --------------------------------------- | ---- | ------ |
| options | [ShowDialogOptions](#showdialogoptions) | 是 | 对话框选项。 | | options | [ShowDialogOptions](#showdialogoptions) | 是 | 对话框选项。 |
...@@ -69,10 +69,8 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt; ...@@ -69,10 +69,8 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt;
**示例:** **示例:**
``` ```js
export default { prompt.showDialog({
showDialog() {
prompt.showDialog({
title: 'Title Info', title: 'Title Info',
message: 'Message Info', message: 'Message Info',
buttons: [ buttons: [
...@@ -85,16 +83,14 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt; ...@@ -85,16 +83,14 @@ showDialog(options: ShowDialogOptions): Promise&lt;ShowDialogSuccessResponse&gt;
color: '#000000', color: '#000000',
} }
], ],
}) })
.then(data => { .then(data => {
console.info('showDialog success, click button: ' + data.index); console.info('showDialog success, click button: ' + data.index);
}) })
.catch(err => { .catch(err => {
console.info('showDialog error: ' + err); console.info('showDialog error: ' + err);
}) })
} ```
}
```
## prompt.showDialog ## prompt.showDialog
...@@ -104,25 +100,17 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc ...@@ -104,25 +100,17 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------ | | -------- | ---------------------------------------- | ---- | ------------ |
| options | [ShowDialogOptions](#showdialogoptions) | 是 | 页面显示对话框信息描述。 | | options | [ShowDialogOptions](#showdialogoptions) | 是 | 页面显示对话框信息描述。 |
| callback | AsyncCallback&lt;[ShowDialogSuccessResponse](#showdialogsuccessresponse)&gt; | 是 | 对话框响应结果回调。 | | callback | AsyncCallback&lt;[ShowDialogSuccessResponse](#showdialogsuccessresponse)&gt; | 是 | 对话框响应结果回调。 |
**示例:** **示例:**
```
export default { ```js
callback(err, data) { prompt.showDialog({
if(err) {
console.info('showDialog err: ' + err);
return;
}
console.info('showDialog success callback, click button: ' + data.index);
},
showDialog() {
prompt.showDialog({
title: 'showDialog Title Info', title: 'showDialog Title Info',
message: 'Message Info', message: 'Message Info',
buttons: [ buttons: [
...@@ -135,19 +123,23 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc ...@@ -135,19 +123,23 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc
color: '#000000', color: '#000000',
} }
] ]
}, this.callback); }, (err, data) => {
} if (err) {
console.info('showDialog err: ' + err);
return;
} }
``` console.info('showDialog success callback, click button: ' + data.index);
});
```
## ShowDialogOptions ## ShowDialogOptions
对话框的选项。 对话框的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ---------------------------------------- | | ------- | ------- | ---- | ---------------------------------------- |
| title | string | 否 | 标题文本。 | | title | string | 否 | 标题文本。 |
| message | string | 否 | 内容文本。 | | message | string | 否 | 内容文本。 |
| buttons | Array | 否 | 对话框中按钮的数组,结构为:{text:'button',&nbsp;color:&nbsp;'\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 | | buttons | Array | 否 | 对话框中按钮的数组,结构为:{text:'button',&nbsp;color:&nbsp;'\#666666'},支持1-3个按钮。其中第一个为positiveButton;第二个为negativeButton;第三个为neutralButton。 |
...@@ -156,7 +148,7 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc ...@@ -156,7 +148,7 @@ showDialog(options: ShowDialogOptions, callback: AsyncCallback&lt;ShowDialogSucc
对话框的响应结果。 对话框的响应结果。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 名称 | 类型 | 说明 | | 名称 | 类型 | 说明 |
| ----- | ------ | ------------------- | | ----- | ------ | ------------------- |
...@@ -172,6 +164,7 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu ...@@ -172,6 +164,7 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------- | | -------- | ---------------------------------------- | ---- | --------- |
| options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 | | options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 |
...@@ -179,17 +172,9 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu ...@@ -179,17 +172,9 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu
**示例:** **示例:**
```
export default { ```js
callback(err, data) { prompt.showActionMenu({
if(err) {
console.info('showActionMenu err: ' + err);
return;
}
console.info('showActionMenu success callback, click button: ' + data.index);
},
showActionMenu() {
prompt.showActionMenu({
title: 'Title Info', title: 'Title Info',
buttons: [ buttons: [
{ {
...@@ -201,34 +186,39 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu ...@@ -201,34 +186,39 @@ showActionMenu(options: ActionMenuOptions, callback: AsyncCallback&lt;ActionMenu
color: '#000000', color: '#000000',
}, },
] ]
}, this.callback) }, (err, data) => {
} if (err) {
console.info('showActionMenu err: ' + err);
return;
} }
``` console.info('showActionMenu success callback, click button: ' + data.index);
})
```
## prompt.showActionMenu ## prompt.showActionMenu
showActionMenu(options: ActionMenuOptions): Promise\<ActionMenuSuccessResponse> showActionMenu(options: ActionMenuOptions): Promise&lt;ActionMenuSuccessResponse&gt;
创建并显示操作菜单,菜单响应后同步返回结果。 创建并显示操作菜单,菜单响应后同步返回结果。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full **系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | ------- | | ------- | --------------------------------------- | ---- | ------- |
| options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 | | options | [ActionMenuOptions](#actionmenuoptions) | 是 | 操作菜单选项。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ---------------------------------------- | ------- | | ---------------------------------------- | ------- |
| Promise&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)&gt; | 菜单响应结果。 | | Promise&lt;[ActionMenuSuccessResponse](#actionmenusuccessresponse)&gt; | 菜单响应结果。 |
**示例:** **示例:**
```
export default { ```js
showActionMenu() { prompt.showActionMenu({
prompt.showActionMenu({
title: 'showActionMenu Title Info', title: 'showActionMenu Title Info',
buttons: [ buttons: [
{ {
...@@ -240,34 +230,42 @@ showActionMenu(options: ActionMenuOptions): Promise\<ActionMenuSuccessResponse> ...@@ -240,34 +230,42 @@ showActionMenu(options: ActionMenuOptions): Promise\<ActionMenuSuccessResponse>
color: '#000000', color: '#000000',
}, },
] ]
}) })
.then(data => { .then(data => {
console.info('showActionMenu success, click button: ' + data.index); console.info('showActionMenu success, click button: ' + data.index);
}) })
.catch(err => { .catch(err => {
console.info('showActionMenu error: ' + err); console.info('showActionMenu error: ' + err);
}) })
} ```
}
```
## ActionMenuOptions ## ActionMenuOptions
操作菜单的选项。 操作菜单的选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full。
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ---------------------------------------- | | ------- | ------------------------------ | ---- | ---------------------------------------- |
| title | string | 否 | 标题文本。 | | title | string | 否 | 标题文本。 |
| buttons | Array | 是 | 菜单中菜单项按钮的数组,结构为:{text:'button',&nbsp;color:&nbsp;'\#666666'},支持1-6个按钮。大于6个按钮时弹窗不显示。 | | buttons | Array&lt;[Button](#button)&gt; | 是 | 菜单中菜单项按钮的数组,结构为:{text:'button',&nbsp;color:&nbsp;'\#666666'},支持1-6个按钮。大于6个按钮时弹窗不显示。 |
## ActionMenuSuccessResponse ## ActionMenuSuccessResponse
操作菜单的响应结果。 操作菜单的响应结果。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.ArkUI.ArkUI.Full。 **系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----- | ------ | ---- | ------------------------ | | ----- | ------ | ---- | ------------------------ |
| index | number | 否 | 选中按钮在buttons数组中的索引,从0开始。 | | index | number | 否 | 选中按钮在buttons数组中的索引,从0开始。 |
## Button
菜单中的菜单项按钮。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 名称 | 类型 | 必填 | 说明 |
| ----- | ------ | ---- | ------- |
| text | string | 是 | 按钮文本内容。 |
| color | string | 是 | 按钮文本颜色。 |
...@@ -276,7 +276,7 @@ isLastWorkTimeOut(workId: number): Promise\<boolean> ...@@ -276,7 +276,7 @@ isLastWorkTimeOut(workId: number): Promise\<boolean>
``` ```
## WorkInfo ## WorkInfo
提供工作的具体信息。 提供工作的具体信息。WorkInfo设置参数约束见[延迟任务调度概述](../../task-management/work-scheduler-overview.md)
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.WorkScheduler
......
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册