提交 b36244a3 编写于 作者: S sienna1128 提交者: Gitee

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

Signed-off-by: Nsienna1128 <lixiaoyan45@huawei.com>
...@@ -231,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen ...@@ -231,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease
...@@ -365,4 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen ...@@ -365,4 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen
zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease
zh-cn/application-dev/website.md @zengyawen zh-cn/application-dev/website.md @zengyawen
zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen
\ No newline at end of file zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen
zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen
\ No newline at end of file
...@@ -66,7 +66,7 @@ ...@@ -66,7 +66,7 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filename" name="*.jpg|*.png|*.gif|*.pdf|*.xlsm" desc="already checked"/> <filteritem type="filename" name="*.jpg|*.png|*.gif|*.pdf|*.xlsm|*.zip" desc="already checked"/>
</filefilter> </filefilter>
</filefilterlist> </filefilterlist>
......
...@@ -81,7 +81,7 @@ import Ability from '@ohos.application.Ability' ...@@ -81,7 +81,7 @@ import Ability from '@ohos.application.Ability'
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
str: String = "" str: string = ""
constructor(num, string) { constructor(num, string) {
this.num = num this.num = num
......
# Distributed Data Service Overview # Distributed Data Service Overview
The distributed data service (DDS) implements distributed database collaboration across devices for applications. 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. 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. You do not need to care about the implementation of the database locking mechanism.
## Basic Concepts ## Basic Concepts
- **KV data model** ### KV Data Model
The key-value \(KV\) data model allows data to be organized, indexed, and stored in key-value pairs. The key-value (KV) data model allows data to be organized, indexed, and stored in KV pairs.
The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces. The KV data model is suitable for storing service data that is not related. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles database version compatibility issues and data synchronization conflicts easily. The distributed database is based on the KV data model and provides KV-based access interfaces.
- **Distributed database transactions** ### Distributed Database Transaction
Distributed database transactions include local transactions \(same as the transactions of traditional databases\) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices. Distributed database transactions include local transactions (same as the transactions of traditional databases) and synchronization transactions. Synchronization transactions allow data to be synchronized between devices by local transaction. Synchronization of a local transaction modification either succeeds or fails on all the devices.
- **Distributed database consistency** ### Distributed Database Consistency
In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types: In a distributed scenario, cross-device collaboration demands consistent data between the devices in the same network. The data consistency can be classified into the following types:
- **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately. - **Strong consistency**: When data is inserted, deleted, or modified on a device, other devices in the same network will obtain the latest data immediately.
- **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time. - **Weak consistency**: When data is added, deleted, or modified on a device, other devices in the same network may or may not obtain the latest data. The data on these devices may be inconsistent after a certain period of time.
- **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time. - **Eventual consistency**: When data is added, deleted, or modified on a device, other devices in the same network may not obtain the latest data immediately. However, data on these devices will become consistent after a certain period of time.
Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center. Strong consistency has high requirements on distributed data management and may be used in distributed server deployment. The DDS supports only the eventual consistency because mobile devices are not always online and the network has no center.
- **Distributed database synchronization** ### Distributed Database Synchronization
After discovering and authenticating a device, the underlying communication component notifies the upper-layer application \(including the DDS\) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices. After discovering and authenticating a device, the underlying communication component notifies the upper-layer application (including the DDS) that the device goes online. The DDS then establishes an encrypted transmission channel to synchronize data between the two devices.
The DDS provides the following synchronization modes: The DDS provides the following synchronization modes:
- **Manual synchronization**: Applications call **sync** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL\_ONLY** \(pulling remote data to the local end\), **PUSH\_ONLY** \(pushing local data to the remote end\), or **PUSH\_PULL** \(pushing local data to the remote end and pulling remote data to the local end\). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end. - **Manual synchronization**: Applications call **sync()** to trigger a synchronization. The list of devices to be synchronized and the synchronization mode must be specified. The synchronization mode can be **PULL_ONLY** (pulling remote data to the local end), **PUSH_ONLY** (pushing local data to the remote end), or **PUSH_PULL** (pushing local data to the remote end and pulling remote data to the local end). The internal interface supports condition-based synchronization. The data that meets the conditions can be synchronized to the remote end.
- **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end. - **Automatic synchronization**: includes full synchronization and condition-based subscription synchronization. In full synchronization, the distributed database automatically pushes local data to the remote end and pulls remote data to the local end when a device goes online or application data is updated. Applications do not need to call **sync()**. The internal interface supports condition-based subscription synchronization. The data that meets the subscription conditions on the remote end is automatically synchronized to the local end.
- **Single KV store** ### Single KV Store
Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time. Data is saved locally in the unit of a single KV entry. Only one entry is saved for each key. Data can be modified only locally and synchronized to remote devices in sequence based on the update time.
- **Device KV store** ### Device KV Store
The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally. The device KV store is based on the single KV store. The local device ID is added to the key when KV data is stored in the device KV store. Data can be isolated, managed, and queried by device. However, the data synchronized from remote devices cannot be modified locally.
- **Conflict resolution** ### Conflict Resolution
A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins \(LWW\) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported. A data conflict occurs when multiple devices modify the same data and commit the modification to the database. The last write wins (LWW) is the default conflict resolution policy used for data conflicts. Based on the commit timestamps, the data with a later timestamp is used. Currently, customized conflict resolution policies are not supported.
- **Schema-based database management and data query based on predicates** ### Schema-based Database Management and Predicate-based Data Query
A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of key-value pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query. A schema is specified when you create or open a single KV store. Based on the schema, the database detects the value format of KV pairs and checks the value structure. Based on the fields in the values, the database implements index creation and predicate-based query.
- **Distributed database backup** ### Distributed Database Backup
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 ## 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.
- **APIs** The DDS consists of the following:
The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released. - **APIs**<br>The DDS provides APIs to create databases, access data, and subscribe to data. The APIs support the KV data model and common data types. They are highly compatible and easy to use, and can be released.
- **Service component** - **Service component**<br>The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database.
The service component implements management of metadata, permissions, encryption, backup and restore, and multiple users, and completes initialization of the storage component, synchronization component, and communication adaptation layer of the distributed database. - **Storage component**<br>The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution.
- **Storage component** - **Synchronization component**<br>The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution. - **Communication adaptation layer**<br>The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
- **Synchronization component** Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
The synchronization component interacts with the storage component and the communication adaptation layer to maintain data consistency between online devices. It synchronizes data generated on the local device to other devices and merges data from other devices into the local device.
- **Communication adaptation layer** **Figure 1** How DDS works
The communication adaptation layer calls APIs of the underlying public communication layer to create and connect to communication channels, receive device online and offline messages, update metadata of the connected and disconnected devices, send device online and offline messages to the synchronization component. The synchronization component updates the list of connected devices, and calls the APIs of the communication adaption layer to encapsulate data and send the data to the connected devices.
![](figures/en-us_image_0000001183386164.png)
Applications call the DDS APIs to create, access, and subscribe to distributed databases. The APIs store data to the storage component based on the capabilities provided by the service component. The storage component interacts with the synchronization component to synchronize data. The synchronization component uses the communication adaptation layer to synchronize data to remote devices, which update the data in the storage component and provide the data for applications through service APIs.
**Figure 1** How DDS works<a name="fig9151258063"></a> ## Constraints
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database.
![](figures/en-us_image_0000001183386164.png) - The KV data model specifications supported by the DDS are as follows:
## Constraints - For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases.
- The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The DDS does not support customized conflict resolution policies.
- The KV data model specifications supported by the DDS are as follows:
- For each record in a device KV store, the key must be less than or equal to 896 bytes and the value be less than 4 MB.
- For each record in a single KV store, the key must be less than or equal to 1 KB and the value be less than 4 MB.
- An application can open a maximum of 16 KV stores simultaneously.
- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases. - The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- The DDS does not support customized conflict resolution policies.
- The maximum number of access requests to the KvStore API is 1000 per second and 10000 per minute. The maximum number of access requests to the KvManager API is 50 per second and 500 per minute.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
- Blocking operations, such as modifying UI components, are not allowed in the distributed database event callback.
...@@ -196,17 +196,41 @@ Table 15 Transaction APIs ...@@ -196,17 +196,41 @@ Table 15 Transaction APIs
(3) Create an RDB store. (3) Create an RDB store.
The sample code is as follows: FA model:
```js ```js
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.rdb'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = { name: "RdbTest.db" }
const STORE_CONFIG = { name: "rdbstore.db" } data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
```
Stage model:
```ts
import data_rdb from '@ohos.data.rdb'
// Obtain the context.
import Ability from '@ohos.application.Ability'
let context = null
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
context = this.context
}
}
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db" }
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
``` ```
2. Insert data. 2. Insert data.
......
...@@ -26,70 +26,30 @@ ...@@ -26,70 +26,30 @@
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.| | ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.| | ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType, callback:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.| | ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.|
## How to Develop ## How to Develop
1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file. 1. Before obtaining data from a type of sensor, check whether the required permission has been configured.<br>
The system provides the following sensor-related permissions:
``` - ohos.permission.ACCELEROMETER
"reqPermissions": [
{ - ohos.permission.GYROSCOPE
"name": "ohos.permission.ACCELEROMETER",
"reason": "", - ohos.permission.ACTIVITY_MOTION
"usedScene": {
"ability": [ - ohos.permission.READ_HEALTH_DATA
"sensor.index.MainAbility",
".MainAbility" For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
],
"when": "inuse"
}
},
{
"name": "ohos.permission.GYROSCOPE",
"reason": "",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "ACTIVITY_MOTION_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.READ_HEALTH_DATA",
"reason": "HEALTH_DATA_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
}
]
```
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){
console.info("Subscription succeeded. data = " + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -99,11 +59,8 @@ ...@@ -99,11 +59,8 @@
3. Unsubscribe from sensor data changes. 3. Unsubscribe from sensor data changes.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER);
console.info("Succeeded in unsubscribing from acceleration sensor data."); // The unsubscription is successful, and the result is printed.
}
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -113,11 +70,10 @@ ...@@ -113,11 +70,10 @@
4. Subscribe to only one data change of a type of sensor. 4. Subscribe to only one data change of a type of sensor.
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor";
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
} });
);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**.
...@@ -127,11 +83,12 @@ ...@@ -127,11 +83,12 @@
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
``` ```
import sensor from "@ohos.sensor";
try { try {
sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) {
console.info("Data obtained successfully. data=" + data); // The call is successful, and the obtained sensor data is printed. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
} catch (error) { } catch (error) {
console.error(error); console.error("Failed to get sensor data");
} }
``` ```
\ No newline at end of file
...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -52,15 +52,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
1. To obtain data of the following sensors, you must claim the required permissions. 1. To obtain data of the following sensors, you must claim the required permissions.
Table 7 Sensor data permissions | Sensor | Permission | Sensitivity | Permission Description |
| ------------------------- | -------------------------------- | ------------ | ----------------------- |
| Sensor | Permission | Sensitivity | Permission Description | | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.|
| ------------------------- | -------------------------------- | ------------ | ----------------------- | | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.|
| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting. 2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting.
...@@ -22,42 +22,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -22,42 +22,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## How to Develop ## How to Develop
1. Declare the permissions required for controlling vibrators on the hardware device in the `config.json` file. 1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
```
"reqPermissions": [
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.VIBRATE",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
}
]
```
2. Trigger the device to vibrate. 2. Trigger the device to vibrate.
......
...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## Constraints ## Constraints
When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect.
...@@ -232,7 +232,6 @@ Table 11 Internal structure of the module tag ...@@ -232,7 +232,6 @@ Table 11 Internal structure of the module tag
| distroFilter | Application distribution rules.<br>AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty)<br/>Set this attribute when an application has multiple entry modules. | | distroFilter | Application distribution rules.<br>AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty)<br/>Set this attribute when an application has multiple entry modules. |
| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | | reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) |
| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | | commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) |
| allowClassMap | Metadata of the HAP file. The value can be **true** or **false**. If the value is **true**, the HAP file uses the Java object proxy mechanism provided by the OpenHarmony framework. | Boolean | No (initial value: **false**) |
| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | | entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) |
Example of the **module** tag structure: Example of the **module** tag structure:
...@@ -348,7 +347,7 @@ Table 17 Internal structure of the abilities attribute ...@@ -348,7 +347,7 @@ Table 17 Internal structure of the abilities attribute
| Attribute | Description | Data Type | Initial Value Allowed | | Attribute | Description | Data Type | Initial Value Allowed |
| ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | | ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- |
| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) |
| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.<br> The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.<br> Note: When you use DevEco Studio to create a project, the configuration of the first ability is generated by default, including the **MainAbility.java** file and the class name **MainAbility** defaulted in the **name** string for the **abilities** attribute in **config.json**. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No | | name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.<br> The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.<br> Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No |
| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) |
| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.<br> Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) | | icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.<br> Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) |
| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br> Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | | label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br> Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) |
...@@ -372,7 +371,7 @@ Table 17 Internal structure of the abilities attribute ...@@ -372,7 +371,7 @@ Table 17 Internal structure of the abilities attribute
| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | | supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) |
| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.<br>**true**: This ability can provide forms.<br>**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) | | formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.<br>**true**: This ability can provide forms.<br>**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) |
| forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | | forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) |
| srcLanguage | Programming language used to develop the ability. | String | The value can be **java**, **js**, or **ets**. | | srcLanguage | Programming language used to develop the ability. | String | The value can be **js**, or **ets**. |
| srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) | | srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) |
| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | | uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) |
| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | Yes (initial value: left empty) | | startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | Yes (initial value: left empty) |
...@@ -587,12 +586,10 @@ Table 27 Internal structure of the forms attribute ...@@ -587,12 +586,10 @@ Table 27 Internal structure of the forms attribute
| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) |
| isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No | | isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No |
| type | Type of the widget. Available values are as follows:<br>**Java**: indicates a Java-programmed widget.<br>**JS**: indicates a JavaScript-programmed widget.| String | No | | type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget.| String | No |
| colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| | colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)|
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>1 * 2: indicates a grid with one row and two columns.<br>2 * 2: indicates a grid with two rows and two columns.<br>2 * 4: indicates a grid with two rows and four columns.<br>4 * 4: indicates a grid with four rows and four columns.| String array| No | | supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>1 * 2: indicates a grid with one row and two columns.<br>2 * 2: indicates a grid with two rows and two columns.<br>2 * 4: indicates a grid with two rows and four columns.<br>4 * 4: indicates a grid with four rows and four columns.| String array| No |
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No |
| landscapeLayouts | Landscape layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No |
| portraitLayouts | Portrait layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No |
| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) |
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) |
...@@ -632,9 +629,9 @@ Example of the **forms** attribute structure: ...@@ -632,9 +629,9 @@ Example of the **forms** attribute structure:
] ]
}, },
{ {
"name": "Form_Java", "name": "Form_JS",
"description": "It's Java Form", "description": "It's JS Form",
"type": "Java", "type": "JS",
"colorMode": "auto", "colorMode": "auto",
"isDefault": false, "isDefault": false,
"updateEnabled": true, "updateEnabled": true,
......
...@@ -6,8 +6,8 @@ This module provides APIs for accessing ability-specific resources. You can use ...@@ -6,8 +6,8 @@ This module provides APIs for accessing ability-specific resources. You can use
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. 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 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model. > - The APIs of this module can be used only in the stage model.
## Usage ## Usage
......
...@@ -4,12 +4,12 @@ The **wantConstant** module provides the actions, entities, and flags used in ** ...@@ -4,12 +4,12 @@ The **wantConstant** module provides the actions, entities, and flags used in **
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```js
import wantConstant from '@ohos.ability.wantConstant' import wantConstant from '@ohos.ability.wantConstant';
``` ```
## wantConstant.Action ## wantConstant.Action
...@@ -46,8 +46,13 @@ Enumerates the action constants of the **Want** object. ...@@ -46,8 +46,13 @@ Enumerates the action constants of the **Want** object.
| ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. | | ACTION_FILE_SELECT<sup>7+</sup> | ohos.action.fileSelect | Action of selecting a file. |
| PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | PARAMS_STREAM<sup>7+</sup> | ability.params.stream | URI of the data stream associated with the target when the data is sent. |
| ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | | ACTION_APP_ACCOUNT_OAUTH <sup>8+</sup> | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. |
| ACTION_MARKER_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_DOWNLOAD <sup>9+</sup> | ohos.want.action.marketDownload | Action of downloading an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| ACTION_MARKET_CROWDTEST <sup>9+</sup> | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_SANDBOX<sup>9+</sup> |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_BUNDLE_NAME<sup>9+</sup> |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_MODULE_NAME<sup>9+</sup> |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_ABILITY_NAME<sup>9+</sup> |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| DLP_PARAMS_INDEX<sup>9+</sup> |ohos.dlp.params.index |Action of obtaining the DLP index.<br>**System API**: This is a system API and cannot be called by third-party applications. |
## wantConstant.Entity ## wantConstant.Entity
......
...@@ -2104,6 +2104,7 @@ Called to return the result of an authentication request. ...@@ -2104,6 +2104,7 @@ Called to return the result of an authentication request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | -------------------- | ---- | ------ | | ------ | -------------------- | ---- | ------ |
| code | number | Yes | Authentication result code.| | code | number | Yes | Authentication result code.|
...@@ -2134,6 +2135,7 @@ Called to redirect a request. ...@@ -2134,6 +2135,7 @@ Called to redirect a request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ---- | ---- | ---------- | | ------- | ---- | ---- | ---------- |
| request | Want | Yes | Request to be redirected.| | request | Want | Yes | Request to be redirected.|
...@@ -2191,6 +2193,7 @@ Implicitly adds an app account based on the specified authentication type and op ...@@ -2191,6 +2193,7 @@ Implicitly adds an app account based on the specified authentication type and op
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
...@@ -2207,6 +2210,7 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr ...@@ -2207,6 +2210,7 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2224,6 +2228,7 @@ Verifies the credential of an app account. This API uses an asynchronous callbac ...@@ -2224,6 +2228,7 @@ Verifies the credential of an app account. This API uses an asynchronous callbac
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2239,6 +2244,7 @@ Sets authenticator properties. This API uses an asynchronous callback to return ...@@ -2239,6 +2244,7 @@ Sets authenticator properties. This API uses an asynchronous callback to return
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | | options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. |
...@@ -2253,6 +2259,7 @@ Checks the account labels. This API uses an asynchronous callback to return the ...@@ -2253,6 +2259,7 @@ Checks the account labels. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
...@@ -2268,6 +2275,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call ...@@ -2268,6 +2275,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
......
...@@ -78,7 +78,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -78,7 +78,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
## WindowExtensionAbility.onWindowReady ## WindowExtensionAbility.onWindowReady
onWindowReady(window: Window): void onWindowReady(window: window.Window): void
Called when a window is ready. Called when a window is ready.
...@@ -88,7 +88,7 @@ Called when a window is ready. ...@@ -88,7 +88,7 @@ Called when a window is ready.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.| | window | [window.Window](js-apis-window.md#window) | Yes| Current **Window** instance.|
**Example** **Example**
...@@ -99,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -99,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onWindowReady(window) { onWindowReady(window) {
window.loadContent('WindowExtAbility/pages/index1').then(() => { window.loadContent('WindowExtAbility/pages/index1').then(() => {
window.getProperties().then((pro) => { window.getProperties().then((pro) => {
console.log("WindowExtension " + JSON.stringify(pro)); console.log('WindowExtension ' + JSON.stringify(pro));
}) })
window.show(); window.show();
}) })
......
...@@ -4,7 +4,7 @@ The **Ability** module manages the ability lifecycle and context, such as creati ...@@ -4,7 +4,7 @@ The **Ability** module manages the ability lifecycle and context, such as creati
This module provides the following common ability-related functions: This module provides the following common ability-related functions:
- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). - [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications. - [Callee](#callee): implements callbacks for registration and deregistration of caller notifications.
> **NOTE** > **NOTE**
...@@ -22,12 +22,12 @@ import Ability from '@ohos.application.Ability'; ...@@ -22,12 +22,12 @@ import Ability from '@ohos.application.Ability';
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| | context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.|
| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| | launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.|
| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| | lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.|
| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| | callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.|
## Ability.onCreate ## Ability.onCreate
...@@ -39,13 +39,13 @@ Called to initialize the service logic when an ability is created. ...@@ -39,13 +39,13 @@ Called to initialize the service logic when an ability is created.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| | want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.|
| param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onCreate(want, param) { onCreate(want, param) {
...@@ -65,12 +65,12 @@ Called when a **WindowStage** is created for this ability. ...@@ -65,12 +65,12 @@ Called when a **WindowStage** is created for this ability.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.| | windowStage | window.WindowStage | Yes| **WindowStage** information.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
...@@ -88,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability. ...@@ -88,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageDestroy() { onWindowStageDestroy() {
...@@ -109,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability ...@@ -109,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| windowStage | window.WindowStage | Yes| **WindowStage** information.| | windowStage | window.WindowStage | Yes| **WindowStage** information.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onWindowStageRestore(windowStage) { onWindowStageRestore(windowStage) {
...@@ -132,8 +132,8 @@ Called when this ability is destroyed to clear resources. ...@@ -132,8 +132,8 @@ Called when this ability is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onDestroy() { onDestroy() {
...@@ -151,8 +151,8 @@ Called when this ability is switched from the background to the foreground. ...@@ -151,8 +151,8 @@ Called when this ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onForeground() { onForeground() {
...@@ -170,8 +170,8 @@ Called when this ability is switched from the foreground to the background. ...@@ -170,8 +170,8 @@ Called when this ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onBackground() { onBackground() {
...@@ -191,18 +191,18 @@ Called to save data during the ability migration preparation process. ...@@ -191,18 +191,18 @@ Called to save data during the ability migration preparation process.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.| | wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| AbilityConstant.OnContinueResult | Continuation result.| | AbilityConstant.OnContinueResult | Continuation result.|
**Example**
**Example**
```js ```js
import AbilityConstant from "@ohos.application.AbilityConstant" import AbilityConstant from "@ohos.application.AbilityConstant"
class myAbility extends Ability { class myAbility extends Ability {
...@@ -225,20 +225,17 @@ Called when the ability startup mode is set to singleton. ...@@ -225,20 +225,17 @@ Called when the ability startup mode is set to singleton.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.|
| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onNewWant(want, launchParams) { onNewWant(want) {
console.log('onNewWant, want:' + want.abilityName); console.log('onNewWant, want:' + want.abilityName);
if (launchParams.launchReason === AbilityConstant.LaunchReason.CONTINUATION) {
console.log('onNewWant, launchReason is continuation');
}
} }
} }
``` ```
...@@ -254,12 +251,12 @@ Called when the configuration of the environment where the ability is running is ...@@ -254,12 +251,12 @@ Called when the configuration of the environment where the ability is running is
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
onConfigurationUpdated(config) { onConfigurationUpdated(config) {
...@@ -278,12 +275,12 @@ Dumps client information. ...@@ -278,12 +275,12 @@ Dumps client information.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.| | params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
**Example**
```js ```js
class myAbility extends Ability { class myAbility extends Ability {
dump(params) { dump(params) {
...@@ -293,11 +290,35 @@ Dumps client information. ...@@ -293,11 +290,35 @@ Dumps client information.
} }
``` ```
## Ability.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
**Example**
```js
class myAbility extends Ability {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
## Caller ## Caller
Implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). Implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
## Caller.call ## Caller.call
...@@ -310,19 +331,19 @@ Sends sequenceable data to the target ability. ...@@ -310,19 +331,19 @@ Sends sequenceable data to the target ability.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return a response.| | Promise&lt;void&gt; | Promise used to return a response.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ // Custom sequenceable data structure class MyMessageAble{ // Custom sequenceable data structure
...@@ -383,19 +404,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data ...@@ -383,19 +404,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| | method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.| | Promise&lt;rpc.MessageParcel&gt; | Promise used to return the sequenceable data from the target ability.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ class MyMessageAble{
...@@ -455,8 +476,8 @@ Releases the caller interface of the target ability. ...@@ -455,8 +476,8 @@ Releases the caller interface of the target ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example** **Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
var caller; var caller;
...@@ -492,12 +513,12 @@ Registers a callback that is invoked when the stub on the target ability is disc ...@@ -492,12 +513,12 @@ Registers a callback that is invoked when the stub on the target ability is disc
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.|
**Example**
**Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
var caller; var caller;
...@@ -540,12 +561,13 @@ Registers a caller notification callback, which is invoked when the target abili ...@@ -540,12 +561,13 @@ Registers a caller notification callback, which is invoked when the target abili
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.| | method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.| | callback | CalleeCallBack | Yes| JS notification synchronization callback of the **rpc.MessageParcel** type. The callback must return at least one empty **rpc.Sequenceable** object. Otherwise, the function execution fails.|
**Example** **Example**
```js ```js
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
class MyMessageAble{ class MyMessageAble{
...@@ -595,9 +617,9 @@ Deregisters a caller notification callback, which is invoked when the target abi ...@@ -595,9 +617,9 @@ Deregisters a caller notification callback, which is invoked when the target abi
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| method | string | Yes| Registered notification message string.| | method | string | Yes| Registered notification message string.|
**Example** **Example**
...@@ -618,17 +640,16 @@ Deregisters a caller notification callback, which is invoked when the target abi ...@@ -618,17 +640,16 @@ Deregisters a caller notification callback, which is invoked when the target abi
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| | (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.|
## CalleeCallBack ## CalleeCallBack
(indata: rpc.MessageParcel): rpc.Sequenceable; (indata: rpc.MessageParcel): rpc.Sequenceable;
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| | (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.|
...@@ -65,7 +65,7 @@ Enumerates ability continuation results. ...@@ -65,7 +65,7 @@ Enumerates ability continuation results.
## AbilityConstant.WindowMode ## AbilityConstant.WindowMode
Enumerates the window modes when an ability is started. Enumerates the window modes in which an ability can be displayed at startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -76,3 +76,15 @@ Enumerates the window modes when an ability is started. ...@@ -76,3 +76,15 @@ Enumerates the window modes when an ability is started.
| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | | WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. |
| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | | WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. |
| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| | WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.|
## AbilityConstant.MemoryLevel
Enumerates the memory levels.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value| Description |
| --- | --- | --- |
| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. |
| MEMORY_LEVEL_LOW | 1 | Low memory usage. |
| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. |
...@@ -875,3 +875,265 @@ abilityDelegator.finishTest(msg, 0).then(() => { ...@@ -875,3 +875,265 @@ abilityDelegator.finishTest(msg, 0).then(() => {
console.info("finishTest promise"); console.info("finishTest promise");
}); });
``` ```
### addAbilityStageMonitor<sup>9+</sup>
addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<void>): void;
Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes of an ability stage. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor, (err : any) => {
console.info("addAbilityStageMonitor callback");
});
```
### addAbilityStageMonitor<sup>9+</sup>
addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes of an ability stage. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.addAbilityStageMonitor(monitor).then(() => {
console.info("addAbilityStageMonitor promise");
});
```
### removeAbilityStageMonitor<sup>9+</sup>
removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<void>): void;
Removes an **AbilityStageMonitor** instance from the application memory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor, (err : any) => {
console.info("removeAbilityStageMonitor callback");
});
```
### removeAbilityStageMonitor<sup>9+</sup>
removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\<void>;
Removes an **AbilityStageMonitor** object from the application memory. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
var abilityDelegator;
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.removeAbilityStageMonitor(monitor).then(() => {
console.info("removeAbilityStageMonitor promise");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\<AbilityStage>): void;
Waits for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Example**
```js
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\<AbilityStage>;
Waits for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| timeout | number | No | Maximum waiting time, in milliseconds.|
**Return value**
| Type | Description |
| -------------- | ------------------- |
| Promise\<AbilityStage> | Promise used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned.|
**Example**
```js
var abilityDelegator;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor).then((data : any) => {
console.info("waitAbilityStageMonitor promise");
});
```
### waitAbilityStageMonitor<sup>9+</sup>
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\<AbilityStage>): void;
Waits a period of time for an **AbilityStage** instance that matches the conditions set in an **AbilityStageMonitor** instance and returns the **AbilityStage** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.|
| timeout | number | No | Maximum waiting time, in milliseconds.|
| callback | AsyncCallback\<AbilityStage> | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. |
**Example**
```js
var abilityDelegator;
var timeout = 100;
function onAbilityCreateCallback(data) {
console.info("onAbilityCreateCallback");
}
var monitor = {
moduleName: "moduleName",
srcEntrance: "srcEntrance",
}
abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator();
abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : any) => {
console.info("waitAbilityStageMonitor callback");
});
```
## AbilityStageMonitor
Provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Type | Readable| Writable| Description |
| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ |
| moduleName<sup>9+</sup> | string | Yes | Yes | Module name of the **AbilityStage** instance.|
| srcEntrance<sup>9+</sup> | string | Yes | Yes | Source path of the **AbilityStage** instance.|
...@@ -11,7 +11,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi ...@@ -11,7 +11,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi
The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**.
```js ```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments(); var args = AbilityDelegatorRegistry.getArguments();
``` ```
......
...@@ -89,6 +89,31 @@ Called when the global configuration is updated. ...@@ -89,6 +89,31 @@ Called when the global configuration is updated.
} }
} }
``` ```
## AbilityStage.onMemoryLevel
onMemoryLevel(level: AbilityConstant.MemoryLevel): void;
Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.|
**Example**
```js
class MyAbilityStage extends AbilityStage {
onMemoryLevel(level) {
console.log('onMemoryLevel, level:' + JSON.stringify(level));
}
}
```
## AbilityStage.context ## AbilityStage.context
context: AbilityStageContext; context: AbilityStageContext;
......
...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.| | Promise&lt;number&gt; | Size of the application memory.|
**Example** **Example**
...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.| | callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.|
**Example** **Example**
...@@ -157,14 +157,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -157,14 +157,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb
``` ```
## appManager.getProcessRunningInfos<sup>(deprecated)</sup> ## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9) instead.
getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>; getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>;
Obtains information about the running processes. This API uses a promise to return the result. Obtains information about the running processes. This API uses a promise to return the result.
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9) instead.
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -187,14 +185,12 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -187,14 +185,12 @@ Obtains information about the running processes. This API uses a promise to retu
## appManager.getProcessRunningInfos<sup>(deprecated)</sup> ## appManager.getProcessRunningInfos<sup>(deprecated)</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9-1) instead.
getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): void; getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): void;
Obtains information about the running processes. This API uses an asynchronous callback to return the result. Obtains information about the running processes. This API uses an asynchronous callback to return the result.
> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation<sup>9+</sup>](#appmanagergetprocessrunninginformation9-1) instead.
**Required permissions**: ohos.permission.GET_RUNNING_INFO **Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -228,7 +224,7 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -228,7 +224,7 @@ Obtains information about the running processes. This API uses a promise to retu
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<Array\<ProcessRunningInformation>> | Promise used to return the process information.| | Promise\<Array\<[ProcessRunningInformation](#processrunninginformation)>> | Promise used to return the process information.|
**Example** **Example**
...@@ -254,7 +250,7 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -254,7 +250,7 @@ Obtains information about the running processes. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<ProcessRunningInformation>> | No| Callback used to return the process information.| | callback | AsyncCallback\<Array\<[ProcessRunningInformation](#processrunninginformation)>> | No| Callback used to return the process information.|
**Example** **Example**
...@@ -269,7 +265,7 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -269,7 +265,7 @@ Obtains information about the running processes. This API uses an asynchronous c
registerApplicationStateObserver(observer: ApplicationStateObserver): number; registerApplicationStateObserver(observer: ApplicationStateObserver): number;
Registers an observer to listen for the state of all applications. Registers an observer to listen for the state changes of all applications.
**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
...@@ -307,9 +303,9 @@ Registers an observer to listen for the state of all applications. ...@@ -307,9 +303,9 @@ Registers an observer to listen for the state of all applications.
## appManager.registerApplicationStateObserver<sup>9+</sup> ## appManager.registerApplicationStateObserver<sup>9+</sup>
registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array<string>): number; registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\<string>): number;
Registers an observer to listen for the state of a specified application. Registers an observer to listen for the state changes of a specified application.
**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER
...@@ -322,7 +318,7 @@ Registers an observer to listen for the state of a specified application. ...@@ -322,7 +318,7 @@ Registers an observer to listen for the state of a specified application.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| | observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.|
| bundleNameList | Array<string> | No| **bundleName** array to be registered for listening. The maximum value is 128.| | bundleNameList | Array<string> | No| **bundleName** array of the application. A maximum of 128 bundle names can be passed.|
**Example** **Example**
...@@ -359,7 +355,7 @@ Deregisters the application state observer. This API uses an asynchronous callba ...@@ -359,7 +355,7 @@ Deregisters the application state observer. This API uses an asynchronous callba
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| observerId | number | No| Numeric code of the observer.| | observerId | number | No| Numeric code of the observer.|
...@@ -491,10 +487,10 @@ Kills a process by bundle name and account ID. This API uses a promise to return ...@@ -491,10 +487,10 @@ Kills a process by bundle name and account ID. This API uses a promise to return
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.| | bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
**Example** **Example**
...@@ -525,11 +521,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal ...@@ -525,11 +521,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | string | Yes| Bundle name of an application.| | bundleName | string | Yes| Bundle name of an application.|
| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).|
| callback | AsyncCallback\<void\> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -708,9 +704,14 @@ Called when the application state changes. ...@@ -708,9 +704,14 @@ Called when the application state changes.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const foregroundApplicationInfo = ApplicationStateObserver.onForegroundApplicationChanged(); onForegroundApplicationChanged(appStateData) {
console.log('-------- foregroundApplicationInfo: ---------', foregroundApplicationInfo); console.log('------------ onForegroundApplicationChanged -----------', appStateData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onAbilityStateChanged<sup>8+</sup> ## ApplicationStateObserver.onAbilityStateChanged<sup>8+</sup>
...@@ -732,9 +733,13 @@ Called when the ability state changes. ...@@ -732,9 +733,13 @@ Called when the ability state changes.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const abilityStateChangedInfo = ApplicationStateObserver.onAbilityStateChanged(); onAbilityStateChanged(abilityStateData) {
console.log('-------- abilityStateChangedInfo: ---------', abilityStateChangedInfo); console.log('------------ onAbilityStateChanged -----------', abilityStateData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onProcessCreated<sup>8+</sup> ## ApplicationStateObserver.onProcessCreated<sup>8+</sup>
...@@ -756,9 +761,13 @@ Called when a process is created. ...@@ -756,9 +761,13 @@ Called when a process is created.
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const processCreatedInfo = ApplicationStateObserver.onProcessCreated(); onProcessCreated(processData) {
console.log('-------- processCreatedInfo: ---------', processCreatedInfo); console.log('------------ onProcessCreated -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## ApplicationStateObserver.onProcessDied<sup>8+</sup> ## ApplicationStateObserver.onProcessDied<sup>8+</sup>
...@@ -775,14 +784,46 @@ Called when a process is terminated. ...@@ -775,14 +784,46 @@ Called when a process is terminated.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| processData | ProcessData | No| Process information.| | processData | [ProcessData](#processdata) | No| Process information.|
**Example** **Example**
```js ```js
import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' var applicationStateObserver = {
const processDiedInfo = ApplicationStateObserver.onProcessDied(); onProcessDied(processData) {
console.log('-------- processDiedInfo: ---------', processDiedInfo); console.log('------------ onProcessDied -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
```
## ApplicationStateObserver.onProcessStateChanged<sup>9+</sup>
onProcessStateChanged(processData: ProcessData): void;
Called when the process state changes.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| processData | [ProcessData](#processdata) | No| Process information.|
**Example**
```js
var applicationStateObserver = {
onProcessStateChanged(processData) {
console.log('------------ onProcessStateChanged -----------', processData);
}
}
const observerCode = app.registerApplicationStateObserver(applicationStateObserver);
console.log('-------- observerCode: ---------', observerCode);
``` ```
## AppStateData ## AppStateData
...@@ -815,7 +856,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -815,7 +856,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
## ProcessData ## ProcessData
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission **System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
...@@ -824,19 +865,19 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -824,19 +865,19 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
| pid<sup>8+</sup> | number | Yes | No | Process ID. | | pid<sup>8+</sup> | number | Yes | No | Process ID. |
| bundleName<sup>8+</sup> | string | Yes | No | Bundle name of an application. | | bundleName<sup>8+</sup> | string | Yes | No | Bundle name of an application. |
| uid<sup>8+</sup> | number | Yes | No | User ID. | | uid<sup>8+</sup> | number | Yes | No | User ID. |
| isContinuousTask<sup>9+</sup> | boolean | Yes | No | Whether the process is a continuous task. |
| isKeepAlive<sup>9+</sup> | boolean | Yes | No | Whether the process remains active. |
## ProcessRunningInfo ## ProcessRunningInfo
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name | Readable/Writable| Type | Mandatory| Description | | Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| pid<sup>9+</sup> | Read only | number | No | Process ID. | | pid<sup>8+</sup> | Read only | number | No | Process ID. |
| uid<sup>9+</sup> | Read only | number | No | User ID.| | uid<sup>8+</sup> | Read only | number | No | User ID.|
| processName<sup>9+</sup> | Read only | string | No | Process name.| | processName<sup>8+</sup> | Read only | string | No | Process name.|
| bundleNames<sup>9+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.| | bundleNames<sup>8+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.|
## ApplicationStateObserver ## ApplicationStateObserver
...@@ -850,3 +891,44 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ...@@ -850,3 +891,44 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo);
| [onAbilityStateChanged<sup>8+</sup>](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. | | [onAbilityStateChanged<sup>8+</sup>](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\<void> | Yes | No | Callback invoked when the ability state changes. |
| [onProcessCreated<sup>8+</sup>](#applicationstateobserveronprocesscreated8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. | | [onProcessCreated<sup>8+</sup>](#applicationstateobserveronprocesscreated8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is created. |
| [onProcessDied<sup>8+</sup>](#applicationstateobserveronprocessdied8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. | | [onProcessDied<sup>8+</sup>](#applicationstateobserveronprocessdied8) | AsyncCallback\<void> | Yes | No | Callback invoked when a process is destroyed. |
## ProcessRunningInformation
Defines the process running information.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| pid<sup>9+</sup> | Read only | number | No | Process ID. |
| uid<sup>9+</sup> | Read only | number | No | User ID.|
| processName<sup>9+</sup> | Read only | string | No | Process name.|
| bundleNames<sup>9+</sup> | Read only | Array\<string> | No | **bundleName** array in the running processes.|
## ApplicationState<sup>9+</sup>
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Value | Description |
| -------------------- | --- | --------------------------------- |
| STATE_CREATE | 1 | State indicating that the application is being created. |
| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. |
| STATE_ACTIVE | 3 | State indicating that the application is active. |
| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. |
| STATE_DESTROY | 5 | State indicating that the application is destroyed. |
## ProcessState<sup>9+</sup>
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Value | Description |
| -------------------- | --- | --------------------------------- |
| STATE_CREATE | 1 | State indicating that the process is being created. |
| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. |
| STATE_ACTIVE | 3 | State indicating that the process is active. |
| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. |
| STATE_DESTROY | 5 | State indicating that the process is destroyed. |
...@@ -12,6 +12,9 @@ When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is mor ...@@ -12,6 +12,9 @@ When compared with **[LinkedList](js-apis-linkedlist.md)**, **ArrayList** is mor
**Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read. **Recommended use case**: Use **ArrayList** when elements in a container need to be frequently read.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ Adds an element at the end of this container. ...@@ -72,7 +75,7 @@ Adds an element at the end of this container.
let result1 = arrayList.add(1); let result1 = arrayList.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
let result2 = arrayList.add(b); let result2 = arrayList.add(b);
let c = {name: "lala", age: "13"}; let c = {name: "Dylon", age: "13"};
let result3 = arrayList.add(false); let result3 = arrayList.add(false);
``` ```
...@@ -124,9 +127,9 @@ Checks whether this container has the specified element. ...@@ -124,9 +127,9 @@ Checks whether this container has the specified element.
```ts ```ts
let arrayList = new ArrayList(); let arrayList = new ArrayList();
let result = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = arrayList.has("squirrel");
arrayList.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); arrayList.add("squirrel");
let result1 = arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = arrayList.has("squirrel");
``` ```
### getIndexOf ### getIndexOf
...@@ -361,7 +364,7 @@ arrayList.add(4); ...@@ -361,7 +364,7 @@ arrayList.add(4);
arrayList.add(5); arrayList.add(5);
arrayList.add(4); arrayList.add(4);
arrayList.forEach((value, index) => { arrayList.forEach((value, index) => {
console.log("value:" + value, index); console.log(`value:${value}`, index);
}); });
``` ```
...@@ -623,14 +626,14 @@ arrayList.add(4); ...@@ -623,14 +626,14 @@ arrayList.add(4);
// Method 1: // Method 1:
for (let item of arrayList) { for (let item of arrayList) {
console.log("value:" + item); console.log(`value:${item}`);
} }
// Method 2: // Method 2:
let iter = arrayList[Symbol.iterator](); let iter = arrayList[Symbol.iterator]();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
console.log("value:" + temp); console.log(`value:${temp}`);
temp = iter.next().value; temp = iter.next().value;
} }
``` ```
# ExtensionAbilityInfo # ExtensionAbilityInfo
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through [getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfo), and flags are obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md#bundleflag).
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. 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 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **ExtensionAbilityInfo** module provides Extension ability information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## ExtensionAbilityInfo ## ExtensionAbilityInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
# LauncherAbilityInfo # LauncherAbilityInfo
The **LauncherAbilityInfo** module provides information about a launcher ability. The **LauncherAbilityInfo** module provides information about the launcher ability, which is obtained through [innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager.md).
> **NOTE** > **NOTE**
> >
...@@ -12,8 +12,8 @@ The **LauncherAbilityInfo** module provides information about a launcher ability ...@@ -12,8 +12,8 @@ The **LauncherAbilityInfo** module provides information about a launcher ability
**System API**: This is a system API and cannot be called by third-party applications. **System API**: This is a system API and cannot be called by third-party applications.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.|
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. |
| labelId | number | Yes | No | Label ID of the launcher ability. | | labelId | number | Yes | No | Label ID of the launcher ability. |
......
# ShortcutInfo # ShortcutInfo
The **ShortcutInfo** module provides shortcut information defined in the configuration file. The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute).
> **NOTE** > **NOTE**
> >
......
...@@ -824,11 +824,8 @@ This is a system API. ...@@ -824,11 +824,8 @@ This is a system API.
**Example** **Example**
```js ```js
let promise = call.reject(1); call.reject(1, (error, data) => {
promise.then(data => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
console.log(`reject success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`reject fail, promise: err->${JSON.stringify(err)}`);
}); });
``` ```
......
...@@ -812,7 +812,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t ...@@ -812,7 +812,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------ | ---- | ------------------------ | | -------- | ------------------------------ | ---- | ------------------------ |
| callback | AsyncCallback<Array<number\>\> | Yes | Callback used to return the result.| | callback | AsyncCallback<Array<number\>\> | Yes | Callback used to return an array containing the minimum and maximum zoom ratios.|
**Example** **Example**
...@@ -838,7 +838,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result. ...@@ -838,7 +838,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------------------ | ------------------------------------------- | | ------------------------ | ------------------------------------------- |
| Promise<Array<number\>\> | Promise used to return the zoom ratio range.| | Promise<Array<number\>\> | Promise used to return an array containing the minimum and maximum zoom ratios.|
**Example** **Example**
......
...@@ -66,15 +66,11 @@ Provides the event types supported by the **CommonEvent** module. The name and v ...@@ -66,15 +66,11 @@ Provides the event types supported by the **CommonEvent** module. The name and v
| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | | COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. |
| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | | COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. |
| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | | COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. |
| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | Indicates the common event that user switching is happening. | | COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. |
| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be started. | | COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. |
| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | | COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. |
| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be stopped. | | COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. |
| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | | COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. |
| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | Indicates the common event about a HUAWEI ID login. |
| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | Indicates the common event about a HUAWEI ID logout. |
| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | Indicates the common event that the HUAWEI ID is invalid. |
| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | Indicates the common event about a HUAWEI ID logoff. |
| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | | COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. |
| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | | COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. |
| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | | COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. |
...@@ -133,8 +129,8 @@ Provides the event types supported by the **CommonEvent** module. The name and v ...@@ -133,8 +129,8 @@ Provides the event types supported by the **CommonEvent** module. The name and v
| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | | COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. |
| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | | COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. |
| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | | COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. |
| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been added to the system. | | COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. |
| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been removed from the system. | | COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. |
| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | | COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. |
| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | | COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. |
| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | | COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. |
......
...@@ -12,6 +12,9 @@ Double-ended queue (deque) is a sequence container implemented based on the queu ...@@ -12,6 +12,9 @@ Double-ended queue (deque) is a sequence container implemented based on the queu
**Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container. **Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -64,7 +67,7 @@ deque.insertFront("a"); ...@@ -64,7 +67,7 @@ deque.insertFront("a");
deque.insertFront(1); deque.insertFront(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
deque.insertFront(b); deque.insertFront(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
deque.insertFront(false); deque.insertFront(false);
``` ```
...@@ -90,7 +93,7 @@ deque.insertEnd("a"); ...@@ -90,7 +93,7 @@ deque.insertEnd("a");
deque.insertEnd(1); deque.insertEnd(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
deque.insertEnd(b); deque.insertEnd(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
deque.insertEnd(false); deque.insertEnd(false);
``` ```
...@@ -118,9 +121,9 @@ Checks whether this container has the specified element. ...@@ -118,9 +121,9 @@ Checks whether this container has the specified element.
```ts ```ts
let deque = new Deque(); let deque = new Deque();
let result = deque.has("Ahfbrgrbgnutfodgorrogorg"); let result = deque.has("squirrel");
deque.insertFront("Ahfbrgrbgnutfodgorrogorg"); deque.insertFront("squirrel");
let result1 = deque.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = deque.has("squirrel");
``` ```
### popFirst ### popFirst
......
...@@ -21,12 +21,13 @@ Obtains a **DistributedAccountAbility** instance. ...@@ -21,12 +21,13 @@ Obtains a **DistributedAccountAbility** instance.
**System capability**: SystemCapability.Account.OsAccount **System capability**: SystemCapability.Account.OsAccount
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
``` ```
...@@ -45,12 +46,13 @@ Obtains distributed account information. This API uses an asynchronous callback ...@@ -45,12 +46,13 @@ Obtains distributed account information. This API uses an asynchronous callback
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the distributed account information obtained.| | callback | AsyncCallback&lt;[DistributedInfo](#distributedinfo)&gt; | Yes| Callback invoked to return the distributed account information obtained.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
accountAbility.queryOsAccountDistributedInfo((err, data) => { accountAbility.queryOsAccountDistributedInfo((err, data) => {
...@@ -70,12 +72,13 @@ Obtains distributed account information. This API uses a promise to return the r ...@@ -70,12 +72,13 @@ Obtains distributed account information. This API uses a promise to return the r
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[DistributedInfo](#distributedinfo)&gt; | Promise used to return the distributed account information obtained.| | Promise&lt;[DistributedInfo](#distributedinfo)&gt; | Promise used to return the distributed account information obtained.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
accountAbility.queryOsAccountDistributedInfo().then((data) => { accountAbility.queryOsAccountDistributedInfo().then((data) => {
...@@ -96,13 +99,14 @@ Updates distributed account information. This API uses an asynchronous callback ...@@ -96,13 +99,14 @@ Updates distributed account information. This API uses an asynchronous callback
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked when the distributed account information is updated.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked when the distributed account information is updated.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'};
...@@ -121,17 +125,19 @@ Updates distributed account information. This API uses a promise to return the r ...@@ -121,17 +125,19 @@ Updates distributed account information. This API uses a promise to return the r
**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.|
- Return value **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
- Example **Example**
```js ```js
const accountAbility = account_distributedAccount.getDistributedAccountAbility(); const accountAbility = account_distributedAccount.getDistributedAccountAbility();
let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'};
......
...@@ -4,7 +4,7 @@ The **EffectKit** module provides basic image processing capabilities, including ...@@ -4,7 +4,7 @@ The **EffectKit** module provides basic image processing capabilities, including
This module provides the following classes: This module provides the following classes:
- [Filter](#filter): a class that provides the effect chain. - [Filter](#filter): a class that provides the effect chain, which is a linked list of image processing effects.
- [Color](#color): a class used to store the color picked. - [Color](#color): a class used to store the color picked.
- [ColorPicker](#colorpicker): a smart color picker. - [ColorPicker](#colorpicker): a smart color picker.
...@@ -155,7 +155,7 @@ Obtains the main color of the image and writes the result to a **[Color](#color) ...@@ -155,7 +155,7 @@ Obtains the main color of the image and writes the result to a **[Color](#color)
```js ```js
colorPicker.getMainColor().then(color => { colorPicker.getMainColor().then(color => {
console.log('Succeeded in getting main color.'); console.log('Succeeded in getting main color.');
console.info("color[ARGB]=" + color.alpha + "," + color.red + "," + color.green + "," + color.blue); console.info(`color[ARGB]=${color.alpha},${color.red},${color.green},${color.blue}`);
}).catch(error => { }).catch(error => {
console.log('Failed to get main color.'); console.log('Failed to get main color.');
}) })
......
...@@ -22,6 +22,7 @@ Obtains information about the root album or directory in asynchronous mode. This ...@@ -22,6 +22,7 @@ Obtains information about the root album or directory in asynchronous mode. This
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| options | Object | No| The options are as follows:<br>- &nbsp;**dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.| | options | Object | No| The options are as follows:<br>- &nbsp;**dev**: See [DevInfo](#devinfo). It is **dev = {name: "local"}** by default if not specified. Currently, only 'local' is supported.|
...@@ -83,6 +84,7 @@ Obtains information about the second-level album or files in asynchronous mode. ...@@ -83,6 +84,7 @@ Obtains information about the second-level album or files in asynchronous mode.
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| path | string | Yes| URI of the directory to query.| | path | string | Yes| URI of the directory to query.|
...@@ -169,6 +171,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi ...@@ -169,6 +171,7 @@ Creates a file in the specified path in asynchronous mode. This API uses a promi
**System capability**: SystemCapability.FileManagement.UserFileService **System capability**: SystemCapability.FileManagement.UserFileService
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| --- | --- | --- | -- | | --- | --- | --- | -- |
| filename | string | Yes| Name of the file to create.| | filename | string | Yes| Name of the file to create.|
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **FormInfo** module provides widget information and state. The **FormInfo** module provides widget information and state.
> **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.
## Modules to Import ## Modules to Import
...@@ -120,3 +120,14 @@ Enumerates the widget dimensions. ...@@ -120,3 +120,14 @@ Enumerates the widget dimensions.
| Dimension_2_4<sup>9+</sup> | 3 | 2 x 4. | | Dimension_2_4<sup>9+</sup> | 3 | 2 x 4. |
| Dimension_4_4<sup>9+</sup> | 4 | 4 x 4. | | Dimension_4_4<sup>9+</sup> | 4 | 4 x 4. |
| Dimension_2_1<sup>9+</sup> | 5 | 2 x 1. | | Dimension_2_1<sup>9+</sup> | 5 | 2 x 1. |
## FormInfoFilter
Defines the widget information filter. Only the widget information that meets the filter is returned.
**System capability**: SystemCapability.Ability.Form
| Name | Yes | Description |
| ----------- | ---- | ------------ |
| moduleName<sup>9+</sup> | No | Module name.|
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release.
> **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.
## Modules to Import ## Modules to Import
...@@ -183,7 +183,7 @@ Obtains the application's widget information that meets a filter criterion on th ...@@ -183,7 +183,7 @@ Obtains the application's widget information that meets a filter criterion on th
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | Yes| Filter criterion.| | filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md#forminfofilter) | Yes| Filter criterion.|
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the widget information.| | callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | Yes| Callback used to return the widget information.|
**Example** **Example**
...@@ -214,7 +214,7 @@ Obtains the application's widget information on the device. This API uses a prom ...@@ -214,7 +214,7 @@ Obtains the application's widget information on the device. This API uses a prom
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | No| Filter criterion.| | filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md) | No| Filter criterion.|
**Return value** **Return value**
......
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
**Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs. **Recommended use case**: Use **HashMap** when you need to quickly access, remove, and insert key-value pairs.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -90,9 +94,9 @@ Checks whether this container contains the specified key. ...@@ -90,9 +94,9 @@ Checks whether this container contains the specified key.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashMap.hasKey("squirrel");
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
let result1 = hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = hashMap.hasKey("squirrel");
``` ```
...@@ -121,7 +125,7 @@ Checks whether this container contains the specified value. ...@@ -121,7 +125,7 @@ Checks whether this container contains the specified value.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.hasValue(123); let result = hashMap.hasValue(123);
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
let result1 = hashMap.hasValue(123); let result1 = hashMap.hasValue(123);
``` ```
...@@ -150,9 +154,9 @@ Obtains the value of the specified key in this container. ...@@ -150,9 +154,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let result = hashMap.get("sdfs"); let result = hashMap.get("sparrow");
``` ```
...@@ -174,8 +178,8 @@ Adds all elements in a **HashMap** instance to this container. ...@@ -174,8 +178,8 @@ Adds all elements in a **HashMap** instance to this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let newHashMap = new HashMap(); let newHashMap = new HashMap();
hashMap.setAll(newHashMap); hashMap.setAll(newHashMap);
``` ```
...@@ -194,7 +198,7 @@ Adds an element to this container. ...@@ -194,7 +198,7 @@ Adds an element to this container.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| key | K | Yes| Key of the target element.| | key | K | Yes| Key of the target element.|
| value | V | Yes| Value of the element.| | value | V | Yes| Value of the target element.|
**Return value** **Return value**
...@@ -206,7 +210,7 @@ Adds an element to this container. ...@@ -206,7 +210,7 @@ Adds an element to this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
let result = hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); let result = hashMap.set("squirrel", 123);
``` ```
...@@ -234,9 +238,9 @@ Removes an element with the specified key from this container. ...@@ -234,9 +238,9 @@ Removes an element with the specified key from this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let result = hashMap.remove("sdfs"); let result = hashMap.remove("sparrow");
``` ```
...@@ -252,8 +256,8 @@ Clears this container and sets its length to **0**. ...@@ -252,8 +256,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
hashMap.clear(); hashMap.clear();
``` ```
...@@ -276,8 +280,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -276,8 +280,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.keys(); let iter = hashMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -305,8 +309,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -305,8 +309,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.values(); let iter = hashMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -341,8 +345,8 @@ Replaces an element in this container. ...@@ -341,8 +345,8 @@ Replaces an element in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("sdfs", 123); hashMap.set("sparrow", 123);
let result = hashMap.replace("sdfs", 357); let result = hashMap.replace("sparrow", 357);
``` ```
...@@ -372,8 +376,8 @@ callbackfn ...@@ -372,8 +376,8 @@ callbackfn
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("sdfs", 123); hashMap.set("sparrow", 123);
hashMap.set("dfsghsf", 357); hashMap.set("gull", 357);
hashMap.forEach((value, key) => { hashMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -398,8 +402,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -398,8 +402,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
let iter = hashMap.entries(); let iter = hashMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -427,8 +431,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -427,8 +431,8 @@ Obtains an iterator, each item of which is a JavaScript object.
**Example** **Example**
```ts ```ts
let hashMap = new HashMap(); let hashMap = new HashMap();
hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); hashMap.set("squirrel", 123);
hashMap.set("sdfs", 356); hashMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of hashMap) { for (let item of hashMap) {
......
...@@ -10,6 +10,9 @@ Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted o ...@@ -10,6 +10,9 @@ Unlike [TreeSet](js-apis-treeset.md), which stores and accesses data in sorted o
**Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set. **Recommended use case**: Use **HashSet** when you need a set that has only unique elements or need to deduplicate a set.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -26,6 +29,17 @@ import HashSet from '@ohos.util.HashSet'; ...@@ -26,6 +29,17 @@ import HashSet from '@ohos.util.HashSet';
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| length | number | Yes| No| Number of elements in a hash set (called container later).| | length | number | Yes| No| Number of elements in a hash set (called container later).|
**Example**
```ts
let hashSet = new HashSet();
hashSet.add(1);
hashSet.add(2);
hashSet.add(3);
hashSet.add(4);
hashSet.add(5);
let res = hashSet.length;
```
### constructor ### constructor
...@@ -88,9 +102,9 @@ Checks whether this container contains the specified element. ...@@ -88,9 +102,9 @@ Checks whether this container contains the specified element.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
let result = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashSet.has("squirrel");
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
let result1 = hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = hashSet.has("squirrel");
``` ```
...@@ -118,7 +132,7 @@ Adds an element to this container. ...@@ -118,7 +132,7 @@ Adds an element to this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
let result = hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = hashSet.add("squirrel");
``` ```
...@@ -146,9 +160,9 @@ Removes an element from this container. ...@@ -146,9 +160,9 @@ Removes an element from this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let result = hashSet.remove("sdfs"); let result = hashSet.remove("sparrow");
``` ```
...@@ -164,8 +178,8 @@ Clears this container and sets its length to **0**. ...@@ -164,8 +178,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
hashSet.clear(); hashSet.clear();
``` ```
...@@ -188,8 +202,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -188,8 +202,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let iter = hashSet.values(); let iter = hashSet.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -225,8 +239,8 @@ callbackfn ...@@ -225,8 +239,8 @@ callbackfn
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("sdfs"); hashSet.add("sparrow");
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.forEach((value, key) => { hashSet.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -250,8 +264,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -250,8 +264,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
let iter = hashSet.entries(); let iter = hashSet.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -280,8 +294,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -280,8 +294,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let hashSet = new HashSet(); let hashSet = new HashSet();
hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); hashSet.add("squirrel");
hashSet.add("sdfs"); hashSet.add("sparrow");
// Method 1: // Method 1:
for (let item of hashSet) { for (let item of hashSet) {
......
...@@ -115,7 +115,7 @@ const readBuffer = new ArrayBuffer(96); ...@@ -115,7 +115,7 @@ const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then(() => { pixelmap.readPixelsToBuffer(readBuffer).then(() => {
console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. console.log('Succeeded in reading image pixel data.'); // Called if the condition is met.
}).catch(error => { }).catch(error => {
('Failed to read image pixel data.'); // Called if no condition is met. console.log('Failed to read image pixel data.'); // Called if no condition is met.
}) })
``` ```
...@@ -261,12 +261,7 @@ image.createPixelMap(color, opts) ...@@ -261,12 +261,7 @@ image.createPixelMap(color, opts)
} }
pixelmap.writePixels(area).then(() => { pixelmap.writePixels(area).then(() => {
const readArea = { pixels: new ArrayBuffer(8), console.info('Succeeded to write pixelmap into the specified area.');
offset: 0,
stride: 8,
// region.size.width + x < opts.width, region.size.height + y < opts.height
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
}) })
}).catch(error => { }).catch(error => {
console.log('error: ' + error); console.log('error: ' + error);
...@@ -291,17 +286,20 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t ...@@ -291,17 +286,20 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t
**Example** **Example**
```js ```js
const area = new ArrayBuffer(400); const area = { pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
let bufferArr = new Uint8Array(area.pixels);
for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writePixels(area, (error) => { pixelmap.writePixels(area, (error) => {
if (error != undefined) { if (error != undefined) {
console.info('Failed to write pixelmap into the specified area.'); console.info('Failed to write pixelmap into the specified area.');
} else { } else {
const readArea = { console.info('Succeeded to write pixelmap into the specified area.');
pixels: new ArrayBuffer(20),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 },
}
} }
}) })
``` ```
...@@ -330,9 +328,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ...@@ -330,9 +328,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color); let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color).then(() => { for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color).then(() => {
console.log("Succeeded in writing data from a buffer to a PixelMap."); console.log("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((err) => { }).catch((err) => {
console.error("Failed to write data from a buffer to a PixelMap."); console.error("Failed to write data from a buffer to a PixelMap.");
...@@ -358,9 +358,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ...@@ -358,9 +358,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj
```js ```js
const color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color); let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color, function(err) { for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color, function(err) {
if (err) { if (err) {
console.error("Failed to write data from a buffer to a PixelMap."); console.error("Failed to write data from a buffer to a PixelMap.");
return; return;
...@@ -387,12 +389,22 @@ Obtains pixel map information of this image. This API uses a promise to return t ...@@ -387,12 +389,22 @@ Obtains pixel map information of this image. This API uses a promise to return t
**Example** **Example**
```js ```js
const pixelMap = new ArrayBuffer(400); const color = new ArrayBuffer(96);
pixelMap.getImageInfo().then(function(info) { let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } }
console.log("Succeeded in obtaining the image pixel map information."); image.createPixelMap(color, opts).then(pixelmap => {
}).catch((err) => { globalpixelmap = pixelmap;
console.error("Failed to obtain the image pixel map information."); if (pixelmap == undefined) {
}); console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo().then(imageInfo => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
})
``` ```
### getImageInfo<sup>7+</sup> ### getImageInfo<sup>7+</sup>
...@@ -412,8 +424,21 @@ Obtains pixel map information of this image. This API uses an asynchronous callb ...@@ -412,8 +424,21 @@ Obtains pixel map information of this image. This API uses an asynchronous callb
**Example** **Example**
```js ```js
pixelmap.getImageInfo((imageInfo) => { const color = new ArrayBuffer(96);
console.log("Succeeded in obtaining the image pixel map information."); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
if (pixelmap == undefined) {
globalpixelmap = pixelmap;
console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo((err, imageInfo) => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
}) })
``` ```
...@@ -500,9 +525,15 @@ Sets an opacity rate for this image pixel map. This API uses an asynchronous cal ...@@ -500,9 +525,15 @@ Sets an opacity rate for this image pixel map. This API uses an asynchronous cal
**Example** **Example**
```js ```js
async function () { var rate = 0.5;
await pixelMap.opacity(0.5); pixelmap.opacity(rate, (err) => {
} if (err) {
console.error("Failed to set opacity.");
return;
} else {
console.log("Succeeded in setting opacity.");
}
})
``` ```
### opacity<sup>9+</sup> ### opacity<sup>9+</sup>
...@@ -529,7 +560,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return ...@@ -529,7 +560,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return
```js ```js
async function () { async function () {
await pixelMap.opacity(0.5); var rate = 0.5;
await pixelmap.opacity(rate);
} }
``` ```
...@@ -550,12 +582,8 @@ Creates a **PixelMap** object that contains only the alpha channel information. ...@@ -550,12 +582,8 @@ Creates a **PixelMap** object that contains only the alpha channel information.
**Example** **Example**
```js ```js
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { async function () {
if (alphaPixelMap == undefined) { await pixelmap.createAlphaPixelmap();
console.info('Failed to obtain new pixel map.');
} else {
console.info('Succeed in obtaining new pixel map.');
}
}) })
``` ```
...@@ -576,14 +604,13 @@ Creates a **PixelMap** object that contains only the alpha channel information. ...@@ -576,14 +604,13 @@ Creates a **PixelMap** object that contains only the alpha channel information.
**Example** **Example**
```js ```js
let pixelMap = await imageSource.createPixelMap(); pixelmap.createAlphaPixelmap((err, alphaPixelMap) => {
if (pixelMap != undefined) { if (alphaPixelMap == undefined) {
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { console.info('Failed to obtain new pixel map.');
console.info('Failed to obtain new pixel map.'); } else {
}) console.info('Succeed in obtaining new pixel map.');
} else { }
console.info('Succeed in obtaining new pixel map.'); })
}
``` ```
### scale<sup>9+</sup> ### scale<sup>9+</sup>
...@@ -606,7 +633,7 @@ Scales this image based on the input width and height. This API uses an asynchro ...@@ -606,7 +633,7 @@ Scales this image based on the input width and height. This API uses an asynchro
```js ```js
async function () { async function () {
await pixelMap.scale(2.0, 1.0); await pixelmap.scale(2.0, 1.0);
} }
``` ```
...@@ -635,7 +662,7 @@ Scales this image based on the input width and height. This API uses a promise t ...@@ -635,7 +662,7 @@ Scales this image based on the input width and height. This API uses a promise t
```js ```js
async function () { async function () {
await pixelMap.scale(2.0, 1.0); await pixelmap.scale(2.0, 1.0);
} }
``` ```
...@@ -659,7 +686,7 @@ Translates this image based on the input coordinates. This API uses an asynchron ...@@ -659,7 +686,7 @@ Translates this image based on the input coordinates. This API uses an asynchron
```js ```js
async function () { async function () {
await pixelMap.translate(3.0, 1.0); await pixelmap.translate(3.0, 1.0);
} }
``` ```
...@@ -688,7 +715,7 @@ Translates this image based on the input coordinates. This API uses a promise to ...@@ -688,7 +715,7 @@ Translates this image based on the input coordinates. This API uses a promise to
```js ```js
async function () { async function () {
await pixelMap.translate(3.0, 1.0); await pixelmap.translate(3.0, 1.0);
} }
``` ```
...@@ -711,7 +738,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb ...@@ -711,7 +738,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb
```js ```js
async function () { async function () {
await pixelMap.rotate(90.0); await pixelmap.rotate(90.0);
} }
``` ```
...@@ -739,7 +766,7 @@ Rotates this image based on the input angle. This API uses a promise to return t ...@@ -739,7 +766,7 @@ Rotates this image based on the input angle. This API uses a promise to return t
```js ```js
async function () { async function () {
await pixelMap.rotate(90.0); await pixelmap.rotate(90.0);
} }
``` ```
...@@ -763,7 +790,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron ...@@ -763,7 +790,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron
```js ```js
async function () { async function () {
await pixelMap.flip(false, true); await pixelmap.flip(false, true);
} }
``` ```
...@@ -792,7 +819,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to ...@@ -792,7 +819,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to
```js ```js
async function () { async function () {
await pixelMap.flip(false, true); await pixelmap.flip(false, true);
} }
``` ```
...@@ -815,7 +842,7 @@ Crops this image based on the input size. This API uses an asynchronous callback ...@@ -815,7 +842,7 @@ Crops this image based on the input size. This API uses an asynchronous callback
```js ```js
async function () { async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -843,7 +870,7 @@ Crops this image based on the input size. This API uses a promise to return the ...@@ -843,7 +870,7 @@ Crops this image based on the input size. This API uses a promise to return the
```js ```js
async function () { async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
} }
``` ```
...@@ -954,7 +981,8 @@ Creates an **ImageSource** instance based on the URI. ...@@ -954,7 +981,8 @@ Creates an **ImageSource** instance based on the URI.
**Example** **Example**
```js ```js
const imageSourceApi = image.createImageSource('/sdcard/test.jpg'); var sourceOptions = { sourceDensity: 120 };
let imageSource = image.createImageSource('test.png', sourceOptions);
``` ```
## image.createImageSource<sup>7+</sup> ## image.createImageSource<sup>7+</sup>
...@@ -1007,7 +1035,8 @@ Creates an **ImageSource** instance based on the file descriptor. ...@@ -1007,7 +1035,8 @@ Creates an **ImageSource** instance based on the file descriptor.
**Example** **Example**
```js ```js
const imageSourceApi = image.createImageSource(fd); var sourceOptions = { sourceDensity: 120 };
const imageSourceApi = image.createImageSource(0, sourceOptions);
``` ```
## image.createImageSource<sup>9+</sup> ## image.createImageSource<sup>9+</sup>
...@@ -1059,9 +1088,9 @@ const data = new ArrayBuffer(112); ...@@ -1059,9 +1088,9 @@ const data = new ArrayBuffer(112);
const imageSourceApi = image.createImageSource(data); const imageSourceApi = image.createImageSource(data);
``` ```
## image.CreateIncrementalSource<sup>9+</sup> ## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer): ImageSource createIncrementalSource(buf: ArrayBuffer): ImageSource
Creates an **ImageSource** instance in incremental mode based on the buffers. Creates an **ImageSource** instance in incremental mode based on the buffers.
...@@ -1083,12 +1112,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ...@@ -1083,12 +1112,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers.
```js ```js
const buf = new ArrayBuffer(96); const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf); const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
``` ```
## image.CreateIncrementalSource<sup>9+</sup> ## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
Creates an **ImageSource** instance in incremental mode based on the buffers. Creates an **ImageSource** instance in incremental mode based on the buffers.
...@@ -1111,7 +1140,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ...@@ -1111,7 +1140,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers.
```js ```js
const buf = new ArrayBuffer(96); const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf); const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
``` ```
## ImageSource ## ImageSource
...@@ -1124,7 +1153,7 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour ...@@ -1124,7 +1153,7 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | | ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| supportedFormats | Array\<string> | Yes | No | Supported image formats, including png, jpeg, wbmp, bmp, gif, webp, and heif.| | supportedFormats | Array\<string> | Yes | No | Supported image formats, including PNG, JPEG, BMP, GIF, WebP, and RAW.|
### getImageInfo ### getImageInfo
...@@ -1282,7 +1311,7 @@ Obtains the value of a property in this image. This API uses an asynchronous cal ...@@ -1282,7 +1311,7 @@ Obtains the value of a property in this image. This API uses an asynchronous cal
**Example** **Example**
```js ```js
const property = new ArrayBuffer(400); let property = { index: 0, defaultValue: '9999' }
imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
if(error) { if(error) {
console.log('Failed to get the value of the specified attribute key of the image.'); console.log('Failed to get the value of the specified attribute key of the image.');
...@@ -1477,7 +1506,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses ...@@ -1477,7 +1506,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses
**Example** **Example**
```js ```js
const decodingOptions = new ArrayBuffer(400); let decodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 1, height: 2 },
rotate: 10,
desiredPixelFormat: 3,
desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 },
index: 0
};
imageSourceApi.createPixelMap(decodingOptions, pixelmap => { imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
console.log('Succeeded in creating pixelmap object.'); console.log('Succeeded in creating pixelmap object.');
}) })
...@@ -1551,7 +1588,7 @@ const imagePackerApi = image.createImagePacker(); ...@@ -1551,7 +1588,7 @@ const imagePackerApi = image.createImagePacker();
## ImagePacker ## ImagePacker
Provide APIs to pack images. Before calling any API in **ImagePacker**, you must use **createImagePacker** to create an **ImagePacker** instance. Provides APIs to pack images. Before calling any API in **ImagePacker**, you must use **createImagePacker** to create an **ImagePacker** instance. The image formats JPEG and WebP are supported.
### Attributes ### Attributes
...@@ -1581,7 +1618,6 @@ Packs an image. This API uses an asynchronous callback to return the result. ...@@ -1581,7 +1618,6 @@ Packs an image. This API uses an asynchronous callback to return the result.
```js ```js
let packOpts = { format:"image/jpeg", quality:98 }; let packOpts = { format:"image/jpeg", quality:98 };
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts, data => {}) imagePackerApi.packing(imageSourceApi, packOpts, data => {})
``` ```
...@@ -1610,7 +1646,6 @@ Packs an image. This API uses a promise to return the result. ...@@ -1610,7 +1646,6 @@ Packs an image. This API uses a promise to return the result.
```js ```js
let packOpts = { format:"image/jpeg", quality:98 } let packOpts = { format:"image/jpeg", quality:98 }
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.log('packing succeeded.'); console.log('packing succeeded.');
...@@ -2112,7 +2147,7 @@ Describes area information in an image. ...@@ -2112,7 +2147,7 @@ Describes area information in an image.
| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ |
| pixels | ArrayBuffer | Yes | No | Pixels of the image. | | pixels | ArrayBuffer | Yes | No | Pixels of the image. |
| offset | number | Yes | No | Offset for data reading. | | offset | number | Yes | No | Offset for data reading. |
| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. |
| region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.|
## ImageInfo ## ImageInfo
...@@ -2146,8 +2181,8 @@ Enumerates the pixel formats of images. ...@@ -2146,8 +2181,8 @@ Enumerates the pixel formats of images.
| ---------------------- | ------ | ----------------- | | ---------------------- | ------ | ----------------- |
| UNKNOWN | 0 | Unknown format. | | UNKNOWN | 0 | Unknown format. |
| RGB_565 | 2 | RGB_565. | | RGB_565 | 2 | RGB_565. |
| RGBA_8888 | 3 | RGBA_8888.| | RGBA_8888 | 3 | RGBA_8888. |
| BGRA_8888<sup>9+</sup> | 4 | BGRA_8888.| | BGRA_8888<sup>9+</sup> | 4 | BGRA_8888. |
## AlphaType<sup>9+</sup> ## AlphaType<sup>9+</sup>
...@@ -2159,8 +2194,8 @@ Enumerates the alpha types of images. ...@@ -2159,8 +2194,8 @@ Enumerates the alpha types of images.
| -------- | ------ | ----------------------- | | -------- | ------ | ----------------------- |
| UNKNOWN | 0 | Unknown alpha type. | | UNKNOWN | 0 | Unknown alpha type. |
| OPAQUE | 1 | There is no alpha or the image is opaque.| | OPAQUE | 1 | There is no alpha or the image is opaque.|
| PREMUL | 2 | Premultiplied alpha. | | PREMUL | 2 | Premultiplied alpha. |
| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | | UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. |
## ScaleMode<sup>9+</sup> ## ScaleMode<sup>9+</sup>
...@@ -2236,7 +2271,7 @@ Defines the option for image packing. ...@@ -2236,7 +2271,7 @@ Defines the option for image packing.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | --------------------------------------------------- | | ------- | ------ | ---- | ---- | --------------------------------------------------- |
| format | string | Yes | Yes | Format of the packed image.<br>Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp. | | format | string | Yes | Yes | Format of the packed image.<br>Currently, the JPEG and WebP formats are supported. |
| quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.|
## GetImagePropertyOptions<sup>7+</sup> ## GetImagePropertyOptions<sup>7+</sup>
......
...@@ -12,6 +12,10 @@ Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, ...@@ -12,6 +12,10 @@ Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs,
**Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**. **Recommended use case**: Use LightWeightMap when you need to store and access **KV pairs**.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -92,10 +96,10 @@ Checks whether this container contains all elements of the specified **LightWeig ...@@ -92,10 +96,10 @@ Checks whether this container contains all elements of the specified **LightWeig
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let map = new LightWeightMap(); let map = new LightWeightMap();
map.set("sdfs", 356); map.set("sparrow", 356);
let result = lightWeightMap.hasAll(map); let result = lightWeightMap.hasAll(map);
``` ```
...@@ -125,9 +129,9 @@ Checks whether this container contains the specified key. ...@@ -125,9 +129,9 @@ Checks whether this container contains the specified key.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.hasKey; let result = lightWeightMap.hasKey;
lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightMap.hasKey("squirrel");
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
let result1 = lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = lightWeightMap.hasKey("squirrel");
``` ```
...@@ -156,7 +160,7 @@ Checks whether this container contains the specified value. ...@@ -156,7 +160,7 @@ Checks whether this container contains the specified value.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.hasValue(123); let result = lightWeightMap.hasValue(123);
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
let result1 = lightWeightMap.hasValue(123); let result1 = lightWeightMap.hasValue(123);
``` ```
...@@ -207,9 +211,9 @@ Obtains the value of the specified key in this container. ...@@ -207,9 +211,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.get("sdfs"); let result = lightWeightMap.get("sparrow");
``` ```
...@@ -237,9 +241,9 @@ Obtains the index of the first occurrence of an element with the specified key i ...@@ -237,9 +241,9 @@ Obtains the index of the first occurrence of an element with the specified key i
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getIndexOfKey("sdfs"); let result = lightWeightMap.getIndexOfKey("sparrow");
``` ```
...@@ -267,8 +271,8 @@ Obtains the index of the first occurrence of an element with the specified value ...@@ -267,8 +271,8 @@ Obtains the index of the first occurrence of an element with the specified value
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getIndexOfValue(123); let result = lightWeightMap.getIndexOfValue(123);
``` ```
...@@ -297,8 +301,8 @@ Obtains the key of an element at the specified position in this container. ...@@ -297,8 +301,8 @@ Obtains the key of an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getKeyAt(1); let result = lightWeightMap.getKeyAt(1);
``` ```
...@@ -321,8 +325,8 @@ Adds all elements in a **LightWeightMap** instance to this container. ...@@ -321,8 +325,8 @@ Adds all elements in a **LightWeightMap** instance to this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let map = new LightWeightMap(); let map = new LightWeightMap();
lightWeightMap.setAll(map); lightWeightMap.setAll(map);
``` ```
...@@ -352,7 +356,7 @@ Adds an element to this container. ...@@ -352,7 +356,7 @@ Adds an element to this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
let result = lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); let result = lightWeightMap.set("squirrel", 123);
``` ```
...@@ -380,9 +384,9 @@ Removes an element with the specified key from this container. ...@@ -380,9 +384,9 @@ Removes an element with the specified key from this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.remove("sdfs"); lightWeightMap.remove("sparrow");
``` ```
...@@ -410,8 +414,8 @@ Removes an element at the specified position from this container. ...@@ -410,8 +414,8 @@ Removes an element at the specified position from this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.removeAt(1); let result = lightWeightMap.removeAt(1);
``` ```
...@@ -441,8 +445,8 @@ Sets a value for an element at the specified position in this container. ...@@ -441,8 +445,8 @@ Sets a value for an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.setValueAt(1, 3546); lightWeightMap.setValueAt(1, 3546);
``` ```
...@@ -471,8 +475,8 @@ Obtains the value of an element at the specified position in this container. ...@@ -471,8 +475,8 @@ Obtains the value of an element at the specified position in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let result = lightWeightMap.getValueAt(1); let result = lightWeightMap.getValueAt(1);
``` ```
...@@ -489,8 +493,8 @@ Clears this container and sets its length to **0**. ...@@ -489,8 +493,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
lightWeightMap.clear(); lightWeightMap.clear();
``` ```
...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the keys in this container. ...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the keys in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.keys(); let iter = lightWeightMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -542,8 +546,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -542,8 +546,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.values(); let iter = lightWeightMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -579,8 +583,8 @@ callbackfn ...@@ -579,8 +583,8 @@ callbackfn
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("sdfs", 123); lightWeightMap.set("sparrow", 123);
lightWeightMap.set("dfsghsf", 357); lightWeightMap.set("gull", 357);
lightWeightMap.forEach((value, key) => { lightWeightMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -605,8 +609,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -605,8 +609,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.entries(); let iter = lightWeightMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -634,8 +638,8 @@ Concatenates the elements in this container into a string and returns the string ...@@ -634,8 +638,8 @@ Concatenates the elements in this container into a string and returns the string
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("A", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
let iter = lightWeightMap.toString(); let iter = lightWeightMap.toString();
``` ```
...@@ -657,8 +661,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -657,8 +661,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let lightWeightMap = new LightWeightMap(); let lightWeightMap = new LightWeightMap();
lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); lightWeightMap.set("squirrel", 123);
lightWeightMap.set("sdfs", 356); lightWeightMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of lightWeightMap) { for (let item of lightWeightMap) {
......
...@@ -14,6 +14,9 @@ Compared with **[HashSet](js-apis-hashset.md)**, which can also store values, ** ...@@ -14,6 +14,9 @@ Compared with **[HashSet](js-apis-hashset.md)**, which can also store values, **
**Recommended use case**: Use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set. **Recommended use case**: Use **LightWeightSet** when you need a set that has only unique elements or need to deduplicate a set.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -93,7 +96,7 @@ Adds an element to this container. ...@@ -93,7 +96,7 @@ Adds an element to this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
let result = lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = lightWeightSet.add("squirrel");
``` ```
...@@ -115,10 +118,10 @@ Adds all elements in a **LightWeightSet** instance to this container. ...@@ -115,10 +118,10 @@ Adds all elements in a **LightWeightSet** instance to this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let set = new LightWeightSet(); let set = new LightWeightSet();
set.add("sfage"); set.add("gull");
let result = lightWeightSet.addAll(set); let result = lightWeightSet.addAll(set);
``` ```
...@@ -147,10 +150,10 @@ Checks whether this container contains all elements of the specified **LightWeig ...@@ -147,10 +150,10 @@ Checks whether this container contains all elements of the specified **LightWeig
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let set = new LightWeightSet(); let set = new LightWeightSet();
set.add("sdfs"); set.add("sparrow");
let result = lightWeightSet.hasAll(set); let result = lightWeightSet.hasAll(set);
``` ```
...@@ -209,9 +212,9 @@ Checks whether this container contains objects of the same type as the specified ...@@ -209,9 +212,9 @@ Checks whether this container contains objects of the same type as the specified
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let obj = ["Ahfbrgrbgnutfodgorrogorgrogofdfdf", "sdfs"]; let obj = ["squirrel", "sparrow"];
let result = lightWeightSet.equal(obj); let result = lightWeightSet.equal(obj);
``` ```
...@@ -262,9 +265,9 @@ Obtains the position index of the element with the specified key in this contain ...@@ -262,9 +265,9 @@ Obtains the position index of the element with the specified key in this contain
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.getIndexOf("sdfs"); let result = lightWeightSet.getIndexOf("sparrow");
``` ```
...@@ -292,9 +295,9 @@ Removes an element of the specified key from this container. ...@@ -292,9 +295,9 @@ Removes an element of the specified key from this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.remove("sdfs"); let result = lightWeightSet.remove("sparrow");
``` ```
...@@ -322,8 +325,8 @@ Removes the element at the specified position from this container. ...@@ -322,8 +325,8 @@ Removes the element at the specified position from this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.removeAt(1); let result = lightWeightSet.removeAt(1);
``` ```
...@@ -352,8 +355,8 @@ Obtains the value of the element at the specified position in this container. ...@@ -352,8 +355,8 @@ Obtains the value of the element at the specified position in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.getValueAt(1); let result = lightWeightSet.getValueAt(1);
``` ```
...@@ -370,8 +373,8 @@ Clears this container and sets its length to **0**. ...@@ -370,8 +373,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
lightWeightSet.clear(); lightWeightSet.clear();
``` ```
...@@ -394,8 +397,8 @@ Obtains a string that contains all elements in this container. ...@@ -394,8 +397,8 @@ Obtains a string that contains all elements in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.toString(); let result = lightWeightSet.toString();
``` ```
...@@ -418,8 +421,8 @@ Obtains an array that contains all objects in this container. ...@@ -418,8 +421,8 @@ Obtains an array that contains all objects in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let result = lightWeightSet.toArray(); let result = lightWeightSet.toArray();
``` ```
...@@ -442,8 +445,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -442,8 +445,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let iter = lightWeightSet.values(); let iter = lightWeightSet.values();
let index = 0; let index = 0;
while(index < lightWeightSet.length) { while(index < lightWeightSet.length) {
...@@ -479,8 +482,8 @@ callbackfn ...@@ -479,8 +482,8 @@ callbackfn
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
lightWeightSet.add("dfsghsf"); lightWeightSet.add("gull");
lightWeightSet.forEach((value, key) => { lightWeightSet.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -505,8 +508,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -505,8 +508,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
let iter = lightWeightSet.entries(); let iter = lightWeightSet.entries();
let index = 0; let index = 0;
while(index < lightWeightSet.length) { while(index < lightWeightSet.length) {
...@@ -534,8 +537,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -534,8 +537,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let lightWeightSet = new LightWeightSet(); let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); lightWeightSet.add("squirrel");
lightWeightSet.add("sdfs"); lightWeightSet.add("sparrow");
// Method 1: // Method 1:
for (let item of lightWeightSet) { for (let item of lightWeightSet) {
......
...@@ -12,6 +12,9 @@ Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList* ...@@ -12,6 +12,9 @@ Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList*
**Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. **Recommended use case**: Use **LinkedList** for frequent insertion and removal operations.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -76,7 +79,7 @@ let result = linkedList.add("a"); ...@@ -76,7 +79,7 @@ let result = linkedList.add("a");
let result1 = linkedList.add(1); let result1 = linkedList.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
linkedList.add(b); linkedList.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = linkedList.add(false); let result3 = linkedList.add(false);
``` ```
...@@ -102,7 +105,7 @@ linkedList.addFirst("a"); ...@@ -102,7 +105,7 @@ linkedList.addFirst("a");
linkedList.addFirst(1); linkedList.addFirst(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
linkedList.addFirst(b); linkedList.addFirst(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
linkedList.addFirst(false); linkedList.addFirst(false);
``` ```
...@@ -154,9 +157,9 @@ Checks whether this container has the specified element. ...@@ -154,9 +157,9 @@ Checks whether this container has the specified element.
```ts ```ts
let linkedList = new LinkedList(); let linkedList = new LinkedList();
let result1 = linkedList.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = linkedList.has("squirrel");
linkedList.add("Ahfbrgrbgnutfodgorrogorg"); linkedList.add("squirrel");
let result = linkedList.has("Ahfbrgrbgnutfodgorrogorg"); let result = linkedList.has("squirrel");
``` ```
### get ### get
......
...@@ -10,6 +10,9 @@ Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **Lis ...@@ -10,6 +10,9 @@ Unlike [LinkedList](js-apis-linkedlist.md), which is a doubly linked list, **Lis
**Recommended use case**: Use **List** for frequent insertion and removal operations. **Recommended use case**: Use **List** for frequent insertion and removal operations.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ let result = list.add("a"); ...@@ -72,7 +75,7 @@ let result = list.add("a");
let result1 = list.add(1); let result1 = list.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
list.add(b); list.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = list.add(false); let result3 = list.add(false);
``` ```
...@@ -124,9 +127,9 @@ Checks whether this container has the specified element. ...@@ -124,9 +127,9 @@ Checks whether this container has the specified element.
```ts ```ts
let list = new List(); let list = new List();
let result = list.has("Ahfbrgrbgnutfodgorrogorg"); let result = list.has("squirrel");
list.add("Ahfbrgrbgnutfodgorrogorg"); list.add("squirrel");
let result1 = list.has("Ahfbrgrbgnutfodgorrogorg"); let result1 = list.has("squirrel");
``` ```
### get ### get
...@@ -181,7 +184,7 @@ Obtains the index of the last occurrence of the specified element in this contai ...@@ -181,7 +184,7 @@ Obtains the index of the last occurrence of the specified element in this contai
| Value Type | Description| | Value Type | Description|
| -------- | -------- | | -------- | -------- |
| number | Returns the position index if obtained; returns **-1** otherwise.| | number | Returns the index if obtained; returns **-1** otherwise.|
**Example** **Example**
...@@ -265,7 +268,7 @@ obj1.add(2); ...@@ -265,7 +268,7 @@ obj1.add(2);
obj1.add(4); obj1.add(4);
obj1.add(5); obj1.add(5);
list.equal(obj1); list.equal(obj1);
let obj2 = {name : "lala", age : "13"}; let obj2 = {name : "Dylon", age : "13"};
let result = list.equal(obj2); let result = list.equal(obj2);
``` ```
......
...@@ -53,7 +53,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re ...@@ -53,7 +53,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | ------------------------------ | | -------- | ------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance created.| | callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
**Example** **Example**
...@@ -82,7 +82,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result ...@@ -82,7 +82,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result
| Type | Description | | Type | Description |
| ------------------------------------- | ----------------------------------- | | ------------------------------------- | ----------------------------------- |
| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance created.| | Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the **VideoPlayer** instance, which can be used to manage and play video media.|
**Example** **Example**
...@@ -135,7 +135,7 @@ Only one **AudioRecorder** instance can be created per device. ...@@ -135,7 +135,7 @@ Only one **AudioRecorder** instance can be created per device.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance created.| | callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the **VideoRecorder** instance, which can be used to record video media.|
**Example** **Example**
...@@ -165,7 +165,7 @@ Only one **AudioRecorder** instance can be created per device. ...@@ -165,7 +165,7 @@ Only one **AudioRecorder** instance can be created per device.
| Type | Description | | Type | Description |
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created.| | Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance, which can be used to record video media.|
**Example** **Example**
...@@ -275,15 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../. ...@@ -275,15 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../.
**System capability**: SystemCapability.Multimedia.Media.AudioPlayer **System capability**: SystemCapability.Multimedia.Media.AudioPlayer
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------- | ----------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.<br>**Examples of supported URI schemes**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.INTERNET| | src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.<br>**Examples of supported URI schemes**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET|
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>If the file is an independent music file, use **src=fd://xx**.<br>| | fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Music 1 (address offset: 0, byte length: 100)<br>Music 2 (address offset: 101; byte length: 50)<br>Music 3 (address offset: 151, byte length: 150)<br>1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>If the file is an independent music file, use **src=fd://xx**.<br>|
| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. |
| audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | audioInterruptMode<sup>9+</sup> | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. |
| currentTime | number | Yes | No | Current audio playback position, in ms. | | currentTime | number | Yes | No | Current audio playback position, in ms. |
| duration | number | Yes | No | Audio duration, in ms. | | duration | number | Yes | No | Audio duration, in ms. |
| state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| | state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.|
### play<a name=audioplayer_play></a> ### play<a name=audioplayer_play></a>
play(): void play(): void
...@@ -442,7 +442,7 @@ function printfDescription(obj) { ...@@ -442,7 +442,7 @@ function printfDescription(obj) {
} }
} }
audioPlayer.getTrackDescription((error, ) => { audioPlayer.getTrackDescription((error, arrlist) => {
if (arrlist != null) { if (arrlist != null) {
for (let i = 0; i < arrlist.length; i++) { for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]); printfDescription(arrlist[i]);
...@@ -680,7 +680,7 @@ For details about the video playback demo, see [Video Playback Development](../. ...@@ -680,7 +680,7 @@ For details about the video playback demo, see [Video Playback Development](../.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| url<sup>8+</sup> | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.<br>**Example of supported URIs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>**Required permissions**: ohos.permission.INTERNET| | url<sup>8+</sup> | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.<br>**Example of supported URIs**:<br>1. FD: fd://xx<br>![](figures/en-us_image_url.png)<br>2. HTTP: http://xx<br>3. HTTPS: https://xx<br>4. HLS: http://xx or https://xx<br>|
| fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>| | fdSrc<sup>9+</sup> | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.<br>**Example:**<br>Assume that a music file that stores continuous music resources consists of the following:<br>Video 1 (address offset: 0, byte length: 100)<br>Video 2 (address offset: 101; byte length: 50)<br>Video 3 (address offset: 151, byte length: 150)<br>1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }<br>2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }<br>3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }<br>To play an independent video file, use **src=fd://xx**.<br>|
| loop<sup>8+</sup> | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | loop<sup>8+</sup> | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. |
| videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | | videoScaleType<sup>9+</sup> | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. |
...@@ -1795,7 +1795,7 @@ Subscribes to the audio recording events. ...@@ -1795,7 +1795,7 @@ Subscribes to the audio recording events.
```js ```js
let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance.
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, , audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
...@@ -1850,7 +1850,7 @@ Subscribes to audio recording error events. After an error event is reported, yo ...@@ -1850,7 +1850,7 @@ Subscribes to audio recording error events. After an error event is reported, yo
```js ```js
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, , audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
...@@ -1974,29 +1974,13 @@ let videoConfig = { ...@@ -1974,29 +1974,13 @@ let videoConfig = {
} }
// asyncallback // asyncallback
let videoRecorder = null; videoRecorder.prepare(videoConfig, (err) => {
let events = require('events'); if (err == null) {
let eventEmitter = new events.EventEmitter(); console.info('prepare success');
eventEmitter.on('prepare', () => {
videoRecorder.prepare(videoConfig, (err) => {
if (err == null) {
console.info('prepare success');
} else {
console.info('prepare failed and error is ' + err.message);
}
});
});
media.createVideoRecorder((err, recorder) => {
if (err == null && recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // Trigger the 'prepare' event.
} else { } else {
console.info('createVideoRecorder failed and error is ' + err.message); console.info('prepare failed and error is ' + err.message);
} }
}); })
``` ```
### prepare<sup>9+</sup><a name=videorecorder_prepare2></a> ### prepare<sup>9+</sup><a name=videorecorder_prepare2></a>
...@@ -2047,21 +2031,10 @@ let videoConfig = { ...@@ -2047,21 +2031,10 @@ let videoConfig = {
} }
// promise // promise
let videoRecorder = null; videoRecorder.prepare(videoConfig).then(() => {
media.createVideoRecorder().then((recorder) => { console.info('prepare success');
if (recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}).catch((err) => {
console.info('prepare failed and catch error is ' + err.message);
});
} else {
console.info('createVideoRecorder failed');
}
}).catch((err) => { }).catch((err) => {
console.info('catch err error message is ' + err.message); console.info('prepare failed and catch error is ' + err.message);
}); });
``` ```
...@@ -2475,11 +2448,10 @@ Subscribes to video recording error events. After an error event is reported, yo ...@@ -2475,11 +2448,10 @@ Subscribes to video recording error events. After an error event is reported, yo
**Example** **Example**
```js ```js
// This event is reported when an error occurs during the retrieval of videoRecordState.
videoRecorder.on('error', (error) => { // Set the 'error' event callback. videoRecorder.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, error: ${error}`); console.info(`audio error called, error: ${error}`);
} })
// This event is reported when an error occurs during the retrieval of videoRecordState.
});
``` ```
## VideoRecordState<sup>9+</sup> ## VideoRecordState<sup>9+</sup>
......
...@@ -12,6 +12,9 @@ Both **PlainArray** and **[LightWeightMap](js-apis-lightweightmap.md)** are used ...@@ -12,6 +12,9 @@ Both **PlainArray** and **[LightWeightMap](js-apis-lightweightmap.md)** are used
**Recommended use case**: Use **PlainArray** when you need to store KV pairs whose keys are of the **number** type. **Recommended use case**: Use **PlainArray** when you need to store KV pairs whose keys are of the **number** type.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -93,7 +96,7 @@ Checks whether this container contains the specified key. ...@@ -93,7 +96,7 @@ Checks whether this container contains the specified key.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.has(1); plainArray.has(1);
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
let result1 = plainArray.has(1); let result1 = plainArray.has(1);
``` ```
...@@ -122,8 +125,8 @@ Obtains the value of the specified key in this container. ...@@ -122,8 +125,8 @@ Obtains the value of the specified key in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.get(1); let result = plainArray.get(1);
``` ```
...@@ -152,8 +155,8 @@ Obtains the index of the first occurrence of an element with the specified key i ...@@ -152,8 +155,8 @@ Obtains the index of the first occurrence of an element with the specified key i
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getIndexOfKey(2); let result = plainArray.getIndexOfKey(2);
``` ```
...@@ -182,9 +185,9 @@ Obtains the index of the first occurrence of an element with the specified value ...@@ -182,9 +185,9 @@ Obtains the index of the first occurrence of an element with the specified value
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getIndexOfValue("sddfhf"); let result = plainArray.getIndexOfValue("squirrel");
``` ```
...@@ -212,8 +215,8 @@ Obtains the key of the element at the specified position in this container. ...@@ -212,8 +215,8 @@ Obtains the key of the element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getKeyAt(1); let result = plainArray.getKeyAt(1);
``` ```
...@@ -241,8 +244,8 @@ Obtains the value of an element at the specified position in this container. ...@@ -241,8 +244,8 @@ Obtains the value of an element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.getKeyAt(1); let result = plainArray.getKeyAt(1);
``` ```
...@@ -264,8 +267,8 @@ Clones this container and returns a copy. The modification to the copy does not ...@@ -264,8 +267,8 @@ Clones this container and returns a copy. The modification to the copy does not
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let newPlainArray = plainArray.clone(); let newPlainArray = plainArray.clone();
``` ```
...@@ -289,7 +292,7 @@ Adds an element to this container. ...@@ -289,7 +292,7 @@ Adds an element to this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
``` ```
...@@ -317,8 +320,8 @@ Removes an element with the specified key from this container. ...@@ -317,8 +320,8 @@ Removes an element with the specified key from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.remove(2); plainArray.remove(2);
let result = plainArray.remove(2); let result = plainArray.remove(2);
``` ```
...@@ -348,8 +351,8 @@ Removes an element at the specified position from this container. ...@@ -348,8 +351,8 @@ Removes an element at the specified position from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.removeAt(1); plainArray.removeAt(1);
let result = plainArray.removeAt(1); let result = plainArray.removeAt(1);
``` ```
...@@ -380,8 +383,8 @@ Removes elements in a specified range from this container. ...@@ -380,8 +383,8 @@ Removes elements in a specified range from this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.removeRangeFrom(1, 3); let result = plainArray.removeRangeFrom(1, 3);
``` ```
...@@ -405,8 +408,8 @@ Sets a value for an element at the specified position in this container. ...@@ -405,8 +408,8 @@ Sets a value for an element at the specified position in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.setValueAt(1, 3546); plainArray.setValueAt(1, 3546);
``` ```
...@@ -429,8 +432,8 @@ Obtains a string that contains all elements in this container. ...@@ -429,8 +432,8 @@ Obtains a string that contains all elements in this container.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
let result = plainArray.toString(); let result = plainArray.toString();
``` ```
...@@ -447,8 +450,8 @@ Clears this container and sets its length to **0**. ...@@ -447,8 +450,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.clear(); plainArray.clear();
``` ```
...@@ -479,8 +482,8 @@ callbackfn ...@@ -479,8 +482,8 @@ callbackfn
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
plainArray.forEach((value, index) => { plainArray.forEach((value, index) => {
console.log("value:" + value, index); console.log("value:" + value, index);
}); });
...@@ -505,8 +508,8 @@ Obtains an iterator object that contains key-value pairs, where the key is of th ...@@ -505,8 +508,8 @@ Obtains an iterator object that contains key-value pairs, where the key is of th
```ts ```ts
let plainArray = new PlainArray(); let plainArray = new PlainArray();
plainArray.add(1, "sddfhf"); plainArray.add(1, "squirrel");
plainArray.add(2, "sffdfhf"); plainArray.add(2, "sparrow");
// Method 1: // Method 1:
for (let item of plainArray) { for (let item of plainArray) {
......
# ProcessRunningInfo # ProcessRunningInfo<sup>(deprecated)</sup>
The **ProcessRunningInfo** module provides process running information. The **ProcessRunningInfo** module provides process running information.
> **NOTE** > **NOTE**
> > - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation<sup>9+</sup>](js-apis-processrunninginformation.md) instead.
> The initial APIs of this module are supported since API version 9. 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.
## Usage ## Usage
...@@ -19,9 +19,9 @@ appManager.getProcessRunningInfos((error,data) => { ...@@ -19,9 +19,9 @@ appManager.getProcessRunningInfos((error,data) => {
## Attributes ## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| pid | number | Yes| No| Process ID.| | pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID.| | uid | number | Yes| No| User ID.|
......
# ProcessRunningInformation<sup>9+</sup>
The **ProcessRunningInformation** module provides process running information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Usage Guidelines
The process running information is obtained through [appManager](js-apis-appmanager.md#appmanagergetprocessrunninginformation9).
```js
import appManager from '@ohos.application.appManager';
appManager.getProcessRunningInformation((error,data) => {
console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data));
});
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| pid | number | Yes| No| Process ID.|
| uid | number | Yes| No| User ID.|
| processName | string | Yes| No| Process name.|
| bundleNames | Array&lt;string&gt; | Yes| No| Names of all running bundles in the process.|
...@@ -10,6 +10,9 @@ Unlike **[Deque](js-apis-deque.md)**, which supports insertion and removal at bo ...@@ -10,6 +10,9 @@ Unlike **[Deque](js-apis-deque.md)**, which supports insertion and removal at bo
**Recommended use case**: Use **Queue** in FIFO scenarios. **Recommended use case**: Use **Queue** in FIFO scenarios.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -72,7 +75,7 @@ let result1 = queue.add(1); ...@@ -72,7 +75,7 @@ let result1 = queue.add(1);
queue.add(1); queue.add(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
queue.add(b); queue.add(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = queue.add(c); let result3 = queue.add(c);
``` ```
...@@ -180,6 +183,7 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -180,6 +183,7 @@ Obtains an iterator, each item of which is a JavaScript object.
| IterableIterator&lt;T&gt; | Iterator obtained.| | IterableIterator&lt;T&gt; | Iterator obtained.|
**Example** **Example**
```ts ```ts
let queue = new Queue(); let queue = new Queue();
queue.add(2); queue.add(2);
......
...@@ -55,7 +55,7 @@ Describes the size of the screen region to capture. ...@@ -55,7 +55,7 @@ Describes the size of the screen region to capture.
## screenshot.save ## screenshot.save
save(options?: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;): void save(options: ScreenshotOptions, callback: AsyncCallback&lt;image.PixelMap&gt;): void
Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result. Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result.
...@@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async ...@@ -67,7 +67,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| | options | [ScreenshotOptions](#screenshotoptions) | Yes | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. | | callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. |
**Example** **Example**
...@@ -97,6 +97,35 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async ...@@ -97,6 +97,35 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async
## screenshot.save ## screenshot.save
save(callback: AsyncCallback&lt;image.PixelMap&gt;): void
Takes a screenshot and saves it as a **PixelMap** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications)
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes | Callback used to return a **PixelMap** object. |
**Example**
```js
screenshot.save((err, pixelMap) => {
if (err) {
console.log('Failed to save screenshot: ' + JSON.stringify(err));
return;
}
console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber());
pixelMap.release(); // Release the memory in time after the PixelMap is used.
});
```
## screenshot.save
save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt; save(options?: ScreenshotOptions): Promise&lt;image.PixelMap&gt;
Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result. Takes a screenshot and saves it as a **PixelMap** object. This API uses a promise to return the result.
......
...@@ -1041,7 +1041,7 @@ promise1.then(() => { ...@@ -1041,7 +1041,7 @@ promise1.then(() => {
console.log('connect success'); console.log('connect success');
let promise2 = tcp.getRemoteAddress(); let promise2 = tcp.getRemoteAddress();
promise2.then(() => { promise2.then(() => {
console.log('getRemoteAddress success:' + JSON.stringify(data)); console.log('getRemoteAddress success');
}).catch(err => { }).catch(err => {
console.log('getRemoteAddressfail'); console.log('getRemoteAddressfail');
}); });
...@@ -1120,7 +1120,7 @@ promise.then(() => { ...@@ -1120,7 +1120,7 @@ promise.then(() => {
console.log('connect success'); console.log('connect success');
let promise1 = tcp.getState(); let promise1 = tcp.getState();
promise1.then(() => { promise1.then(() => {
console.log('getState success:' + JSON.stringify(data)); console.log('getState success');
}).catch(err => { }).catch(err => {
console.log('getState fail'); console.log('getState fail');
}); });
......
...@@ -10,6 +10,9 @@ Unlike **[Queue](js-apis-queue.md)**, which is implemented based on the queue da ...@@ -10,6 +10,9 @@ Unlike **[Queue](js-apis-queue.md)**, which is implemented based on the queue da
**Recommended use case**: Use **Stack** in LOFI scenarios. **Recommended use case**: Use **Stack** in LOFI scenarios.
This topic uses the following to identify the use of generics:
- T: Type
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -73,7 +76,7 @@ let result = stack.push("a"); ...@@ -73,7 +76,7 @@ let result = stack.push("a");
let result1 = stack.push(1); let result1 = stack.push(1);
let b = [1, 2, 3]; let b = [1, 2, 3];
stack.push(b); stack.push(b);
let c = {name : "lala", age : "13"}; let c = {name : "Dylon", age : "13"};
let result3 = stack.push(c); let result3 = stack.push(c);
``` ```
......
...@@ -18,26 +18,26 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -18,26 +18,26 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- | | ------ | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
- Return value **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------- | | --------------------- | -------------- |
| Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.| | Promise&lt;number&gt; | Promise used to return the number of free bytes obtained.|
- Example **Example**
```js ```js
let path = "/dev"; let path = "/dev";
statfs.getFreeBytes(path).then(function (number){ statfs.getFreeBytes(path).then(function (number) {
console.info("getFreeBytes promise successfully:"+ number); console.info("getFreeBytes promise successfully:" + number);
}).catch(function(err){ }).catch(function (err) {
console.info("getFreeBytes failed with error:"+ err); console.info("getFreeBytes failed with error:" + err);
}); });
``` ```
...@@ -49,21 +49,21 @@ Obtains the number of free bytes of the specified file system in asynchronous mo ...@@ -49,21 +49,21 @@ Obtains the number of free bytes of the specified file system in asynchronous mo
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.| | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of free bytes obtained.|
- Example **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir().then(function (path) { context.getFilesDir().then(function (path) {
statfs.getFreeBytes(path, function(err, number){ statfs.getFreeBytes(path, function (err, number) {
console.info("Got free bytes successfully:"+ number); console.info("getFreeBytes callback successfully:" + number);
}); });
}); });
``` ```
...@@ -76,26 +76,26 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -76,26 +76,26 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | ------ | ---- | ---------------------------- | | ---- | ------ | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
- Return value **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------ | | --------------------- | ------------ |
| Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.| | Promise&lt;number&gt; | Promise used to return the total number of bytes obtained.|
- Example **Example**
```js ```js
let path = "/dev"; let path = "/dev";
statfs.getTotalBytes(path).then(function (number){ statfs.getTotalBytes(path).then(function (number) {
console.info("getTotalBytes promise successfully:"+ number); console.info("getTotalBytes promise successfully:" + number);
}).catch(function(err){ }).catch(function (err) {
console.info("getTotalBytes failed with error:"+ err); console.info("getTotalBytes failed with error:" + err);
}); });
``` ```
...@@ -107,21 +107,21 @@ Obtains the total number of bytes of the specified file system in asynchronous m ...@@ -107,21 +107,21 @@ Obtains the total number of bytes of the specified file system in asynchronous m
**System capability**: SystemCapability.FileManagement.File.FileIO **System capability**: SystemCapability.FileManagement.File.FileIO
- **Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ---------------------------- | | -------- | --------------------------- | ---- | ---------------------------- |
| path | string | Yes | File path of the file system.| | path | string | Yes | File path of the file system.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. | | callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the total number of bytes obtained. |
- Example **Example**
```js ```js
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.getFilesDir().then(function (path) { context.getFilesDir().then(function (path) {
statfs.getTotalBytes(path, function(err, number){ statfs.getTotalBytes(path, function(err, number) {
console.info("Got total bytes successfully:"+ number); console.info("getTotalBytes callback successfully:" + number);
}); });
}); });
``` ```
...@@ -25,7 +25,7 @@ Encrypts or decrypts data using RSA. ...@@ -25,7 +25,7 @@ Encrypts or decrypts data using RSA.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| action | string | Yes| Action to perform. The options are as follows:<br>-&nbsp;encrypt<br>-&nbsp;decrypt| | action | string | Yes| Action to perform. The options are as follows:<br>- encrypt<br>- decrypt |
| text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text that meets the following requirement:<br> Maximum text length = Key length/8 - 66<br>For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).<br> The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.|
| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| | key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.|
| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| | transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.|
...@@ -109,7 +109,7 @@ Encrypts or decrypts data using AES. ...@@ -109,7 +109,7 @@ Encrypts or decrypts data using AES.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| action | string | Yes| Action to perform. The options are as follows:<br>-&nbsp;encrypt<br>-&nbsp;decrypt| | action | string | Yes| Action to perform. The options are as follows:<br>- encrypt<br>- decrypt |
| text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| | text | string | Yes| Text to be encrypted or decrypted.<br> The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.|
| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| | key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.|
| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| | transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.|
...@@ -165,7 +165,6 @@ export default { ...@@ -165,7 +165,6 @@ export default {
console.log(`operation complete!`); console.log(`operation complete!`);
} }
}); });
});
} }
} }
......
...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner { ...@@ -29,7 +29,7 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onPrepare") console.log("Trigger onPrepare")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner { ...@@ -50,6 +50,6 @@ export default class UserTestRunner implements TestRunner {
onPrepare() { onPrepare() {
console.log("Trigger onRun") console.log("Trigger onRun")
} }
onRun(){} onRun(){}
}; };
``` ```
...@@ -12,6 +12,10 @@ ...@@ -12,6 +12,10 @@
Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order. Recommended use case: Use **TreeMap** when you need to store KV pairs in sorted order.
This topic uses the following to identify the use of generics:
- K: Key
- V: Value
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -96,9 +100,9 @@ Checks whether this container has the specified key. ...@@ -96,9 +100,9 @@ Checks whether this container has the specified key.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
let result = treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result = treeMap.hasKey("squirrel");
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
let result1 = treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); let result1 = treeMap.hasKey("squirrel");
``` ```
...@@ -127,7 +131,7 @@ Checks whether this container has the specified value. ...@@ -127,7 +131,7 @@ Checks whether this container has the specified value.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
let result = treeMap.hasValue(123); let result = treeMap.hasValue(123);
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
let result1 = treeMap.hasValue(123); let result1 = treeMap.hasValue(123);
``` ```
...@@ -156,9 +160,9 @@ Obtains the value of the specified key in this container. ...@@ -156,9 +160,9 @@ Obtains the value of the specified key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.get("sdfs"); let result = treeMap.get("sparrow");
``` ```
...@@ -180,8 +184,8 @@ Obtains the first key in this container. ...@@ -180,8 +184,8 @@ Obtains the first key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.getFirstKey(); let result = treeMap.getFirstKey();
``` ```
...@@ -204,8 +208,8 @@ Obtains the last key in this container. ...@@ -204,8 +208,8 @@ Obtains the last key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let result = treeMap.getLastKey(); let result = treeMap.getLastKey();
``` ```
...@@ -228,8 +232,8 @@ Adds all elements in a **TreeMap** instance to this container. ...@@ -228,8 +232,8 @@ Adds all elements in a **TreeMap** instance to this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let map = new TreeMap(); let map = new TreeMap();
treeMap.setAll(map); treeMap.setAll(map);
``` ```
...@@ -260,7 +264,7 @@ Adds an element to this container. ...@@ -260,7 +264,7 @@ Adds an element to this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
``` ```
...@@ -288,9 +292,9 @@ Removes the element with the specified key from this container. ...@@ -288,9 +292,9 @@ Removes the element with the specified key from this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.remove("sdfs"); treeMap.remove("sparrow");
``` ```
...@@ -318,10 +322,10 @@ Obtains the key that is placed in front of the input key in this container. ...@@ -318,10 +322,10 @@ Obtains the key that is placed in front of the input key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.set("zdfgsd", 356); treeMap.set("gander", 356);
let result = treeMap.getLowerKey("sdfs"); let result = treeMap.getLowerKey("sparrow");
``` ```
...@@ -349,10 +353,10 @@ Obtains the key that is placed next to the input key in this container. ...@@ -349,10 +353,10 @@ Obtains the key that is placed next to the input key in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.set("zdfgsd", 356); treeMap.set("gander", 356);
let result = treeMap.getHigherKey("sdfs"); let result = treeMap.getHigherKey("sparrow");
``` ```
### replace ### replace
...@@ -380,8 +384,8 @@ Replaces an element in this container. ...@@ -380,8 +384,8 @@ Replaces an element in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("sdfs", 123); treeMap.set("sparrow", 123);
let result = treeMap.replace("sdfs", 357); let result = treeMap.replace("sparrow", 357);
``` ```
...@@ -397,8 +401,8 @@ Clears this container and sets its length to **0**. ...@@ -397,8 +401,8 @@ Clears this container and sets its length to **0**.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
treeMap.clear(); treeMap.clear();
``` ```
...@@ -421,8 +425,8 @@ Obtains an iterator that contains all the keys in this container. ...@@ -421,8 +425,8 @@ Obtains an iterator that contains all the keys in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.keys(); let iter = treeMap.keys();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -450,8 +454,8 @@ Obtains an iterator that contains all the values in this container. ...@@ -450,8 +454,8 @@ Obtains an iterator that contains all the values in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.values(); let iter = treeMap.values();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -487,8 +491,8 @@ callbackfn ...@@ -487,8 +491,8 @@ callbackfn
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("sdfs", 123); treeMap.set("sparrow", 123);
treeMap.set("dfsghsf", 357); treeMap.set("gull", 357);
treeMap.forEach((value, key) => { treeMap.forEach((value, key) => {
console.log("value:" + value, key); console.log("value:" + value, key);
}); });
...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the elements in this container. ...@@ -513,8 +517,8 @@ Obtains an iterator that contains all the elements in this container.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
let iter = treeMap.entries(); let iter = treeMap.entries();
let temp = iter.next().value; let temp = iter.next().value;
while(temp != undefined) { while(temp != undefined) {
...@@ -542,8 +546,8 @@ Obtains an iterator, each item of which is a JavaScript object. ...@@ -542,8 +546,8 @@ Obtains an iterator, each item of which is a JavaScript object.
```ts ```ts
let treeMap = new TreeMap(); let treeMap = new TreeMap();
treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); treeMap.set("squirrel", 123);
treeMap.set("sdfs", 356); treeMap.set("sparrow", 356);
// Method 1: // Method 1:
for (let item of treeMap) { for (let item of treeMap) {
......
...@@ -339,8 +339,8 @@ let strXml = ...@@ -339,8 +339,8 @@ let strXml =
let arrayBuffer = new ArrayBuffer(strXml.length); let arrayBuffer = new ArrayBuffer(strXml.length);
let bufView = new Uint8Array(arrayBuffer); let bufView = new Uint8Array(arrayBuffer);
let strLen = strXml.length; let strLen = strXml.length;
for (var i = 0; i < strLen; ++i) { for (var tmp = 0; tmp < strLen; ++tmp) {
bufView[i] = strXml.charCodeAt(i); bufView[tmp] = strXml.charCodeAt(tmp);
} }
let that = new xml.XmlPullParser(arrayBuffer); let that = new xml.XmlPullParser(arrayBuffer);
let arrTag = {}; let arrTag = {};
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册