提交 6e306372 编写于 作者: 关明月 提交者: Gitee

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

Signed-off-by: N关明月 <guanmingyue@huawei.com>
...@@ -2,19 +2,19 @@ ...@@ -2,19 +2,19 @@
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.
| Item | FA Model | Stage Model | | Item | FA Model | Stage Model |
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- | | -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. | | Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. | | 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.
- **RDB** ## Basic concepts
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. - **RDB**
- **Predicate** 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.
A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. - **Predicate**
- **Result set** A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions.
A set of query results used to access the data. You can access the required data in a result set in flexible modes. - **Result set**
- **SQLite database** A set of query results used to access data. You can access the required data in a result set in flexible modes.
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability \(ACID\). - **SQLite database**
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability (ACID).
## Working Principles<a name="section4810552814"></a> ## Working Principles
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. 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.
**Figure 1** How RDB works<a name="fig1826214361535"></a> **Figure 1** How RDB works
![](figures/how-rdb-works.png "how-rdb-works")
## Default Settings<a name="section176091243121218"></a> ![how-rdb-works](figures/how-rdb-works.png)
- The default database logging mode is write-ahead logging \(WAL\). ## Default Settings
- The default database flush mode is Full mode.
- The default shared memory used by the OpenHarmony database is 2 MB.
## Constraints<a name="section929813398308"></a> - The default RDB logging mode is Write Ahead Log (WAL).
- The default data flushing mode is **FULL** mode.
- The default size of the shared memory used by an OpenHarmony database is 2 MB.
- A maximum of four connection pools can be connected to an RDB to manage read and write operations. ## Constraints
- To ensure data accuracy, the RDB supports only one write operation at a time. - 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.
# 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.
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. ## Basic Concepts
- **Non-relational database** - **Key-value structure**
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 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**
## Working Principles<a name="section682631371115"></a> 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.
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. ## Working Principles
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> 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.
**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.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters.
- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters.
- **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 bytes.
- 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.
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **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.
The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
## Modules to Import ## Modules to Import
...@@ -12,18 +12,6 @@ The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low E ...@@ -12,18 +12,6 @@ The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low E
import bluetooth from '@ohos.bluetooth'; import bluetooth from '@ohos.bluetooth';
``` ```
## Required Permissions
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
...@@ -320,7 +308,7 @@ let remoteDeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX"); ...@@ -320,7 +308,7 @@ let remoteDeviceClass = bluetooth.getRemoteDeviceClass("XX:XX:XX:XX:XX:XX");
getPairedDevices(): Array&lt;string&gt; getPairedDevices(): Array&lt;string&gt;
Obtains the Bluetooth pairing list. Obtains the paired devices.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -330,7 +318,7 @@ Obtains the Bluetooth pairing list. ...@@ -330,7 +318,7 @@ Obtains the Bluetooth pairing list.
| Type | Description | | Type | Description |
| ------------------- | ------------- | | ------------------- | ------------- |
| Array&lt;string&gt; | List of the addresses of the paired Bluetooth devices.| | Array&lt;string&gt; | Addresses of the paired Bluetooth devices.|
**Example** **Example**
...@@ -354,7 +342,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de ...@@ -354,7 +342,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------- | ---- | ---------------------------- | | -------- | --------------------- | ---- | ---------------------------- |
| mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode to set. | | mode | [ScanMode](#scanmode) | Yes | Bluetooth scan mode to set. |
| duration | number | Yes | Duration (in seconds) in which the device can be discovered. The value **0** indicates unlimited time.| | duration | number | Yes | Duration (in ms) in which the device can be discovered. The value **0** indicates unlimited time.|
**Return value** **Return value**
...@@ -609,7 +597,7 @@ bluetooth.off('pinRequired', onReceiveEvent); ...@@ -609,7 +597,7 @@ bluetooth.off('pinRequired', onReceiveEvent);
on(type: "bondStateChange", callback: Callback&lt;BondStateParam&gt;): void on(type: "bondStateChange", callback: Callback&lt;BondStateParam&gt;): void
Subscribes to the Bluetooth pairing state change events. Subscribes to the Bluetooth bond state change events.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -619,8 +607,8 @@ Subscribes to the Bluetooth pairing state change events. ...@@ -619,8 +607,8 @@ Subscribes to the Bluetooth pairing state change events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------ | | -------- | ---------------------------------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event.| | type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth bond state change event.|
| callback | Callback&lt;[BondStateParam](#bondstate)&gt; | Yes | Callback invoked to return the pairing state. You need to implement this callback. | | callback | Callback&lt;[BondStateParam](#bondstateparam8)&gt; | Yes | Callback invoked to return the bond state. You need to implement this callback. |
**Return value** **Return value**
...@@ -629,7 +617,7 @@ No value is returned. ...@@ -629,7 +617,7 @@ No value is returned.
**Example** **Example**
```js ```js
function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the pairing state. function onReceiveEvent(data) { // data, as the input parameter of the callback, indicates the bond state.
console.info('pair state = '+ JSON.stringify(data)); console.info('pair state = '+ JSON.stringify(data));
} }
bluetooth.on('bondStateChange', onReceiveEvent); bluetooth.on('bondStateChange', onReceiveEvent);
...@@ -640,7 +628,7 @@ bluetooth.on('bondStateChange', onReceiveEvent); ...@@ -640,7 +628,7 @@ bluetooth.on('bondStateChange', onReceiveEvent);
off(type: "bondStateChange", callback?: Callback&lt;BondStateParam&gt;): void off(type: "bondStateChange", callback?: Callback&lt;BondStateParam&gt;): void
Unsubscribes from the Bluetooth pairing state change events. Unsubscribes from the Bluetooth bond state change events.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -650,8 +638,8 @@ Unsubscribes from the Bluetooth pairing state change events. ...@@ -650,8 +638,8 @@ Unsubscribes from the Bluetooth pairing state change events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth pairing state change event. | | type | string | Yes | Event type. The value **bondStateChange** indicates a Bluetooth bond state change event. |
| callback | Callback&lt;[BondStateParam](#bondstate)&gt; | No | Callback used to report the change of the Bluetooth pairing state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| | callback | Callback&lt;[BondStateParam](#bondstateparam8)&gt; | No | Callback used to report the change of the Bluetooth bond state. If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.|
**Return value** **Return value**
...@@ -1295,7 +1283,7 @@ Obtains the connection state of the profile. ...@@ -1295,7 +1283,7 @@ Obtains the connection state of the profile.
| | | | | |
| ------------------------------------------------- | ----------------------- | | ------------------------------------------------- | ----------------------- |
| Type | Description | | Type | Description |
| [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. | | [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained. |
## A2dpSourceProfile ## A2dpSourceProfile
...@@ -1894,7 +1882,7 @@ Subscribes to the characteristic read request events. ...@@ -1894,7 +1882,7 @@ Subscribes to the characteristic read request events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------------- | | -------- | ---------------------------------------- | ---- | ------------------------------------- |
| type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event.| | type | string | Yes | Event type. The value **characteristicRead** indicates a characteristic read request event.|
| callback | Callback&lt;[CharacteristicReadReq](#characteristicreadreq)&gt; | Yes | Callback invoked to return a characteristic read request from the GATT client. | | callback | Callback&lt;[CharacteristicReadReq](#characteristicreadreq)&gt; | Yes | Callback invoked to return a characteristic read request event from the GATT client. |
**Return value** **Return value**
...@@ -1971,7 +1959,7 @@ Subscribes to the characteristic write request events. ...@@ -1971,7 +1959,7 @@ Subscribes to the characteristic write request events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------------------- | | -------- | ---------------------------------------- | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.| | type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.|
| callback | Callback&lt;[CharacteristicWriteReq](#descriptorwritereq)&gt; | Yes | Callback invoked to return a characteristic write request from the GATT client. | | callback | Callback&lt;[CharacteristicWriteReq](#characteristicwritereq)&gt; | Yes | Callback invoked to return a characteristic write request from the GATT client. |
**Return value** **Return value**
...@@ -2192,6 +2180,7 @@ let gattServer = bluetooth.BLE.createGattServer(); ...@@ -2192,6 +2180,7 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite"); gattServer.off("descriptorWrite");
``` ```
### on('connectStateChange') ### on('connectStateChange')
on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void
...@@ -2410,7 +2399,7 @@ device.getServices().then(result => { ...@@ -2410,7 +2399,7 @@ device.getServices().then(result => {
readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void
Reads the characteristic value of the specific service of the peer BLE device. This API uses an asynchronous callback to return the result. Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2511,7 +2500,7 @@ device.readCharacteristicValue(characteristic); ...@@ -2511,7 +2500,7 @@ device.readCharacteristicValue(characteristic);
readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void
Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses an asynchronous callback to return the result. Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2683,7 +2672,7 @@ if (retWriteDesc) { ...@@ -2683,7 +2672,7 @@ if (retWriteDesc) {
setBLEMtuSize(mtu: number): boolean setBLEMtuSize(mtu: number): boolean
Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This method can be used only after a connection is set up by calling [connect](#connect). Sets the maximum transmission unit (MTU) that can be transmitted between the GATT client and its remote BLE device. This API can be used only after a connection is set up by calling [connect](#connect).
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -3355,6 +3344,18 @@ Defines the pairing request parameters. ...@@ -3355,6 +3344,18 @@ Defines the pairing request parameters.
| pinCode | string | Yes | No | Key for the device pairing. | | pinCode | string | Yes | No | Key for the device pairing. |
## BondStateParam<sup>8+</sup><a name="BondStateParam"></a>
Defines the bond state parameters.
**System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Type | Readable | Writable | Description |
| -------- | ------ | ---- | ---- | ----------- |
| deviceId | string | Yes | No | ID of the device.|
| state | BondState | Yes | No | State of the device.|
## StateChangeParam<sup>8+</sup><a name="StateChangeParam"></a> ## StateChangeParam<sup>8+</sup><a name="StateChangeParam"></a>
Defines the profile state change parameters. Defines the profile state change parameters.
...@@ -3512,7 +3513,7 @@ Enumerates the A2DP playing states. ...@@ -3512,7 +3513,7 @@ Enumerates the A2DP playing states.
## ProfileId<sup>8+</sup><a name="ProfileId"></a> ## ProfileId<sup>8+</sup><a name="ProfileId"></a>
Enumerates the Bluetooth profile IDs. Enumerates the Bluetooth profiles.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
......
# 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;
......
# 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;
if (err.code) { display.getDefaultDisplay((err, data) => {
console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); if (err.code) {
return; console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err));
} return;
console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); }
displayClass = data; console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(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) => {
console.info('Listening enabled. Data: ' + JSON.stringify(data))
}
display.on("add", callback);
```
```js
var callback = (data) => {
console.info('Listening enabled. Data: ' + JSON.stringify(data))
}
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,10 +138,10 @@ Starts an ability. This API uses a callback to return the execution result when ...@@ -138,10 +138,10 @@ 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(
{ {
want: want:
{ {
action: "action.system.home", action: "action.system.home",
...@@ -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)
} }
......
...@@ -3057,7 +3057,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3057,7 +3057,7 @@ Notification.subscribe(subscriber, subscribeCallback);
| desc | Yes | Yes | string | No | Notification slot description. | | desc | Yes | Yes | string | No | Notification slot description. |
| badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. | | badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. |
| bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. | | bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. |
| lockscreenVisibility | Yes | Yes | boolean | No | Mode for displaying the notification on the lock screen. | | lockscreenVisibility | Yes | Yes | number | No | Mode for displaying the notification on the lock screen. |
| vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | | vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. |
| sound | Yes | Yes | string | No | Notification alert tone. | | sound | Yes | Yes | string | No | Notification alert tone. |
| lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | | lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. |
......
# 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**
...@@ -52,4 +45,11 @@ export default { ...@@ -52,4 +45,11 @@ export default {
}); });
}, },
} }
``` ```
\ No newline at end of file
## 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,34 +24,35 @@ Obtains the current screen brightness. ...@@ -24,34 +24,35 @@ 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){
console.log('success get brightness value:' + data.value); console.log('success get brightness value:' + data.value);
}, },
fail: function(data, code) { fail: function(data, code) {
console.log('get brightness fail, code: ' + code + ', data: ' + data); console.log('get brightness fail, code: ' + code + ', data: ' + data);
}, },
}); });
}, },
} }
``` ```
## brightness.setValue ## brightness.setValue
...@@ -64,30 +65,30 @@ Sets the screen brightness. ...@@ -64,30 +65,30 @@ 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,
success: function(){ success: function(){
console.log('handling set brightness success.'); console.log('handling set brightness success.');
}, },
fail: function(data, code){ fail: function(data, code){
console.log('handling set brightness value fail, code:' + code + ', data: ' + data); console.log('handling set brightness value fail, code:' + code + ', data: ' + data);
}, },
}); });
}, },
} }
``` ```
## brightness.getMode ## brightness.getMode
...@@ -100,34 +101,34 @@ Obtains the screen brightness adjustment mode. ...@@ -100,34 +101,34 @@ 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){
console.log('success get mode:' + data.mode); console.log('success get mode:' + data.mode);
}, },
fail: function(data, code){ fail: function(data, code){
console.log('handling get mode fail, code:' + code + ', data: ' + data); console.log('handling get mode fail, code:' + code + ', data: ' + data);
}, },
}); });
}, },
} }
``` ```
## brightness.setMode ## brightness.setMode
...@@ -139,31 +140,30 @@ Sets the screen brightness adjustment mode. ...@@ -139,31 +140,30 @@ 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,
success: function(){ success: function(){
console.log('handling set mode success.'); console.log('handling set mode success.');
}, },
fail: function(data, code){ fail: function(data, code){
console.log('handling set mode fail, code:' + code + ', data: ' + data); console.log('handling set mode fail, code:' + code + ', data: ' + data);
}, },
}); });
}, },
} }
``` ```
## brightness.setKeepScreenOn ## brightness.setKeepScreenOn
...@@ -175,28 +175,40 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. ...@@ -175,28 +175,40 @@ 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,
success: function () { success: function () {
console.log('handling set keep screen on success.') console.log('handling set keep screen on success.')
}, },
fail: function (data, code) { fail: function (data, code) {
console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); console.log('handling set keep screen on fail, code:' + code + ', data: ' + data);
}, },
}); });
}, },
} }
``` ```
\ 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
# WLAN # WLAN
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The APIs described in this document are used only for non-universal products, such as routers. The APIs described in this document are used only for non-universal products, such as routers.
The APIs of this module are not supported by OpenHarmony 3.1 Release.
## Modules to Import ## Modules to Import
...@@ -17,13 +18,13 @@ enableHotspot(): boolean; ...@@ -17,13 +18,13 @@ enableHotspot(): boolean;
Enables the WLAN hotspot. Enables the WLAN hotspot.
- Required permissions: - **Required permissions**:
ohos.permission.MANAGE_WIFI_HOTSPOT_EXT ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Return value - **Return value**:
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
...@@ -35,13 +36,13 @@ disableHotspot(): boolean; ...@@ -35,13 +36,13 @@ disableHotspot(): boolean;
Disables the WLAN hotspot. Disables the WLAN hotspot.
- Required permissions: - **Required permissions**:
ohos.permission.MANAGE_WIFI_HOTSPOT_EXT ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Return value - **Return value**:
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
...@@ -51,15 +52,15 @@ Disables the WLAN hotspot. ...@@ -51,15 +52,15 @@ Disables the WLAN hotspot.
getSupportedPowerModel(): Promise&lt;Array&lt;PowerModel&gt;&gt; getSupportedPowerModel(): Promise&lt;Array&lt;PowerModel&gt;&gt;
Obtains the supported power models. The method uses a promise to return the result. Obtains the supported power models. The API uses a promise to return the result.
- Required permissions: - **Required permissions**:
ohos.permission.GET_WIFI_INFO ohos.permission.GET_WIFI_INFO
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Return value - **Return value**:
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#PowerModel)&gt;&gt; | Promise used to return the power models obtained.| | Promise&lt;Array&lt;[PowerModel](#PowerModel)&gt;&gt; | Promise used to return the power models obtained.|
...@@ -67,7 +68,7 @@ Obtains the supported power models. The method uses a promise to return the resu ...@@ -67,7 +68,7 @@ Obtains the supported power models. The method uses a promise to return the resu
## PowerModel ## PowerModel
Enumerates of the power models. Enumerates the power models.
| Name| Default Value| Description| | Name| Default Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -80,33 +81,33 @@ Enumerates of the power models. ...@@ -80,33 +81,33 @@ Enumerates of the power models.
getSupportedPowerModel(callback: AsyncCallback&lt;Array&lt;PowerModel&gt;&gt;): void getSupportedPowerModel(callback: AsyncCallback&lt;Array&lt;PowerModel&gt;&gt;): void
Obtains the supported power models. The method uses an asynchronous callback to return the result. Obtains the supported power models. The API uses an asynchronous callback to return the result.
- Required permissions: - **Required permissions**:
ohos.permission.GET_WIFI_INFO ohos.permission.GET_WIFI_INFO
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Parameters - **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Callback used to return the power models obtained.| | callback | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Callback invoked to return the power models obtained.|
## wifiext.getPowerModel ## wifiext.getPowerModel
getPowerModel(): Promise&lt;PowerModel&gt; getPowerModel(): Promise&lt;PowerModel&gt;
Obtains the power model. The method uses a promise to return the result. Obtains the power model. The API uses a promise to return the result.
- Required permissions: - **Required permissions**:
ohos.permission.GET_WIFI_INFO ohos.permission.GET_WIFI_INFO
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Return value - **Return value**:
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[PowerModel](#PowerModel)&gt; | Promise used to return the power model obtained.| | Promise&lt;[PowerModel](#PowerModel)&gt; | Promise used to return the power model obtained.|
...@@ -116,15 +117,15 @@ Obtains the power model. The method uses a promise to return the result. ...@@ -116,15 +117,15 @@ Obtains the power model. The method uses a promise to return the result.
getPowerModel(callback: AsyncCallback&lt;PowerModel&gt;): void getPowerModel(callback: AsyncCallback&lt;PowerModel&gt;): void
Obtains the power model. The method uses an asynchronous callback to return the result. Obtains the power model. The API uses an asynchronous callback to return the result.
- Required permissions: - **Required permissions**:
ohos.permission.GET_WIFI_INFO ohos.permission.GET_WIFI_INFO
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Parameters - **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Callback invoked to return the power mode obtained.| | callback | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Callback invoked to return the power mode obtained.|
...@@ -136,18 +137,18 @@ setPowerModel(model: PowerModel) : boolean; ...@@ -136,18 +137,18 @@ setPowerModel(model: PowerModel) : boolean;
Sets the power model. Sets the power model.
- Required permissions: - **Required permissions**:
ohos.permission.MANAGE_WIFI_HOTSPOT_EXT ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
- System capability: - **System capability**:
SystemCapability.Communication.WiFi.AP.Extension SystemCapability.Communication.WiFi.AP.Extension
- Parameters - **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| model | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Power model to set.| | model | AsyncCallback&lt;[PowerModel](#PowerModel)&gt; | Yes| Power model to set.|
- Return value - **Return value**:
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
...@@ -35,33 +35,27 @@ Obtains an image from the specified source for subsequent rendering and display. ...@@ -35,33 +35,27 @@ Obtains an image from the specified source for subsequent rendering and display.
**Parameters** **Parameters**
| Name| Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| ------ | ------------------------------------------------------------ | ---- | ------ | ------------------------------------------------------------ | | ---- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](../../ui/ts-types.md) | Yes | - | Image source. Both local and online images are supported.<br>When using resources referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>\- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. | | src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](/ts-types.md#resource-type) | Yes | - | Image source. Both local and online images are supported.<br>When using resources referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- | | --------------------- | ------------------------------------------------------- | ------------------------ | ------------------------------------------------------------ |
| alt | string \| [Resource](../../ui/ts-types.md) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. | | alt | string \| [Resource](ts-types.md#resource-type) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | ImageFit | Cover | Image scale type. | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| interpolation | ImageInterpolation | None | Interpolation effect of the image. This attribute is valid only when the image is zoomed in.<br>**NOTE**<br>This attribute is not applicable to SVG images or **PixelMap** objects. | | interpolation | ImageInterpolation | None | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>**NOTE**<br>> This attribute is not applicable to SVG images.<br>> This attribute is not applicable to **PixelMap** objects. |
| renderMode | ImageRenderMode | Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. | | renderMode | ImageRenderMode | Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| sourceSize | {<br>width: number,<br>height: number<br>} | - | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. | | sourceSize | {<br>width: number,<br>height: number<br>} | - | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. |
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. | | matchTextDirection | boolean | false | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.|
| fitOriginalSize | boolean | true | Whether to fit the component to the original size of the image source when the component size is not set.|
## ImageFit | fillColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Fill color. This parameter is valid only for SVG images. Once set, the fill color will replace that of the SVG image.|
| autoResize | boolean | true | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.|
| Name | Description | | syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
| --------- | -------------------------------- |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. |
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. |
| Fill | The image is scaled to fill the display area, and its aspect ratio is not retained. |
| None | The image is displayed in its original size. Generally, this enum is used together with the **objectRepeat** attribute.|
| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. |
## ImageInterpolation ## ImageInterpolation
...@@ -82,11 +76,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -82,11 +76,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Events ## Events
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>| | onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>| | onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels. |
| onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.| | onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. |
## Example ## Example
...@@ -179,12 +173,12 @@ struct ImageExample2 { ...@@ -179,12 +173,12 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed) .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) .overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
} }
Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30) Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Image('') Image('')
.alt($r('app.media.Image_none')) .alt($r('app.media.Image_none'))
.width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed) .width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%') Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%')
Row({ space: 50 }) { Row({ space: 50 }) {
Image($r('app.media.img_example')) Image($r('app.media.img_example'))
...@@ -204,7 +198,7 @@ struct ImageExample2 { ...@@ -204,7 +198,7 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed) .border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } }) .overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
} }
Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30) Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Row({ space: 5 }) { Row({ space: 5 }) {
Image($r('app.media.ic_health_heart')) Image($r('app.media.ic_health_heart'))
......
# RichText # RichText
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<RichText>** component parses and displays HTML text. The **\<RichText>** component parses and displays HTML text.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
None None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
RichText\(content:string\) RichText(content:string)
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description| | Name| Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| content | string | Yes| - | String in HTML format.| | content | string | Yes| - | Text string in HTML format. |
## Events ## Events
| Name| Description| | Name | Description|
| -------- | -------- | | -------- | -------- |
| onStart() => void | Triggered when web page loading starts.| | onStart(callback: () => void) => void | Triggered when web page loading starts. |
| onComplete() => void | Triggered when web page loading is completed.| | onComplete(callback: () => void) => void | Triggered when web page loading is completed. |
## Supported Tags ## Supported Tags
| Name| Description| Example| | Name | Description | Example |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| \<h1>--\<h6> | Defines six levels of headings in the HTML document. \<h1> defines the most important heading, and \<h6> defines the least important heading.| \<h1>This is an H1 heading\</h1> \<h2>This is an H2 heading\</h2>| | \<h1>--\<h6> | Defines six levels of headings in the HTML document. \<h1> defines the most important heading, and \<h6> defines the least important heading. | \<h1>This is an H1 heading\</h1> \<h2>This is an H2 heading\</h2> |
| \<p>\</p> | Defines a paragraph.| \<p>This is a paragraph\</p>| | \<p>\</p> | Defines a paragraph. | \<p>This is a paragraph\</p> |
| \<br/> | Inserts a newline character.| \<p>This is a paragraph\<br/>This is a new paragraph\</p>| | \<br/> | Inserts a newline character. | \<p>This is a paragraph\<br/>This is a new paragraph\</p>|
| \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> | | \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line. | \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> |
| \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> | | \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time. | \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> |
| \<i>\</i> | Displays text in italic style.| \<i>This is in italic style\</i> | | \<i>\</i> | Displays text in italic style. | \<i>This is in italic style\</i> |
| \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink.| \<p>\<u>This is an underlined paragraph\<u>\<p> | | \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink. | \<p>\<u>This is an underlined paragraph\<u>\<p> |
| \<style>\</style> | Used to embed CSS within an HTML document.| \<style>h1{color:red;}p{color:blue;}\</style> | | \<style>\</style> | Used to embed CSS within an HTML document. | \<style>h1{color:red;}p{color:blue;}\</style> |
| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> | | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**. | \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> |
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> | | \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript. | \<script>document.write("Hello World!")\</script> |
## 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 RichTextExample { struct RichTextExample {
......
# 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)
# XComponent # XComponent
> **NOTE**<br> > **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 **\<XComponent>** can accept and display the EGL/OpenGLES and media data input. The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data input.
## Required Permissions ## Required Permissions
...@@ -15,24 +16,36 @@ ...@@ -15,24 +16,36 @@
## APIs ## APIs
XComponent\(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}\) XComponent\(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}\)
- Name **Parameters**
| Name | Type | Mandatory | Description |
| ----------- | --------------------------------------- | --------- | ------------------------------------------------------------ |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. |
| type | string | Yes | Type of the component. The options are as follows:<br>- **surface**: The content of this component is displayed individually, without being combined with that of other components.<br>- **component**: The content of this component is displayed after having been combined with that of other components. |
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. |
| controller | [XComponentController](#XComponentController) | No | Controller bound to the component, which can be used to invoke methods of the component. |
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.|
| type | string | Yes | Type of the component. The options are as follows:<br>- **surface**: The content of this component is displayed individually, without being combined with that of other components.<br>- **component**: The content of this component is displayed after having been combined with that of other components.|
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer.|
| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component.|
## Events ## Events
| Name | Description | ### onLoad
| ------------------------------- | ------------------------ |
| onLoad(context?: object) => void | Triggered when the plug-in is loaded. | onLoad(callback: (event?: object) => void )
| onDestroy() => void | Triggered when the plug-in is destroyed. |
Triggered when the plug-in is loaded.
**Parameters**
| Name | Type | Mandatory | Description |
| ------------- | ------ | ---- | ----------------------- |
| event | object | No | Context of the **\<XComponent>** object. The APIs contained in the context are defined at the C++ layer by developers.|
### onDestroy
onDestroy(event: () => void )
Triggered when the plug-in is destroyed.
## XComponentController ## XComponentController
...@@ -50,11 +63,13 @@ getXComponentSurfaceId(): string ...@@ -50,11 +63,13 @@ getXComponentSurfaceId(): string
Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces, such as camera-related interfaces. Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces, such as camera-related interfaces.
- Return value **System API**: This is a system API.
**Return value**
| Type | Description | | Type | Description |
| ------ | --------------------------- | | ------ | ----------------------- |
| string | ID of the surface held by the **\<XComponent>**. | | string | ID of the surface held by the **\<XComponent>**.|
### setXComponentSurfaceSize ### setXComponentSurfaceSize
...@@ -62,12 +77,14 @@ setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): ...@@ -62,12 +77,14 @@ setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}):
Sets the width and height of the surface held by the **\<XComponent>**. Sets the width and height of the surface held by the **\<XComponent>**.
- Parameters **System API**: This is a system API.
| Name | Type | Mandatory | Default Value | Description | **Parameters**
| ------------- | -------- | ---- | ------ | ----------------------------- |
| surfaceWidth | number | Yes | - | Width of the surface held by the **\<XComponent>**. | | Name | Type | Mandatory | Description |
| surfaceHeight | number | Yes | - | Height of the surface held by the **\<XComponent>**. | | ------------- | ------ | ---- | ----------------------- |
| surfaceWidth | number | Yes | Width of the surface held by the **\<XComponent>**.|
| surfaceHeight | number | Yes | Height of the surface held by the **\<XComponent>**.|
### getXComponentContext ### getXComponentContext
...@@ -75,16 +92,18 @@ getXComponentContext(): Object ...@@ -75,16 +92,18 @@ getXComponentContext(): Object
Obtains the context of an **\<XComponent>** object. Obtains the context of an **\<XComponent>** object.
- Return value **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------------------------------------------ | | ------ | ---------------------------------------- |
| Object | Context of an **\<XComponent>** object. The APIs contained in the context are defined by developers. | | Object | Context of the **\<XComponent>** object. The APIs contained in the context are defined by developers.|
## Example ## Example
Provide a surface-type **\<XComponent>** to support capabilities such as camera preview. Provide a surface-type **\<XComponent>** to support capabilities such as camera preview.
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts ```ts
// xxx.ets // xxx.ets
import camera from '@ohos.multimedia.camera'; import camera from '@ohos.multimedia.camera';
......
...@@ -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.
......
...@@ -4,8 +4,7 @@ ...@@ -4,8 +4,7 @@
> **NOTE** > **NOTE**
> >
> - The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> - The APIs provided by this module are system APIs.
## Required Permissions ## Required Permissions
...@@ -27,7 +26,7 @@ None ...@@ -27,7 +26,7 @@ None
getInspectorByKey(id: string): string getInspectorByKey(id: string): string
Obtains all attributes of the component with the specified ID, excluding the information about child components. Obtains all attributes of the component with the specified ID, excluding the information about child components. This is a system API.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
...@@ -43,7 +42,7 @@ Obtains all attributes of the component with the specified ID, excluding the inf ...@@ -43,7 +42,7 @@ Obtains all attributes of the component with the specified ID, excluding the inf
getInspectorTree(): string getInspectorTree(): string
Obtains the component tree and component attributes. Obtains the component tree and component attributes. This is a system API.
- Return value - Return value
...@@ -55,7 +54,7 @@ Obtains the component tree and component attributes. ...@@ -55,7 +54,7 @@ Obtains the component tree and component attributes.
sendEventByKey(id: string, action: number, params: string): boolean sendEventByKey(id: string, action: number, params: string): boolean
Sends an event to the component with the specified ID. Sends an event to the component with the specified ID. This is a system API.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
...@@ -73,7 +72,7 @@ Sends an event to the component with the specified ID. ...@@ -73,7 +72,7 @@ Sends an event to the component with the specified ID.
sendTouchEvent(event: TouchObject): boolean sendTouchEvent(event: TouchObject): boolean
Sends a touch event. Sends a touch event. This is a system API.
- Parameters - Parameters
...@@ -91,7 +90,7 @@ Sends a touch event. ...@@ -91,7 +90,7 @@ Sends a touch event.
sendKeyEvent(event: KeyEvent): boolean sendKeyEvent(event: KeyEvent): boolean
Sends a key event. Sends a key event. This is a system API.
- Parameters - Parameters
...@@ -109,7 +108,7 @@ Sends a key event. ...@@ -109,7 +108,7 @@ Sends a key event.
sendMouseEvent(event: MouseEvent): boolean sendMouseEvent(event: MouseEvent): boolean
Sends a mouse event. Sends a mouse event. This is a system API.
- Parameters - Parameters
......
# 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)
......
# Popup Control # Popup Control
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -17,44 +18,34 @@ None ...@@ -17,44 +18,34 @@ None
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bindPopup | show: boolean,<br/>popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.<br/>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br/>**popup**: parameters of the current popup. | | bindPopup | show: boolean,<br/>popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.<br/>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br/>**popup**: parameters of the current popup. |
## PopupOptions
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| message | string | Yes | - | Content of the popup message. |
| placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. |
| primaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | First button.<br/>**value**: text of the primary button in the popup.<br/>**action**: callback function for clicking the primary button. |
| secondaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | Second button.<br/>**value**: text of the secondary button in the popup.<br/>**action**: callback function for clicking the secondary button. |
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event.<br>**isVisible**: visibility of the popup. |
## CustomPopupOptions<sup>8+</sup>
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ---------------------------------------------- | ---- | ---------------- | ------------------------------------------------------------ |
| builder | () =&gt; any | Yes | - | Builder of the tooltip content. |
| placement | [Placement](ts-appendix-enums.md) | No | Placement.Bottom | Preferred position of the tooltip component. If the set position is insufficient for holding the component, it will be automatically adjusted. |
| maskColor | [Color](ts-appendix-enums.md#color) | No | - | Color of the tooltip mask. |
| popupColor | [Color](ts-appendix-enums.md#color) | No | - | Color of the tooltip. |
| enableArrow | boolean | No | true | Whether to display arrows. Arrows are displayed only for tooltips in the up and down directions. |
| autoCancel | boolean | No | true | Whether to automatically close the tooltip when an operation is performed on the page. |
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
- PopupOptions attributes
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| message | string | Yes | - | Content of the popup message. |
| placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. |
| primaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | First button.<br/>**value**: text of the primary button in the popup.<br/>**action**: callback function for clicking the primary button. |
| secondaryButton | {<br/>value: string,<br/>action: () =&gt; void<br/>} | No | - | Second button.<br/>**value**: text of the secondary button in the popup.<br/>**action**: callback function for clicking the secondary button. |
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
- CustomPopupOptions<sup>8+</sup>
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| builder | () =&gt; any | Yes | - | Builder of the tooltip content. |
| placement | Placement | No | Placement.Bottom | Preferred position of the tooltip component. If the set position is insufficient for holding the component, it will be automatically adjusted. |
| maskColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip mask. |
| popupColor | [Color](../../ui/ts-types.md) | No | - | Color of the tooltip. |
| enableArrow | boolean | No | true | Whether to display arrows. Arrows are displayed only for tooltips in the up and down directions. |
| autoCancel | boolean | No | true | Whether to automatically close the tooltip when an operation is performed on the page. |
| onStateChange | (isVisible: boolean) =&gt; void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. |
- Placement<sup>8+</sup> enums
| Name | Description |
| -------- | -------- |
| Left | The tooltip is on the left of the component. |
| Right | The tooltip is on the right of the component. |
| Top | The tooltip is on the top of the component. |
| Bottom | The tooltip is at the bottom of the component. |
| TopLeft | The tooltip is in the upper left corner of the component. |
| TopRight | The tooltip is in the upper right corner of the component. |
| BottomLeft | The tooltip is in the lower left corner of the component. |
| BottomRight | The tooltip is in the lower right corner of the component. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct PopupExample { struct PopupExample {
...@@ -65,7 +56,7 @@ struct PopupExample { ...@@ -65,7 +56,7 @@ struct PopupExample {
@Builder popupBuilder() { @Builder popupBuilder() {
Row({ space: 2 }) { Row({ space: 2 }) {
Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 }) Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 })
Text('Custom Popup').fontSize(12) Text('Custom Popup').fontSize(10)
}.width(100).height(50).backgroundColor(Color.White) }.width(100).height(50).backgroundColor(Color.White)
} }
......
# Z-order Control # Z-order Control
The **zIndex** attribute sets the z-order of a component in the stacking context.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -13,15 +15,16 @@ None ...@@ -13,15 +15,16 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| zIndex | number | 0 | Hierarchy of sibling components in a container. A larger z-order value indicates a higher display level. | | zIndex | number | 0 | Hierarchy of sibling components in a container. A larger value indicates a higher display level. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ZIndexExample { struct ZIndexExample {
...@@ -38,7 +41,7 @@ struct ZIndexExample { ...@@ -38,7 +41,7 @@ struct ZIndexExample {
Text('third child, zIndex(1)') Text('third child, zIndex(1)')
.size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart) .size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart)
.zIndex(1) .zIndex(1)
} }.width('100%').height(200)
}.width('100%').height(200) }.width('100%').height(200)
} }
} }
......
...@@ -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
......
...@@ -4,16 +4,17 @@ ...@@ -4,16 +4,17 @@
The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. The functionality and syntax of the **@Builder** decorator are the same as those of the [build Function](ts-function-build.md). The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. The functionality and syntax of the **@Builder** decorator are the same as those of the [build Function](ts-function-build.md).
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CompA { struct CompA {
size : number = 100; size1 : number = 100;
@Builder SquareText(label: string) { @Builder SquareText(label: string) {
Text(label) Text(label)
.width(1 * this.size) .width(1 * this.size1)
.height(1 * this.size) .height(1 * this.size1)
} }
@Builder RowOfSquareTexts(label1: string, label2: string) { @Builder RowOfSquareTexts(label1: string, label2: string) {
...@@ -21,8 +22,8 @@ struct CompA { ...@@ -21,8 +22,8 @@ struct CompA {
this.SquareText(label1) this.SquareText(label1)
this.SquareText(label2) this.SquareText(label2)
} }
.width(2 * this.size) .width(2 * this.size1)
.height(1 * this.size) .height(1 * this.size1)
} }
build() { build() {
...@@ -32,12 +33,12 @@ struct CompA { ...@@ -32,12 +33,12 @@ struct CompA {
this.SquareText("B") this.SquareText("B")
// or as long as tsc is used // or as long as tsc is used
} }
.width(2 * this.size) .width(2 * this.size1)
.height(1 * this.size) .height(1 * this.size1)
this.RowOfSquareTexts("C", "D") this.RowOfSquareTexts("C", "D")
} }
.width(2 * this.size) .width(2 * this.size1)
.height(2 * this.size) .height(2 * this.size1)
} }
} }
``` ```
...@@ -51,7 +52,8 @@ In certain circumstances, you may need to add a specific function, such as a cli ...@@ -51,7 +52,8 @@ In certain circumstances, you may need to add a specific function, such as a cli
### Component Initialization Through Parameters ### Component Initialization Through Parameters
When initializing a custom component through parameters, assign a **@Builder** decorated method to the **@BuilderParam** decorated attribute — **content**, and call the value of **content** in the custom component. If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `content: this.specificParam`), define the type of the attribute as a function without a return value (for example, `@BuilderParam content: () => void`). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `callContent: this.specificParam1("111")`), define the type of the attribute as `any` (for example,`@BuilderParam callContent: any;`). When initializing a custom component through parameters, assign a **@Builder** decorated method to the **@BuilderParam** decorated attribute — **content**, and call the value of **content** in the custom component. If no parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `content: this.specificParam`), define the type of the attribute as a function without a return value (for example, `@BuilderParam content: () => void`). If any parameter is passed when assigning a value to the **@BuilderParam** decorated attribute (for example, `callContent: this.specificParam1("111")`), define the type of the attribute as `any` (for example,`@BuilderParam callContent: any;`).
``` ```ts
// xxx.ets
@Component @Component
struct CustomContainer { struct CustomContainer {
header: string = ""; header: string = "";
...@@ -100,7 +102,8 @@ struct CustomContainerUser { ...@@ -100,7 +102,8 @@ struct CustomContainerUser {
In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of [build](../ui/ts-function-build.md). In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute. In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of [build](../ui/ts-function-build.md). In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute.
Example: Add a **\<Column>** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\<Column>** component. After the **\<Column>** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**. Example: Add a **\<Column>** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\<Column>** component. After the **\<Column>** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**.
``` ```ts
// xxx.ets
@Component @Component
struct CustomContainer { struct CustomContainer {
header: string = ""; header: string = "";
......
...@@ -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%')
}
}
```
...@@ -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,28 +42,26 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -41,28 +42,26 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%; width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
justify-content: center; justify-content: center;
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,11 +113,11 @@ Turn on the switch and the default delivery address is used. When the switch is ...@@ -113,11 +113,11 @@ 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%;
height: 100%; height: 100%;
background-color: #F1F3F5; background-color: #F1F3F5;
flex-direction: column; flex-direction: column;
padding: 50px; padding: 50px;
...@@ -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 {
......
...@@ -48,6 +48,7 @@ In the Hardware Driver Foundation (HDF), the I3C module uses the unified service ...@@ -48,6 +48,7 @@ In the Hardware Driver Foundation (HDF), the I3C module uses the unified service
Multiple devices, such as I2C target device, I3C target device, and I3C secondary controller, can be connected to an I3C bus. However, the I3C bus must have only one controller. Multiple devices, such as I2C target device, I3C target device, and I3C secondary controller, can be connected to an I3C bus. However, the I3C bus must have only one controller.
**Figure 1** I3C physical connection **Figure 1** I3C physical connection
![](figures/I3C_physical_connection.png "I3C_physical_connection") ![](figures/I3C_physical_connection.png "I3C_physical_connection")
### Constraints ### Constraints
...@@ -159,7 +160,7 @@ if (ret != 2) { ...@@ -159,7 +160,7 @@ if (ret != 2) {
} }
``` ```
>![](./public_sys-resources/icon-caution.gif) **Caution**<br> >![](../public_sys-resources/icon-caution.gif) **Caution**<br>
>- The device address in the **I3cMsg** structure does not contain the read/write flag bit. The read/write information is passed by the read/write control bit in the member variable **flags**. >- The device address in the **I3cMsg** structure does not contain the read/write flag bit. The read/write information is passed by the read/write control bit in the member variable **flags**.
>- The **I3cTransfer()** function does not limit the number of message structures or the length of data in each message structure. The I3C controller determines these two limits. >- The **I3cTransfer()** function does not limit the number of message structures or the length of data in each message structure. The I3C controller determines these two limits.
>- Using **I3cTransfer()** may cause the system to sleep. Do not call it in the interrupt context. >- Using **I3cTransfer()** may cause the system to sleep. Do not call it in the interrupt context.
......
...@@ -63,7 +63,7 @@ The RTC module adaptation involves the following steps: ...@@ -63,7 +63,7 @@ The RTC module adaptation involves the following steps:
3. Instantiate the RTC controller object. 3. Instantiate the RTC controller object.
- Initialize **RtcHost**. - Initialize **RtcHost**.
- Instantiate **RtcMethod** in the **RtcHost** object. - Instantiate **RtcMethod** in the **RtcHost** 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 **RtcMethod**, see [Available APIs](#available-apis). > For details about the functions in **RtcMethod**, see [Available APIs](#available-apis).
4. Debug the driver. 4. Debug the driver.
......
# Ability框架概述 # Ability框架概述
​ Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件。一个应用可以包含一个或多个Ability。 ​ Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。Ability是系统调度应用的最小单元,是能够完成一个独立功能的组件。一个应用可以包含一个或多个Ability。
​ Ability框架模型具有两种形态: ​ Ability框架模型具有两种形态:
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
| 开发方式 | 提供类Web的API,UI开发与Stage模型一致。 | 提供面向对象的开发方式,UI开发与FA模型一致。 | | 开发方式 | 提供类Web的API,UI开发与Stage模型一致。 | 提供面向对象的开发方式,UI开发与FA模型一致。 |
| 引擎实例 | 每个进程内的每个Ability实例独享一个JS VM引擎实例。 | 每个进程内的多个Ability实例共享一个JS VM引擎实例。 | | 引擎实例 | 每个进程内的每个Ability实例独享一个JS VM引擎实例。 | 每个进程内的多个Ability实例共享一个JS VM引擎实例。 |
| 进程内对象共享 | 不支持。 | 支持。 | | 进程内对象共享 | 不支持。 | 支持。 |
| 包描述文件 | 使用config.json描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用module.json描述HAP包和组件信息,可以指定入口文件名。 | | 包描述文件 | 使用config.json描述HAP包和组件信息,组件必须使用固定的文件名。 | 使用module.json5描述HAP包和组件信息,可以指定入口文件名。 |
| 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享)以及FormAbility(卡片)。 | 提供Ability(页面展示)、Extension(基于场景的服务扩展)。 | | 组件 | 提供PageAbility(页面展示),ServiceAbility(服务),DataAbility(数据分享)以及FormAbility(卡片)。 | 提供Ability(页面展示)、Extension(基于场景的服务扩展)。 |
​ 除了上述设计上的差异外,对于开发者而言,两种模型的主要区别在于: ​ 除了上述设计上的差异外,对于开发者而言,两种模型的主要区别在于:
......
# Ability开发指导 # Ability开发指导
## 场景介绍 ## 场景介绍
Stage模型是区别于FA模型的一种应用开发模型,对此模型的介绍详见[Stage模型综述](stage-brief.md)。开发Stage模型应用时,需要在module.json和app.json配置文件中对应用的包结构进行声明,对应用包结构配置文件的说明详见[应用包结构配置文件的说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/stage-structure.md)。基于Stage模型的Ability应用开发,主要涉及如下功能逻辑: Stage模型是区别于FA模型的一种应用开发模型,对此模型的介绍详见[Stage模型综述](stage-brief.md)。开发Stage模型应用时,需要在module.json5和app.json5配置文件中对应用的包结构进行声明,对应用包结构配置文件的说明详见[应用包结构配置文件的说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/stage-structure.md)。基于Stage模型的Ability应用开发,主要涉及如下功能逻辑:
- 创建支持使用屏幕浏览及人机交互的Ability应用,包括实现Ability的生命周期、获取Ability配置信息、向用户申请授权及环境变化通知等场景。 - 创建支持使用屏幕浏览及人机交互的Ability应用,包括实现Ability的生命周期、获取Ability配置信息、向用户申请授权及环境变化通知等场景。
- 启动Ability应用,包括相同设备启动Ability、跨设备启动Ability以及指定页面启动Ability等场景。 - 启动Ability应用,包括相同设备启动Ability、跨设备启动Ability以及指定页面启动Ability等场景。
- 通用组件Call功能,详见[Call调用开发指导](stage-call.md) - 通用组件Call功能,详见[Call调用开发指导](stage-call.md)
...@@ -8,7 +8,7 @@ Stage模型是区别于FA模型的一种应用开发模型,对此模型的介 ...@@ -8,7 +8,7 @@ Stage模型是区别于FA模型的一种应用开发模型,对此模型的介
- 应用迁移,详见[应用迁移开发指导](stage-ability-continuation.md) - 应用迁移,详见[应用迁移开发指导](stage-ability-continuation.md)
### 启动模式 ### 启动模式
ability支持单实例、多实例和指定实例3种启动模式,在module.json中通过launchType配置。启动模式对应Ability被启动时的行为,对启动模式的详细说明如下: ability支持单实例、多实例和指定实例3种启动模式,在module.json5中通过launchType配置。启动模式对应Ability被启动时的行为,对启动模式的详细说明如下:
| 启动模式 | 描述 |说明 | | 启动模式 | 描述 |说明 |
| ----------- | ------- |---------------- | | ----------- | ------- |---------------- |
...@@ -16,7 +16,7 @@ ability支持单实例、多实例和指定实例3种启动模式,在module.js ...@@ -16,7 +16,7 @@ ability支持单实例、多实例和指定实例3种启动模式,在module.js
| singleton | 单实例 | 系统中只存在唯一一个实例,startAbility时,如果已存在,则复用系统中的唯一一个实例 | | singleton | 单实例 | 系统中只存在唯一一个实例,startAbility时,如果已存在,则复用系统中的唯一一个实例 |
| specified | 指定实例 | 运行时由ability内部业务决定是否创建多实例 | | specified | 指定实例 | 运行时由ability内部业务决定是否创建多实例 |
缺省情况下是singleton模式,module.json示例如下: 缺省情况下是singleton模式,module.json5示例如下:
```json ```json
{ {
"module": { "module": {
...@@ -146,9 +146,9 @@ export default class MainAbility extends Ability { ...@@ -146,9 +146,9 @@ export default class MainAbility extends Ability {
} }
``` ```
### 应用向用户申请授权 ### 应用向用户申请授权
应用需要获取用户的隐私信息或使用系统能力时,比如获取位置信息、使用相机拍摄照片或录制视频等,需要向用户申请授权。在开发过程中,首先需要明确涉及的敏感权限并在module.json中声明需要的权限,同时通过接口`requestPermissionsFromUser`以动态弹窗的方式向用户申请授权。以访问日历为例,具体示例代码如下: 应用需要获取用户的隐私信息或使用系统能力时,比如获取位置信息、使用相机拍摄照片或录制视频等,需要向用户申请授权。在开发过程中,首先需要明确涉及的敏感权限并在module.json5中声明需要的权限,同时通过接口`requestPermissionsFromUser`以动态弹窗的方式向用户申请授权。以访问日历为例,具体示例代码如下:
在module.json声明需要的权限: 在module.json5声明需要的权限:
```json ```json
"requestPermissions": [ "requestPermissions": [
{ {
......
...@@ -61,9 +61,9 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用 ...@@ -61,9 +61,9 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用
2.注册ServiceExtensionAbility 2.注册ServiceExtensionAbility
需要在应用配置文件module.json中进行注册,注册类型type需要设置为service。 需要在应用配置文件module.json5中进行注册,注册类型type需要设置为service。
**module.json配置样例** **module.json5配置样例**
```json ```json
"extensionAbilities":[{ "extensionAbilities":[{
...@@ -72,6 +72,6 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用 ...@@ -72,6 +72,6 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用
"description": "service", "description": "service",
"type": "service", "type": "service",
"visible": true, "visible": true,
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts" "srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}] }]
``` ```
...@@ -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,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)
......
...@@ -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)
...@@ -45,7 +45,7 @@ showToast(options: ShowToastOptions): void ...@@ -45,7 +45,7 @@ showToast(options: ShowToastOptions): void
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | -------------- | ---- | ---------------------------------------- | | -------- | -------------- | ---- | ---------------------------------------- |
| message | string | 是 | 显示的文本信息。 | | message | string | 是 | 显示的文本信息。 |
| duration | number | 否 | 默认值1500ms,建议区间:1500ms-10000ms,若小于1500ms则取默认值。 | | duration | number | 否 | 默认值1500ms,取值区间:1500ms-10000ms。若小于1500ms则取默认值,若大于10000ms则取上限值10000ms。 |
| bottom | &lt;length&gt; | 否 | 设置弹窗边框距离屏幕底部的位置。 | | bottom | &lt;length&gt; | 否 | 设置弹窗边框距离屏幕底部的位置。 |
## prompt.showDialog ## prompt.showDialog
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册