diff --git a/CODEOWNERS b/CODEOWNERS index 9ffdaf23ba7351b7dd5e18b54559e424f4a2b80a..6a8730751d65c0cd83e109d7a4edffce37b988ec 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -151,9 +151,9 @@ zh-cn/application-dev/work-scheduler/ @HelloCrease zh-cn/application-dev/internationalization/ @HelloCrease zh-cn/application-dev/device/usb-overview.md @ge-yafang zh-cn/application-dev/device/usb-guidelines.md @ge-yafang -zh-cn/application-dev/device/device-location-overview.md @sun-yue14 -zh-cn/application-dev/device/device-location-info.md @sun-yue14 -zh-cn/application-dev/device/device-location-geocoding.md @sun-yue14 +zh-cn/application-dev/device/device-location-overview.md @zengyawen +zh-cn/application-dev/device/device-location-info.md @zengyawen +zh-cn/application-dev/device/device-location-geocoding.md @zengyawen zh-cn/application-dev/device/sensor-overview.md @HelloCrease zh-cn/application-dev/device/sensor-guidelines.md @HelloCrease zh-cn/application-dev/device/vibrator-overview.md @HelloCrease @@ -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-image.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-intl.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease @@ -277,14 +277,14 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-tagSession.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-wifi.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen @@ -293,18 +293,18 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-system-time.md @bmeangel -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-time.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-device-manager.md -zh-cn/application-dev/reference/apis/js-apis-geolocation.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-geolocation.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease @@ -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/website.md @zengyawen zh-cn/application-dev/faqs/ @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-useriam-faceauth.md @zengyawen +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 diff --git a/OAT.xml b/OAT.xml index 8cc884632d4a963fa921c5905cfbf96e7e22edb7..4edf72f5a3b3e03801bdab83dad547cd7c0c18ef 100644 --- a/OAT.xml +++ b/OAT.xml @@ -66,7 +66,7 @@ - + diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md index f603c4dd54840118471cba6c344de58121577d57..c654e42cf77f1c739e420e3d9a50c6be00d26385 100644 --- a/en/application-dev/database/database-datashare-overview.md +++ b/en/application-dev/database/database-datashare-overview.md @@ -14,23 +14,23 @@ The data provider can directly use the **DataShare** framework to share data wit Before you get started, familiarize yourself with the following concepts: -- Data provider +- **Data provider** An application that provides data and implements related services. It is also called a producer or server. -- Data consumer +- **Data consumer** An application that accesses the data or services provided by a data provider. It is also called a client. -- Value bucket (**ValuesBucket**) +- **ValuesBucket** One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. -- Result set +- **Result set** A collection of query results. Flexible data access modes are provided for users to obtain data. -- Predicate +- **Predicate** Conditions specified for updating, deleting, or querying data in the database. diff --git a/en/application-dev/database/database-mdds-overview.md b/en/application-dev/database/database-mdds-overview.md index 26efa7491805e871017db3593f5fa50d947717f5..cfe264a4f7eb06cd51cb834bc3e38ee27e649a14 100644 --- a/en/application-dev/database/database-mdds-overview.md +++ b/en/application-dev/database/database-mdds-overview.md @@ -1,105 +1,103 @@ # 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. You do not need to care about the implementation of the database locking mechanism. + ## 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. - - **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. +- **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. +- **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. - - **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. +- **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. -- **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 -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**
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**
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**
The storage component implements data access, data reduction, transactions, snapshots, database encryption, data combination, and conflict resolution. -- **Storage component** +- **Synchronization component**
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**
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 +## 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 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 DDS does not support customized conflict resolution policies. -- The data that needs to be synchronized between devices should be stored in distributed databases rather than local databases. -- 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. +- 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. diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index a4acbd9a7b47dca4332c7f6a881939b1928abd78..bd38925cbe8a17e5cb6319ffc9729ef263945e9c 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -196,17 +196,41 @@ Table 15 Transaction APIs (3) Create an RDB store. - The sample code is as follows: + FA model: ```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: "rdbstore.db" } - data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { + const STORE_CONFIG = { name: "RdbTest.db" } + data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { rdbStore.executeSql(CREATE_TABLE_TEST) 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. diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index 325f4983f16f0cd48899fb657d3c9e41d2f9c3d8..03ed574bb99bcd65cecf0c6ca4710ab2271db9d3 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -187,7 +187,7 @@ ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index 7c623151a90c6f7fe278ee9354ff3232456b6026..b6b8cd11b8ba18b59931c1bf0244d4af3d7ec888 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -185,7 +185,7 @@ ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index dbd2931eba6f6de6c6d23777a5c761dc505dc7c4..03b037aeb529dcf7d481caf56db32625943c055b 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -181,7 +181,7 @@ ## Implementing Page Redirection -You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index fe77dc5347f70c5cbcef596dbd8c3b57df83d9cc..e580b6bbef7bd71869de1da19a3a3d5c4757370d 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -146,6 +146,7 @@ - [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.security.huks ](js-apis-huks.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) + - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - [@system.cipher](js-apis-system-cipher.md) - Data Management diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index 9aab0179f06478fef211871d29e90daa33cf5609..9d33d34e9e0275c538e1cf2913af5fc0fdc656bc 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -6,8 +6,8 @@ This module provides APIs for accessing ability-specific resources. You can use > **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 APIs of this module can be used only in the stage model. +> - 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. ## Usage diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 619ed387b6338fa06a064b3848a3491ee7ea08c9..4b1a66f071f464d6662d8429606c48aa025e8ef6 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -4,12 +4,12 @@ The **wantConstant** module provides the actions, entities, and flags used in ** > **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 -``` -import wantConstant from '@ohos.ability.wantConstant' +```js +import wantConstant from '@ohos.ability.wantConstant'; ``` ## wantConstant.Action @@ -46,8 +46,13 @@ Enumerates the action constants of the **Want** object. | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | | PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | -| ACTION_MARKER_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | - +| ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| ACTION_MARKET_CROWDTEST 9+ | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_SANDBOX9+ |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_BUNDLE_NAME9+ |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_MODULE_NAME9+ |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_ABILITY_NAME9+ |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_INDEX9+ |ohos.dlp.params.index |Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications. | ## wantConstant.Entity diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md index c48d33d59a701fb998f82316d5c70a0d86fc5ea1..3509cdff1bc50c134be76aa4a90742cb3a14f778 100644 --- a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @@ -99,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log("WindowExtension " + JSON.stringify(pro)); + console.log('WindowExtension ' + JSON.stringify(pro)); }) window.show(); }) diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 565210637c6e83f83ec734c0905e11596baaf0db..87a9809bb9b49db443ec6f7d1617a2228dacaf88 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -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: -- [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. > **NOTE** @@ -22,12 +22,12 @@ import Ability from '@ohos.application.Ability'; **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.| -| 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.| -| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| +| 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.| +| 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.| ## Ability.onCreate @@ -39,13 +39,13 @@ Called to initialize the service logic when an ability is created. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | 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.| +**Example** + ```js class myAbility extends Ability { onCreate(want, param) { @@ -65,12 +65,12 @@ Called when a **WindowStage** is created for this ability. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | windowStage | window.WindowStage | Yes| **WindowStage** information.| +**Example** + ```js class myAbility extends Ability { onWindowStageCreate(windowStage) { @@ -88,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onWindowStageDestroy() { @@ -109,12 +109,12 @@ Called when the **WindowStage** is restored during the migration of this ability **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | windowStage | window.WindowStage | Yes| **WindowStage** information.| +**Example** + ```js class myAbility extends Ability { onWindowStageRestore(windowStage) { @@ -132,8 +132,8 @@ Called when this ability is destroyed to clear resources. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onDestroy() { @@ -151,8 +151,8 @@ Called when this ability is switched from the background to the foreground. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onForeground() { @@ -170,8 +170,8 @@ Called when this ability is switched from the foreground to the background. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js class myAbility extends Ability { onBackground() { @@ -191,18 +191,18 @@ Called to save data during the ability migration preparation process. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wantParam | {[key: string]: any} | Yes| **want** parameter.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | wantParam | {[key: string]: any} | Yes| **want** parameter.| **Return value** -| Type| Description| -| -------- | -------- | -| AbilityConstant.OnContinueResult | Continuation result.| - -**Example** + | Type| Description| + | -------- | -------- | + | AbilityConstant.OnContinueResult | Continuation result.| +**Example** + ```js import AbilityConstant from "@ohos.application.AbilityConstant" class myAbility extends Ability { @@ -225,20 +225,17 @@ Called when the ability startup mode is set to singleton. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | 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.| +**Example** + ```js class myAbility extends Ability { - onNewWant(want, launchParams) { + onNewWant(want) { 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 **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +**Example** + ```js class myAbility extends Ability { onConfigurationUpdated(config) { @@ -278,12 +275,12 @@ Dumps client information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| params | Array\ | Yes| Parameters in the form of a command.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| +**Example** + ```js class myAbility extends Ability { dump(params) { @@ -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 -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 @@ -310,19 +331,19 @@ Sends sequenceable data to the target ability. **Parameters** -| 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.| -| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| + | 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.| + | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return a response.| - -**Example** + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return a response.| +**Example** + ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ // Custom sequenceable data structure @@ -383,19 +404,19 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Parameters** -| 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.| -| data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| + | 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.| + | data | rpc.Sequenceable | Yes| Sequenceable data. You need to customize the data.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| - -**Example** + | Type| Description| + | -------- | -------- | + | Promise<rpc.MessageParcel> | Promise used to return the sequenceable data from the target ability.| +**Example** + ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ @@ -455,8 +476,8 @@ Releases the caller interface of the target ability. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -**Example** - +**Example** + ```js import Ability from '@ohos.application.Ability'; var caller; @@ -492,12 +513,12 @@ Registers a callback that is invoked when the stub on the target ability is disc **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| - -**Example** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| +**Example** + ```js import Ability from '@ohos.application.Ability'; var caller; @@ -540,12 +561,13 @@ Registers a caller notification callback, which is invoked when the target abili **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | 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.| -**Example** +**Example** + ```js import Ability from '@ohos.application.Ability'; class MyMessageAble{ @@ -595,9 +617,9 @@ Deregisters a caller notification callback, which is invoked when the target abi **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| method | string | Yes| Registered notification message string.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | method | string | Yes| Registered notification message string.| **Example** @@ -618,17 +640,16 @@ Deregisters a caller notification callback, which is invoked when the target abi **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; **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.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md index ca3269353344ca06935afaf6b390ae0c906f1a1a..50e65757431e7df6b9bc784c6169da902a04bf5d 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -65,7 +65,7 @@ Enumerates ability continuation results. ## 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 @@ -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_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.| + +## 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. | diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md index 542214482f3e5bc8a74dad3d9990e1817b3f02e8..1a6035f15c6d68dd374d21e1953163b57d1e7648 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md @@ -875,3 +875,265 @@ abilityDelegator.finishTest(msg, 0).then(() => { console.info("finishTest promise"); }); ``` + +### addAbilityStageMonitor9+ + +addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): 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\ | 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"); +}); +``` + + + +### addAbilityStageMonitor9+ + +addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; + +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\ | 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"); +}); +``` + +### removeAbilityStageMonitor9+ + +removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): 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\ | 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"); +}); +``` + + + +### removeAbilityStageMonitor9+ + +removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; + +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\ | 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"); +}); +``` + +### waitAbilityStageMonitor9+ + +waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): 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\ | 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"); +}); +``` + +### waitAbilityStageMonitor9+ + +waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\; + +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\ | 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"); +}); +``` + +### waitAbilityStageMonitor9+ + +waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\): 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\ | 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 | +| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| +| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md index dffe0e39e69e38123bf7e89338b3d4efb14ad82a..678cc3a11a34f9b7481b0754eb024d5454f39b09 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @@ -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**. ```js -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; var args = AbilityDelegatorRegistry.getArguments(); ``` @@ -24,7 +24,7 @@ Describes the ability delegator arguments. | Name | Type | Readable| Writable| Description | | ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Yes | Bundle name of the application to test. | -| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently. | -| testCaseNames | string | Yes | Yes | Test case names. | -| testRunnerClassName | string | Yes | Yes | Names of the test case executors. | +| bundleName | string | Yes | Yes | Bundle name of the application to test.| +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.| +| testCaseNames | string | Yes | Yes | Test case names.| +| testRunnerClassName | string | Yes | Yes | Names of the test case executors.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilitystage.md index 5817123ea55725ecd6c3c7a1f1d2a88b3f27b2ca..d1c8592f97d4c8b8799d5773b391bb1798663219 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilitystage.md @@ -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 context: AbilityStageContext; diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 1b2bd22548deeed3145803c1a3939e59399b904c..9dc3ec0c3c5f022d4aecd438f59ebc830a34ae63 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | 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** @@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | 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.| + | Type| Description| + | -------- | -------- | + | Promise<boolean> | 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** @@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | 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.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | 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** @@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Size of the application memory.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Size of the application memory.| **Example** @@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | No| Size of the application memory.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | No| Size of the application memory.| **Example** @@ -157,14 +157,12 @@ Obtains the memory size of this application. This API uses an asynchronous callb ``` ## appManager.getProcessRunningInfos(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. - getProcessRunningInfos(): Promise\>; 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.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -187,14 +185,12 @@ Obtains information about the running processes. This API uses a promise to retu ## appManager.getProcessRunningInfos(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. - getProcessRunningInfos(callback: AsyncCallback\>): void; 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.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. + **Required permissions**: ohos.permission.GET_RUNNING_INFO **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -228,7 +224,7 @@ Obtains information about the running processes. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise\> | Promise used to return the process information.| +| Promise\> | Promise used to return the process information.| **Example** @@ -254,7 +250,7 @@ Obtains information about the running processes. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the process information.| +| callback | AsyncCallback\> | No| Callback used to return the process information.| **Example** @@ -269,7 +265,7 @@ Obtains information about the running processes. This API uses an asynchronous c 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 @@ -307,9 +303,9 @@ Registers an observer to listen for the state of all applications. ## appManager.registerApplicationStateObserver9+ -registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array): number; +registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): 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 @@ -322,7 +318,7 @@ Registers an observer to listen for the state of a specified application. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| -| bundleNameList | Array | No| **bundleName** array to be registered for listening. The maximum value is 128.| +| bundleNameList | Array | No| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| **Example** @@ -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. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | 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 **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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).| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | 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).| **Example** @@ -525,11 +521,11 @@ Kills a process by bundle name and account ID. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| 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).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | 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).| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -708,9 +704,14 @@ Called when the application state changes. **Example** ```js -import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' -const foregroundApplicationInfo = ApplicationStateObserver.onForegroundApplicationChanged(); -console.log('-------- foregroundApplicationInfo: ---------', foregroundApplicationInfo); + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); + ``` ## ApplicationStateObserver.onAbilityStateChanged8+ @@ -732,9 +733,13 @@ Called when the ability state changes. **Example** ```js -import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' -const abilityStateChangedInfo = ApplicationStateObserver.onAbilityStateChanged(); -console.log('-------- abilityStateChangedInfo: ---------', abilityStateChangedInfo); + var applicationStateObserver = { + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); ``` ## ApplicationStateObserver.onProcessCreated8+ @@ -756,9 +761,13 @@ Called when a process is created. **Example** ```js -import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' -const processCreatedInfo = ApplicationStateObserver.onProcessCreated(); -console.log('-------- processCreatedInfo: ---------', processCreatedInfo); + var applicationStateObserver = { + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); ``` ## ApplicationStateObserver.onProcessDied8+ @@ -775,14 +784,46 @@ Called when a process is terminated. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| processData | ProcessData | No| Process information.| +| processData | [ProcessData](#processdata) | No| Process information.| **Example** ```js -import ApplicationStateObserver from '@ohos.application.ApplicationStateObserver' -const processDiedInfo = ApplicationStateObserver.onProcessDied(); -console.log('-------- processDiedInfo: ---------', processDiedInfo); + var applicationStateObserver = { + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + } + } + const observerCode = app.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); +``` + +## ApplicationStateObserver.onProcessStateChanged9+ + + 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 @@ -815,7 +856,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); ## 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. @@ -824,19 +865,19 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | pid8+ | number | Yes | No | Process ID. | | bundleName8+ | string | Yes | No | Bundle name of an application. | | uid8+ | number | Yes | No | User ID. | - - +| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | +| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | ## ProcessRunningInfo -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission | Name | Readable/Writable| Type | Mandatory| Description | | ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid9+ | Read only | number | No | Process ID. | -| uid9+ | Read only | number | No | User ID.| -| processName9+ | Read only | string | No | Process name.| -| bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| +| pid8+ | Read only | number | No | Process ID. | +| uid8+ | Read only | number | No | User ID.| +| processName8+ | Read only | string | No | Process name.| +| bundleNames8+ | Read only | Array\ | No | **bundleName** array in the running processes.| ## ApplicationStateObserver @@ -850,3 +891,44 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | [onAbilityStateChanged8+](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | | [onProcessCreated8+](#applicationstateobserveronprocesscreated8) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | | [onProcessDied8+](#applicationstateobserveronprocessdied8) | AsyncCallback\ | 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 | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| pid9+ | Read only | number | No | Process ID. | +| uid9+ | Read only | number | No | User ID.| +| processName9+ | Read only | string | No | Process name.| +| bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| + +## ApplicationState9+ + +**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. | + +## ProcessState9+ + +**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. | diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 78db0562f97cf687e26c210d870519c829b691ee..5d57d317cb2a4ae2fa0e7ba29e61a23d95c8dbd1 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -812,7 +812,7 @@ Obtains the zoom ratio range. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | -------- | ------------------------------ | ---- | ------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return an array containing the minimum and maximum zoom ratios.| **Example** @@ -838,7 +838,7 @@ Obtains the zoom ratio range. This API uses a promise to return the result. | Type | Description | | ------------------------ | ------------------------------------------- | -| Promise\> | Promise used to return the zoom ratio range.| +| Promise\> | Promise used to return an array containing the minimum and maximum zoom ratios.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 710d6ccb8820e88ed98e3519c36824efdd5e5b17..0bf80dbbd39095bdce908faad30f90da0461e08b 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -71,10 +71,6 @@ Provides the event types supported by the **CommonEvent** module. The name and v | 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_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_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. | diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 6803d4edf50fc219bc37c4be79fc71687dd91457..5d649c2f28ebd158da0abe963095c9202fdf6c25 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -39,8 +39,8 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | -| name | string | Yes | Name of the **Preferences** instance. | -| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined and the **Preferences** instance obtained is returned. Otherwise, **err** is an error code.| **Example** @@ -66,12 +66,14 @@ Obtains a **Preferences** instance. This API uses a promise to return the result **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance.| **Return value** + | Type | Description | | ------------------------------------------ | ---------------------------------- | | Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| @@ -103,6 +105,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | @@ -110,6 +113,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js data_preferences.deletePreferences(this.context, 'mystore', function (err) { if (err) { @@ -134,17 +138,20 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = data_preferences.deletePreferences(this.context, 'mystore') promise.then(() => { @@ -166,6 +173,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | @@ -173,6 +181,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { if (err) { @@ -195,17 +204,20 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') promise.then(() => { @@ -232,6 +244,7 @@ Obtains the value of a key. This API uses an asynchronous callback to return the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -260,6 +273,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -272,6 +286,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the | Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** + ```js let promise = preferences.get('startup', 'default'); promise.then((data) => { @@ -290,6 +305,7 @@ Obtains an **Object** instance that contains all KV pairs. This API uses an asyn **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| @@ -318,11 +334,13 @@ Obtains an **Object** instance that contains all KV pairs. This API uses a promi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** + ```js let promise = preferences.getAll(); promise.then((value) => { @@ -343,6 +361,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | @@ -350,6 +369,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** + ```js preferences.put('startup', 'auto', function (err) { if (err) { @@ -370,17 +390,20 @@ Writes data to this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | | value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.put('startup', 'auto'); promise.then(() => { @@ -400,12 +423,14 @@ Checks whether this **Preferences** instance contains a KV pair of the given key **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to check. It cannot be empty. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** + ```js preferences.has('startup', function (err, isExist) { if (err) { @@ -430,11 +455,13 @@ Checks whether this **Preferences** instance contains data with the given key. T **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| @@ -464,12 +491,14 @@ Deletes a KV pair from this **Preferences** instance. This API uses an asynchron **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.delete('startup', function (err) { if (err) { @@ -490,16 +519,19 @@ Deletes a KV pair from this **Preferences** instance. This API uses a promise to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.delete('startup'); promise.then(() => { @@ -514,16 +546,18 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. +Asynchronously stores data of this **Preferences** instance to its persistent file. This API uses a asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.flush(function (err) { if (err) { @@ -539,16 +573,18 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. +Asynchronously stores data of this **Preferences** instance to its persistent file. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.flush(); promise.then(() => { @@ -568,11 +604,13 @@ Clears this **Preferences** instance. This API uses an asynchronous callback to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.clear(function (err) { if (err) { @@ -593,11 +631,13 @@ Clears this **Preferences** instance. This API uses a promise to return the resu **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.clear() promise.then(() => { @@ -617,56 +657,14 @@ Subscribes to data changes. A callback will be triggered to return the new value **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| | callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** -```js -data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { - if (err) { - console.info("Failed to get the preferences."); - return; - } - var observer = function (key) { - console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { - if (err) { - console.info("Failed to put the value of 'startup'. Cause: " + err); - return; - } - console.info("Put the value of 'startup' successfully."); - preferences.flush(function (err) { - if (err) { - console.info("Failed to flush data. Cause: " + err); - return; - } - console.info("Flushed data successfully."); // The observer will be called. - }) - }) -}) -``` - - -### off('change') - -off(type: 'change', callback?: Callback<{ key : string }>): void - -Unsubscribes from data changes. - -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | -| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| - -**Example** ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index ff9f8d69e48847bd60741f174af4dbe92a19e2ee..965cd60ea5e20bcacf9b69302491604fa135d647 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -3,11 +3,13 @@ Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. -> **NOTE** +> **NOTE**
> -> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - The APIs of this module are no longer maintained since API Version 9. You are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md). +> - The APIs of this module are no longer maintained since API version 9. You are advised to use [`@ohos.data.preferences`](js-apis-data-preferences.md). +> +> - The APIs of this module can be used only in the FA model. ## Modules to Import @@ -36,15 +38,15 @@ Reads the specified file and loads its data to the **Storage** instance for data **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------ | -| [Storage](#storage) | **Storage** instance used for data storage operations. | +| Type | Description | +| ------------------- | ------------------------------------------------- | +| [Storage](#storage) | **Storage** instance used for data storage operations.| **Example** @@ -54,13 +56,13 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -let storage = data_storage.getStorageSync(path + '/mystore'); -storage.putSync('startup', 'auto'); -storage.flushSync(); + let storage = data_storage.getStorageSync(path + '/mystore'); + storage.putSync('startup', 'auto'); + storage.flushSync(); +}); ``` @@ -74,10 +76,10 @@ Reads the specified file and loads its data to the **Storage** instance for data **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | --------------------------------------------- | -| path | string | Yes | Path of the target file. | -| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| +| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. | **Example** @@ -87,18 +89,18 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -data_storage.getStorage(path + '/mystore', function (err, storage) { + data_storage.getStorage(path + '/mystore', function (err, storage) { if (err) { - console.info("Failed to get the storage. path: " + path + '/mystore'); - return; + console.info("Failed to get the storage. path: " + path + '/mystore'); + return; } storage.putSync('startup', 'auto'); storage.flushSync(); -}) + }) +}); ``` @@ -112,15 +114,15 @@ Reads the specified file and loads its data to the **Storage** instance for data **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| ---------------------------------- | ---------------------------------- | -| Promise<[Storage](#storage)> | Promise used to return the result. | +| Type | Description | +| ---------------------------------- | ------------------------------- | +| Promise<[Storage](#storage)> | Promise used to return the result.| **Example** @@ -130,17 +132,17 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -let getPromise = data_storage.getStorage(path + '/mystore'); -getPromise.then((storage) => { + let getPromise = data_storage.getStorage(path + '/mystore'); + getPromise.then((storage) => { storage.putSync('startup', 'auto'); storage.flushSync(); -}).catch((err) => { + }).catch((err) => { console.info("Failed to get the storage. path: " + path + '/mystore'); -}) + }) +}); ``` @@ -154,9 +156,9 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Example** @@ -168,12 +170,11 @@ var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; console.info("======================>getFilesDirPromise====================>"); -}); -data_storage.deleteStorageSync(path + '/mystore'); + data_storage.deleteStorageSync(path + '/mystore'); +}); ``` - ## data_storage.deleteStorage deleteStorage(path: string, callback: AsyncCallback<void>): void @@ -184,9 +185,9 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------- | -| path | string | Yes | Path of the target file. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -197,17 +198,17 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -data_storage.deleteStorage(path + '/mystore', function (err) { + data_storage.deleteStorage(path + '/mystore', function (err) { if (err) { - console.info("Failed to delete the storage with err: " + err); - return; + console.info("Failed to delete the storage with err: " + err); + return; } console.info("Succeeded in deleting the storage."); -}) + }) +}); ``` @@ -221,13 +222,14 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | + +| Type | Description | +| ------------------- | ------------------------------- | | Promise<void> | Promise that returns no value. | **Example** @@ -238,16 +240,16 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -let promisedelSt = data_storage.deleteStorage(path + '/mystore'); -promisedelSt.then(() => { + let promisedelSt = data_storage.deleteStorage(path + '/mystore'); + promisedelSt.then(() => { console.info("Succeeded in deleting the storage."); -}).catch((err) => { + }).catch((err) => { console.info("Failed to delete the storage with err: " + err); -}) + }) +}); ``` @@ -260,10 +262,9 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Example** @@ -275,9 +276,9 @@ var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; console.info("======================>getFilesDirPromise====================>"); + + data_storage.removeStorageFromCacheSync(path + '/mystore'); }); - -data_storage.removeStorageFromCacheSync(path + '/mystore'); ``` @@ -291,9 +292,9 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------- | -| path | string | Yes | Path of the target file. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -304,17 +305,17 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -data_storage.removeStorageFromCache(path + '/mystore', function (err) { + data_storage.removeStorageFromCache(path + '/mystore', function (err) { if (err) { - console.info("Failed to remove storage from cache with err: " + err); - return; + console.info("Failed to remove storage from cache with err: " + err); + return; } console.info("Succeeded in removing storage from cache."); -}) + }) +}); ``` @@ -328,14 +329,14 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------ | -| path | string | Yes | Path of the target file. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------- | +| path | string | Yes | Path of the target file.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | +| Type | Description | +| ------------------- | ------------------------------- | | Promise<void> | Promise that returns no value. | **Example** @@ -346,24 +347,22 @@ import featureAbility from '@ohos.ability.featureAbility'; var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { - path = filePath; - console.info("======================>getFilesDirPromise====================>"); -}); + path = filePath; + console.info("======================>getFilesDirPromise====================>"); -let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') -promiserevSt.then(() => { + let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') + promiserevSt.then(() => { console.info("Succeeded in removing storage from cache."); -}).catch((err) => { + }).catch((err) => { console.info("Failed to remove storage from cache with err: " + err); -}) + }) +}); ``` - ## Storage Provides APIs for obtaining and modifying storage data. - ### getSync getSync(key: string, defValue: ValueType): ValueType @@ -374,16 +373,16 @@ Obtains the value corresponding to a key. If the value is null or not in the def **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| defValue | [ValueType](#valuetype) | Yes | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value.| **Return value** -| Type | Description | -| --------- | ------------------------------------------------------------ | -| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned. | +| Type | Description | +| --------- | -------------------------------------------------------- | +| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.| **Example** @@ -403,11 +402,11 @@ Obtains the value corresponding to a key. If the value is null or not in the def **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------ | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | -| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ----------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value.| +| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. | **Example** @@ -432,18 +431,19 @@ Obtains the value corresponding to a key. If the value is null or not in the def **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value.| **Return value** -| Type | Description | -| ------------------------ | ---------------------------------- | -| Promise<ValueType> | Promise used to return the result. | +| Type | Description | +| ------------------------ | ------------------------------- | +| Promise<ValueType> | Promise used to return the result.| **Example** + ```js let promiseget = storage.get('startup', 'default'); promiseget.then((value) => { @@ -464,15 +464,15 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ----------------------- | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ----------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value.| **Example** ```js -storage.putSync('startup', 'auto') +storage.putSync('startup', 'auto'); ``` @@ -486,10 +486,10 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value.| | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -515,18 +515,19 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ----------------------- | --------- | ------------------------------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | -| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ----------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | +| Type | Description | +| ------------------- | --------------------------- | | Promise<void> | Promise that returns no value. | **Example** + ```js let promiseput = storage.put('startup', 'auto'); promiseput.then(() => { @@ -547,15 +548,15 @@ Checks whether the storage object contains data with a given key. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty.| **Return value** -| Type | Description | -| ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| **Example** @@ -577,16 +578,16 @@ Checks whether the storage object contains data with a given key. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | --------------------------------------------- | -| key | string | Yes | Key of the data. It cannot be empty. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. | **Return value** -| Type | Description | -| ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| **Example** @@ -613,15 +614,15 @@ Checks whether the storage object contains data with a given key. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty.| **Return value** -| Type | Description | -| ---------------------- | ---------------------------------- | -| Promise<boolean> | Promise used to return the result. | +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| **Example** @@ -647,14 +648,14 @@ Deletes data with the specified key from this storage object. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty.| **Example** ```js -storage.deleteSync('startup') + storage.deleteSync('startup'); ``` @@ -668,9 +669,9 @@ Deletes data with the specified key from this storage object. This API uses an a **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------ | -| key | string | Yes | Key of the data. It cannot be empty. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty.| | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -696,14 +697,14 @@ Deletes data with the specified key from this storage object. This API uses a pr **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ---------------- | -| key | string | Yes | Key of the data. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------------- | +| key | string | Yes | Key of the data.| **Return value** -| Type | Description | -| ------------------- | ------------------------------ | +| Type | Description | +| ------------------- | --------------------------- | | Promise<void> | Promise that returns no value. | **Example** @@ -729,7 +730,7 @@ Saves the modification of this object to the **Storage** instance and synchroniz **Example** ```js -storage.flushSync() +storage.flushSync(); ``` @@ -743,8 +744,8 @@ Saves the modification of this object to the **Storage** instance and synchroniz **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -770,8 +771,8 @@ Saves the modification of this object to the **Storage** instance and synchroniz **Return value** -| Type | Description | -| ------------------- | ------------------------------ | +| Type | Description | +| ------------------- | --------------------------- | | Promise<void> | Promise that returns no value. | **Example** @@ -797,7 +798,7 @@ Clears this **Storage** object. **Example** ```js -storage.clearSync() +storage.clearSync(); ``` @@ -811,8 +812,8 @@ Clears this **Storage** object. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** @@ -837,9 +838,8 @@ Clears this **Storage** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - -| Type | Description | -| ------------------- | ------------------------------ | +| Type | Description | +| ------------------- | --------------------------- | | Promise<void> | Promise that returns no value. | **Example** @@ -864,10 +864,10 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe **Parameters** -| Name | Type | Description | -| -------- | --------------------------------------------------- | ------------------------------------------------------------ | -| type | string | Event type. The value **change** indicates data change events. | -| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | +| Name | Type | Description | +| -------- | --------------------------------------------------- | ---------------------------------------- | +| type | string | Event type. The value **change** indicates data change events.| +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** @@ -891,10 +891,10 @@ Unsubscribes from data changes. **Parameters** -| Name | Type | Description | -| -------- | --------------------------------------------------- | ------------------------------------------------------------ | -| type | string | Event type. The value **change** indicates data change events. | -| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | +| Name | Type | Description | +| -------- | --------------------------------------------------- | ---------------------------------------- | +| type | string | Event type. The value **change** indicates data change events.| +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** @@ -910,9 +910,9 @@ storage.off('change', observer); **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------- | -| key | string | No | Data changed. | +| Name| Type| Mandatory| Description | +| ---- | -------- | ---- | ---------------- | +| key | string | No | Data changed.| ## ValueType @@ -920,8 +920,8 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Type | Description | -| ------- | ----------------------------- | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type. | \ No newline at end of file +| Type | Description | +| ------- | -------------------- | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 7ad7cfe126f1186189c62cd525098aad770cdabd..09a68ffcbed741da9913afd1a9aff717f5f755c8 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -45,55 +45,50 @@ Stage model: import AbilityStage from '@ohos.application.Ability' let kvManager; export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } } ``` FA model: ```js -import AbilityStage from '@ohos.application.Ability' +import featureAbility from '@ohos.ability.featureAbility' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { userId: '0', userType: distributedData.UserType.SAME_USER_ID - } } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { +} +distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } -} + } + console.log("Created KVManager successfully"); + kvManager = manager; +}); ``` ## distributedData.createKVManager @@ -123,55 +118,46 @@ Stage model: import AbilityStage from '@ohos.application.Ability' let kvManager; export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + }); } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } } ``` FA model: ```js -import AbilityStage from '@ohos.application.Ability' +import featureAbility from '@ohos.ability.featureAbility' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { userId: '0', userType: distributedData.UserType.SAME_USER_ID - } } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } } +distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; +}).catch((err) => { + console.log("Failed to create KVManager: " + JSON.stringify(err)); +}); ``` ## KVManagerConfig @@ -320,7 +306,7 @@ Closes a KV store. This API uses an asynchronous callback to return the result. | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -328,21 +314,21 @@ Closes a KV store. This API uses an asynchronous callback to return the result. let kvStore; let kvManager; const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedData.SecurityLevel.S2, +} +try { kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); + console.log('getKVStore success'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { + console.log('closeKVStore success'); + }); }); } catch (e) { console.log('closeKVStore e ' + e); @@ -378,29 +364,29 @@ Closes a KV store. This API uses a promise to return the result. let kvManager; let kvStore; const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedData.SecurityLevel.S2, } - try { +try { kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { - console.log('closeKVStore success'); - }).catch((err) => { - console.log('closeKVStore err ' + JSON.stringify(err)); - }); + console.log('getKVStore success'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { + console.log('closeKVStore success'); + }).catch((err) => { + console.log('closeKVStore err ' + JSON.stringify(err)); + }); }).catch((err) => { console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); }); - } catch (e) { +} catch (e) { console.log('closeKVStore e ' + e); -} +} ``` @@ -418,7 +404,7 @@ Deletes a KV store. This API uses an asynchronous callback to return the result. | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -574,7 +560,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to service status changes. +Subscribes to service status changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -590,7 +576,6 @@ Subscribes to service status changes. ```js let kvManager; try { - console.log('KVManagerOn'); const deathCallback = function () { console.log('death callback call'); @@ -606,7 +591,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from service status changes. +Unsubscribes from service status changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -615,7 +600,7 @@ Unsubscribes from service status changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| -| deathCallback | Callback<void> | No | Callback used to return a service status change event.| +| deathCallback | Callback<void> | No | Callback for the service status change event. | **Example** @@ -666,16 +651,14 @@ Enumerates the KV store types. Enumerates the KV store security levels. -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - | Name | Value| Description | | --- | ---- | ----------------------- | -| NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public.| -| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| -| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| -| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| -| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| +| NO_LEVEL | 0 | No security level is set for the KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| S0 | 1 | The KV store security level is public.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | ## Constants @@ -2156,7 +2139,7 @@ Adds a KV pair of the specified type to this KV store. This API uses an asynchro | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | | value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -2229,7 +2212,7 @@ Deletes a KV pair from this KV store. This API uses an asynchronous callback to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -2314,7 +2297,7 @@ Deletes KV pairs that meet the specified conditions. This API uses an asynchrono | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -2395,8 +2378,8 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object. | +| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object.| **Example** @@ -2429,7 +2412,7 @@ Backs up an RDB store. This API uses a promise to return the result. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database. This parameter cannot be empty and its length cannot exceed [MAX_KEY_LENGTH](#constants).| +| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| **Return value** @@ -2467,7 +2450,7 @@ Restores an RDB store from a database file. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** @@ -2537,7 +2520,7 @@ Deletes a backup file. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| | callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | **Example** @@ -2600,7 +2583,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2610,7 +2593,7 @@ Subscribes to data changes of the specified type. | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | | type |[SubscribeType](#subscribetype) | Yes |Type of data change. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return a data change event.| +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -2626,7 +2609,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. +Subscribes to the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2635,7 +2618,7 @@ Subscribes to synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event.| **Example** @@ -2650,7 +2633,7 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data changes. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2659,7 +2642,7 @@ Unsubscribes from data changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| **Example** @@ -2686,7 +2669,7 @@ class KvstoreModel { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2695,7 +2678,7 @@ Unsubscribes from data changes. This API returns the result synchronously. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | **Example** @@ -2732,7 +2715,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| +| callback |Asyncallback<void> |Yes |Callback invoked to return the result.| **Example** @@ -2835,7 +2818,7 @@ Writes data to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| +| callback |Asyncallback<void> |Yes |Callback invoked to return the result.| **Example** @@ -2921,7 +2904,7 @@ Deletes KV pairs in batches from this KV store. This API uses an asynchronous ca | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keys |string[] | Yes |KV pairs to delete in batches. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3023,7 +3006,7 @@ Starts the transaction in this KV store. This API uses an asynchronous callback | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3110,7 +3093,7 @@ Commits the transaction in this KV store. This API uses an asynchronous callback | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3172,7 +3155,7 @@ Rolls back the transaction in this KV store. This API uses an asynchronous callb | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3235,7 +3218,7 @@ Sets data synchronization, which can be enabled or disabled. This API uses an as | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3305,7 +3288,7 @@ Sets the data synchronization range. This API uses an asynchronous callback to r | ----- | ------ | ---- | ----------------------- | | localLabels |string[] | Yes |Synchronization labels set for the local device. | | remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -4033,7 +4016,7 @@ Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet]( | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -4205,7 +4188,7 @@ Deletes data of a device. This API uses an asynchronous callback to return the r | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -4287,7 +4270,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. +Subscribes to the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4323,7 +4306,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from synchronization complete events. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4332,7 +4315,7 @@ Unsubscribes from synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | **Example** @@ -4394,7 +4377,7 @@ Unsubscribes from data changes. This API returns the result synchronously. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| **Example** @@ -4445,7 +4428,7 @@ kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4497,7 +4480,7 @@ Sets the default delay allowed for KV store synchronization. This API uses an as | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -5355,7 +5338,7 @@ Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet]( | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -5634,7 +5617,7 @@ Deletes data of the specified device from this KV store. This API uses an asynch | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -5797,7 +5780,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. +Subscribes to synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5833,7 +5816,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from synchronization complete events. This API returns the result synchronously. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5842,7 +5825,7 @@ Unsubscribes from synchronization complete events. This API returns the result s | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback |Callback **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. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index bcbf619bf7173a405eee37f5dac86c5e87a023e9..fc2d7fb5f8b7954d5433e9e1ffafe5dc7bcfdd0a 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).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 +263,7 @@ image.createPixelMap(color, opts) } pixelmap.writePixels(area).then(() => { - const readArea = { pixels: new ArrayBuffer(8), - 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 } - } + console.info('Succeeded to write pixelmap into the specified area.'); }) }).catch(error => { console.log('error: ' + error); @@ -291,17 +288,20 @@ Writes image pixel map data to an area. This API uses an asynchronous callback t **Example** ```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) => { if (error != undefined) { console.info('Failed to write pixelmap into the specified area.'); } else { - const readArea = { - pixels: new ArrayBuffer(20), - offset: 0, - stride: 8, - region: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - } + console.info('Succeeded to write pixelmap into the specified area.'); } }) ``` @@ -330,9 +330,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ```js const color = new ArrayBuffer(96); -const pixelMap = new ArrayBuffer(400); 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."); }).catch((err) => { console.error("Failed to write data from a buffer to a PixelMap."); @@ -358,9 +360,11 @@ Reads image data in an **ArrayBuffer** and writes the data to a **PixelMap** obj ```js const color = new ArrayBuffer(96); -const pixelMap = new ArrayBuffer(400); 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) { console.error("Failed to write data from a buffer to a PixelMap."); return; @@ -387,12 +391,21 @@ Obtains pixel map information of this image. This API uses a promise to return t **Example** ```js -const pixelMap = new ArrayBuffer(400); -pixelMap.getImageInfo().then(function(info) { - console.log("Succeeded in obtaining the image pixel map information."); -}).catch((err) => { - console.error("Failed to obtain the image pixel map information."); -}); +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } +image.createPixelMap(color, opts).then(pixelmap => { + 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."); + } + }) +}) ``` ### getImageInfo7+ @@ -412,8 +425,20 @@ Obtains pixel map information of this image. This API uses an asynchronous callb **Example** ```js -pixelmap.getImageInfo((imageInfo) => { - console.log("Succeeded in obtaining the image pixel map information."); +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err, pixelmap) => { + if (pixelmap == undefined) { + 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 **Example** ```js -async function () { - await pixelMap.opacity(0.5); -} +var rate = 0.5; +pixelmap.opacity(rate, (err) => { + if (err) { + console.error("Failed to set opacity."); + return; + } else { + console.log("Succeeded in setting opacity."); + } +}) ``` ### opacity9+ @@ -528,8 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - await pixelMap.opacity(0.5); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -550,13 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { - if (alphaPixelMap == undefined) { - console.info('Failed to obtain new pixel map.'); - } else { - console.info('Succeed in obtaining new pixel map.'); - } -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -576,14 +603,13 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -let pixelMap = await imageSource.createPixelMap(); -if (pixelMap != undefined) { - pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => { - console.info('Failed to obtain new pixel map.'); - }) -} else { - console.info('Succeed in obtaining new pixel map.'); -} +pixelmap.createAlphaPixelmap((err, alphaPixelMap) => { + if (alphaPixelMap == undefined) { + console.info('Failed to obtain new pixel map.'); + } else { + console.info('Succeed in obtaining new pixel map.'); + } +}) ``` ### scale9+ @@ -605,8 +631,8 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { - await pixelMap.scale(2.0, 1.0); +async function Demo() { + await pixelmap.scale(2.0, 1.0); } ``` @@ -634,8 +660,8 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { - await pixelMap.scale(2.0, 1.0); +async function Demo() { + await pixelmap.scale(2.0, 1.0); } ``` @@ -658,8 +684,8 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { - await pixelMap.translate(3.0, 1.0); +async function Demo() { + await pixelmap.translate(3.0, 1.0); } ``` @@ -687,8 +713,8 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { - await pixelMap.translate(3.0, 1.0); +async function Demo() { + await pixelmap.translate(3.0, 1.0); } ``` @@ -710,8 +736,8 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { - await pixelMap.rotate(90.0); +async function Demo() { + await pixelmap.rotate(90.0); } ``` @@ -738,8 +764,8 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { - await pixelMap.rotate(90.0); +async function Demo() { + await pixelmap.rotate(90.0); } ``` @@ -762,8 +788,8 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { - await pixelMap.flip(false, true); +async function Demo() { + await pixelmap.flip(false, true); } ``` @@ -791,8 +817,8 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { - await pixelMap.flip(false, true); +async function Demo() { + await pixelmap.flip(false, true); } ``` @@ -814,8 +840,8 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { - await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); +async function Demo() { + await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -842,8 +868,8 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { - await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); +async function Demo() { + await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -864,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -893,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -954,7 +970,8 @@ Creates an **ImageSource** instance based on the URI. **Example** ```js -const imageSourceApi = image.createImageSource('/sdcard/test.jpg'); +var sourceOptions = { sourceDensity: 120 }; +let imageSource = image.createImageSource('test.png', sourceOptions); ``` ## image.createImageSource7+ @@ -1007,7 +1024,8 @@ Creates an **ImageSource** instance based on the file descriptor. **Example** ```js -const imageSourceApi = image.createImageSource(fd); +var sourceOptions = { sourceDensity: 120 }; +const imageSourceApi = image.createImageSource(0, sourceOptions); ``` ## image.createImageSource9+ @@ -1059,9 +1077,9 @@ const data = new ArrayBuffer(112); const imageSourceApi = image.createImageSource(data); ``` -## image.CreateIncrementalSource9+ +## image.createIncrementalSource9+ -CreateIncrementalSource(buf: ArrayBuffer): ImageSource +createIncrementalSource(buf: ArrayBuffer): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1083,12 +1101,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); -const imageSourceApi = image.CreateIncrementalSource(buf); +const imageSourceIncrementalSApi = image.createIncrementalSource(buf); ``` -## image.CreateIncrementalSource9+ +## image.createIncrementalSource9+ -CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource +createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1111,7 +1129,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); -const imageSourceApi = image.CreateIncrementalSource(buf); +const imageSourceIncrementalSApi = image.createIncrementalSource(buf); ``` ## ImageSource @@ -1124,7 +1142,7 @@ Provides APIs to obtain image information. Before calling any API in **ImageSour | Name | Type | Readable| Writable| Description | | ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | -| supportedFormats | Array\ | Yes | No | Supported image formats, including png, jpeg, wbmp, bmp, gif, webp, and heif.| +| supportedFormats | Array\ | Yes | No | Supported image formats, including PNG, JPEG, BMP, GIF, WebP, and RAW.| ### getImageInfo @@ -1282,7 +1300,7 @@ Obtains the value of a property in this image. This API uses an asynchronous cal **Example** ```js -const property = new ArrayBuffer(400); +let property = { index: 0, defaultValue: '9999' } imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => { if(error) { console.log('Failed to get the value of the specified attribute key of the image.'); @@ -1316,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1372,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1400,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1477,7 +1494,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Example** ```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 => { console.log('Succeeded in creating pixelmap object.'); }) @@ -1551,7 +1576,7 @@ const imagePackerApi = image.createImagePacker(); ## 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 @@ -1580,8 +1605,8 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; -const imageSourceApi = new ArrayBuffer(400); imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1610,7 +1635,6 @@ Packs an image. This API uses a promise to return the result. ```js let packOpts = { format:"image/jpeg", quality:98 } -const imageSourceApi = new ArrayBuffer(400); imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { console.log('packing succeeded.'); @@ -1638,10 +1662,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelMapApi, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1669,14 +1697,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelMapApi, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -2112,7 +2144,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | 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.| ## ImageInfo @@ -2146,8 +2178,8 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888.| -| BGRA_88889+ | 4 | BGRA_8888.| +| RGBA_8888 | 3 | RGBA_8888. | +| BGRA_88889+ | 4 | BGRA_8888. | ## AlphaType9+ @@ -2159,8 +2191,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2236,7 +2268,7 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp. | +| format | string | Yes | Yes | Format of the packed image.
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.| ## GetImagePropertyOptions7+ diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 96b190f1f7f9166c68ef1fda64bb9a98bf6b269d..94499cdc9ad1f967bc4e2c2a3c1c7efe46fc5923 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -163,9 +163,9 @@ Only one **AudioRecorder** instance can be created per device. **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------- | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created.| +| Type | Description | +| ----------------------------------------- | ------------------------------------------------------------ | +| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the **VideoRecorder** instance created. | **Example** @@ -275,15 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| 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.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.INTERNET| -| fdSrc9+ | [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.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.
| -| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | -| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | -| currentTime | number | Yes | No | Current audio playback position, 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()**.| +| 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.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| +| fdSrc9+ | [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.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.
| +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | +| currentTime | number | Yes | No | Current audio playback position, 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()**.| ### play play(): void @@ -442,7 +442,7 @@ function printfDescription(obj) { } } -audioPlayer.getTrackDescription((error, ) => { +audioPlayer.getTrackDescription((error, arrlist) => { if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); @@ -680,7 +680,7 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.INTERNET| +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| | fdSrc9+ | [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.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | @@ -1795,7 +1795,7 @@ Subscribes to the audio recording events. ```js let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, , + audioEncoder : media.AudioEncoder.AAC_LC, audioEncodeBitRate : 22050, audioSampleRate : 22050, numberOfChannels : 2, @@ -1850,7 +1850,7 @@ Subscribes to audio recording error events. After an error event is reported, yo ```js let audioRecorderConfig = { - audioEncoder : media.AudioEncoder.AAC_LC, , + audioEncoder : media.AudioEncoder.AAC_LC, audioEncodeBitRate : 22050, audioSampleRate : 22050, numberOfChannels : 2, @@ -1974,29 +1974,13 @@ let videoConfig = { } // asyncallback -let videoRecorder = null; -let events = require('events'); -let eventEmitter = new events.EventEmitter(); - -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. +videoRecorder.prepare(videoConfig, (err) => { + if (err == null) { + console.info('prepare success'); } else { - console.info('createVideoRecorder failed and error is ' + err.message); + console.info('prepare failed and error is ' + err.message); } -}); +}) ``` ### prepare9+ @@ -2047,21 +2031,10 @@ let videoConfig = { } // promise -let videoRecorder = null; -media.createVideoRecorder().then((recorder) => { - 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'); - } +videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); }).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 **Example** ```js +// This event is reported when an error occurs during the retrieval of videoRecordState. videoRecorder.on('error', (error) => { // Set the 'error' event callback. console.info(`audio error called, error: ${error}`); -} -// This event is reported when an error occurs during the retrieval of videoRecordState. -}); +}) ``` ## VideoRecordState9+ diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index e805a8d3172b2ec12f05a4fe39034be08d249905..2887044269488b47e2a4f434447b43d617a16f05 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -2,10 +2,10 @@ > **NOTE** > -> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import mediaLibrary from '@ohos.multimedia.mediaLibrary'; ``` @@ -33,17 +33,18 @@ This API can be used only in the stage model. **Example (from API version 9)** -``` -var media = mediaLibrary.getMediaLibrary(this.context); +```ts +const context = getContext(this); +let media = mediaLibrary.getMediaLibrary(context); ``` **Example (API version 8)** -``` +```js import featureAbility from '@ohos.ability.featureAbility'; -var context = featureAbility.getContext() -var media = mediaLibrary.getMediaLibrary(context); +let context = featureAbility.getContext(); +let media = mediaLibrary.getMediaLibrary(context); ``` ## mediaLibrary.getMediaLibrary @@ -68,7 +69,7 @@ This API can be used only in the FA model. **Example** ```js -var media = mediaLibrary.getMediaLibrary(); +let media = mediaLibrary.getMediaLibrary(); ``` ## MediaLibrary @@ -93,24 +94,45 @@ Obtains file assets (also called files). This API uses an asynchronous callback **Example** -``` -let fileKeyObj = mediaLibrary.FileKey -let imageType = mediaLibrary.MediaType.IMAGE -let imagesfetchOp = { +```js +let fileKeyObj = mediaLibrary.FileKey; +let imageType = mediaLibrary.MediaType.IMAGE; +let imagesFetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -media.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { - if (fetchFileResult != undefined) { - console.info('mediaLibraryTest : ASSET_CALLBACK fetchFileResult success'); - fetchFileResult.getAllObject((err, fileAssetList) => { - if (fileAssetList != undefined) { - fileAssetList.forEach(function(getAllObjectInfo){ - console.info("getAllObjectInfo.displayName :" + getAllObjectInfo.displayName); - }); - } - }); +media.getFileAssets(imagesFetchOp, (error, fetchFileResult) => { + if (fetchFileResult == undefined) { + console.error('Failed to get fetchFileResult: ' + error); + return; } + const count = fetchFileResult.getCount(); + if (count < 0) { + console.error('Failed to get count from fetchFileResult: count: ' + count); + return; + } + if (count == 0) { + console.info('The count of fetchFileResult is zero'); + return; + } + + console.info('Get fetchFileResult success, count: ' + count); + fetchFileResult.getFirstObject((err, fileAsset) => { + if (fileAsset == undefined) { + console.error('Failed to get first object: ' + err); + return; + } + console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + for (let i = 1; i < count; i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (fileAsset == undefined) { + console.error('Failed to get next object: ' + err); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } + }); }); ``` ### getFileAssets7+ @@ -137,17 +159,38 @@ Obtains file assets. This API uses a promise to return the result. **Example** -``` -let fileKeyObj = mediaLibrary.FileKey -let imageType = mediaLibrary.MediaType.IMAGE -let imagesfetchOp = { +```js +let fileKeyObj = mediaLibrary.FileKey; +let imageType = mediaLibrary.MediaType.IMAGE; +let imagesFetchOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], }; -media.getFileAssets(imagesfetchOp).then(function(fetchFileResult){ - console.info("getFileAssets successfully: image number is "+ fetchFileResult.getCount()); +media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { + const count = fetchFileResult.getCount(); + if (count < 0) { + console.error('Failed to get count from fetchFileResult: count: ' + count); + return; + } + if (count == 0) { + console.info('The count of fetchFileResult is zero'); + return; + } + console.info('Get fetchFileResult success, count: ' + count); + fetchFileResult.getFirstObject().then(function(fileAsset) { + console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + for (let i = 1; i < count; i++) { + fetchFileResult.getNextObject().then(function(fileAsset) { + console.log('fileAsset.displayName ' + ': ' + fileAsset.displayName); + }).catch(function(err) { + console.error('Failed to get next object: ' + err); + }) + } + }).catch(function(err) { + console.error('Failed to get first object: ' + err); + }); }).catch(function(err){ - console.info("getFileAssets failed with error:"+ err); + console.error("Failed to get file assets: " + err); }); ``` @@ -168,7 +211,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback **Example** -``` +```js media.on('imageChange', () => { // image file had changed, do something }) @@ -190,13 +233,13 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb **Example** -``` +```js media.off('imageChange', () => { // stop listening success }) ``` -### createAsset 8+ +### createAsset8+ createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void @@ -217,7 +260,7 @@ Creates a media asset. This API uses an asynchronous callback to return the resu **Example** -``` +```js async function example() { // Create an image file in callback mode. let mediaType = mediaLibrary.MediaType.IMAGE; @@ -259,7 +302,7 @@ Creates a media asset. This API uses a promise to return the result. **Example** -``` +```js let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ console.info("getPublicDirectory successfully:"+ JSON.stringify(dicResult)); @@ -268,6 +311,101 @@ media.getPublicDirectory(DIR_CAMERA).then(function(dicResult){ }); ``` +### deleteAsset8+ + +deleteAsset(uri: string): Promise\ + +Deletes a file asset. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------- | +| uri | string | Yes | URI of the file asset to delete.| + +**Return value** +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + media.deleteAsset(asset.uri).then(() => { + console.info("deleteAsset successfully"); + }).catch((err) => { + console.info("deleteAsset failed with error:"+ err); + }); +} +``` + +### deleteAsset8+ +deleteAsset(uri: string, callback: AsyncCallback\): void + +Deletes a file asset. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------- | +| uri | string | Yes | URI of the file asset to delete.| +|callback |AsyncCallback\| Yes |Callback used to return the result.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + media.deleteAsset(asset.uri, (err) => { + if (err != undefined) { + console.info("deleteAsset successfully"); + } else { + console.info("deleteAsset failed with error:"+ err); + } + }); +} +``` + ### getPublicDirectory8+ getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void @@ -285,7 +423,7 @@ Obtains a public directory. This API uses an asynchronous callback to return the **Example** -``` +```js let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; media.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { if (dicResult == 'Camera/') { @@ -318,7 +456,7 @@ Obtains a public directory. This API uses a promise to return the result. **Example** -``` +```js async function example() { let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; const dicResult = await media.getPublicDirectory(DIR_CAMERA); @@ -349,7 +487,7 @@ Obtains the albums. This API uses an asynchronous callback to return the result. **Example** -``` +```js let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], @@ -389,7 +527,7 @@ Obtains the albums. This API uses a promise to return the result. **Example** -``` +```js let AlbumNoArgsfetchOp = { selections: '', selectionArgs: [], @@ -418,7 +556,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in **Example** -``` +```js var media = mediaLibrary.getMediaLibrary(context); media.release((err) => { // do something @@ -442,7 +580,7 @@ Call this API when you no longer need to use the APIs in the **MediaLibrary** in **Example** -``` +```js media.release() ``` @@ -467,7 +605,7 @@ Stores a media asset. This API uses an asynchronous callback to return the URI t **Example** - ``` +```js let option = { src : "/data/storage/el2/base/haps/entry/image.png", mimeType : "image/*", @@ -481,7 +619,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option, (err, value) => { console.log("Media asset stored."); // Obtain the URI that stores the media asset. }); - ``` +``` ### storeMediaAsset(deprecated) @@ -510,7 +648,7 @@ Stores a media asset. This API uses a promise to return the URI that stores the **Example** - ``` +```js let option = { src : "/data/storage/el2/base/haps/entry/image.png", mimeType : "image/*", @@ -522,7 +660,7 @@ mediaLibrary.getMediaLibrary().storeMediaAsset(option).then((value) => { }).catch((err) => { console.log("An error occurred when storing the media assets."); }); - ``` +``` ### startImagePreview(deprecated) @@ -547,7 +685,7 @@ Starts image preview, with the first image to preview specified. This API can be **Example** - ``` +```js let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" @@ -566,7 +704,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index, (err) => { } console.log("Succeeded in previewing the images."); }); - ``` +``` ### startImagePreview(deprecated) @@ -590,7 +728,7 @@ Starts image preview. This API can be used to preview local images whose URIs st **Example** - ``` +```js let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" @@ -608,7 +746,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, (err) => { } console.log("Succeeded in previewing the images."); }); - ``` +``` ### startImagePreview(deprecated) @@ -638,7 +776,7 @@ Starts image preview, with the first image to preview specified. This API can be **Example** - ``` +```js let images = [ "dataability:///media/xxxx/2", "dataability:///media/xxxx/3" @@ -655,7 +793,7 @@ mediaLibrary.getMediaLibrary().startImagePreview(images, index).then(() => { }).catch((err) => { console.log("An error occurred when previewing the images."); }); - ``` +``` ### startMediaSelect(deprecated) @@ -674,13 +812,13 @@ Starts media selection. This API uses an asynchronous callback to return the lis | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------------ | -| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option. | +| option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option. | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the list of URIs (starting with **dataability://**) that store the selected media assets.| **Example** - ``` -let option = { +```js +let option : mediaLibrary.MediaSelectOption = { type : "media", count : 2 }; @@ -692,7 +830,7 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option, (err, value) => { console.log("Media asset selected."); // Obtain the media selection value. }); - ``` +``` ### startMediaSelect(deprecated) @@ -711,7 +849,7 @@ Starts media selection. This API uses a promise to return the list of URIs that | Name | Type | Mandatory | Description | | ------ | --------------------------------------- | ---- | ------- | -| option | [MediaSelectOption](#mediaselectoption) | Yes | Media selection option.| +| option | [MediaSelectOption](#mediaselectoptiondeprecated) | Yes | Media selection option.| **Return value** @@ -721,8 +859,8 @@ Starts media selection. This API uses a promise to return the list of URIs that **Example** - ``` -let option = { +```js +let option : mediaLibrary.MediaSelectOption = { type : "media", count : 2 }; @@ -733,7 +871,155 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { console.log("An error occurred when selecting the media assets."); }); - ``` +``` +### getActivePeers8+ + +getActivePeers(): Promise\>; + +Obtains information about online peer devices. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| + +**Example** + +```js +async function example() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + media.getActivePeers().then((devicesInfo) => { + if (devicesInfo != undefined) { + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed info is undefined!') + } + }).catch((err) => { + console.info("get distributed info failed with error:" + err); + }); +} +``` + +### getActivePeers8+ + +getActivePeers(callback: AsyncCallback\>): void; + +Obtains information about online peer devices. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| callback: AsyncCallback\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| + +**Example** + +```js +async function example() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + media.getActivePeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail, message = ' + err) + } + }) +} +``` + + +### getAllPeers8+ + +getAllPeers(): Promise\>; + +Obtains information about all peer devices. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| + +**Example** + +```js +async function example() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + media.getAllPeers().then((devicesInfo) => { + if (devicesInfo != undefined) { + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed info is undefined!') + } + }).catch((err) => { + console.info("get distributed info failed with error:" + err); + }); +} +``` + +### getAllPeers8+ + +getAllPeers(callback: AsyncCallback\>): void; + +Obtains information about online peer devices. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.READ_MEDIA + +**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| callback: AsyncCallback\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| + +**Example** + +```js +async function example() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + media.getAllPeers((err, devicesInfo) => { + if (devicesInfo != undefined) { + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail, message = ' + err) + } + }) +} +``` ## FileAsset7+ @@ -786,7 +1072,7 @@ Checks whether this file asset is a directory. This API uses an asynchronous cal **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -822,7 +1108,7 @@ Checks whether this file asset is a directory. This API uses a promise to return **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -860,7 +1146,7 @@ Commits the modification in this file asset to the database. This API uses an as **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -897,7 +1183,7 @@ Commits the modification in this file asset to the database. This API uses a pro **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -937,7 +1223,7 @@ Opens this file asset. This API uses an asynchronous callback to return the resu **Example** -``` +```js async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; @@ -981,7 +1267,7 @@ Opens this file asset. This API uses a promise to return the result. **Example** -``` +```js async function example() { let mediaType = mediaLibrary.MediaType.IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; @@ -1016,7 +1302,7 @@ Closes this file asset. This API uses an asynchronous callback to return the res **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -1032,7 +1318,7 @@ async function example() { console.info('File fd!' + fd); asset.close(fd, (closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : close : FAIL ' + closeErr); console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { console.info("=======asset.close success====>"); @@ -1069,7 +1355,7 @@ Closes this file asset. This API uses a promise to return the result. **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -1085,7 +1371,7 @@ async function example() { console.info('File fd!' + fd); asset.close(fd).then((closeErr) => { if (closeErr != undefined) { - console.info('mediaLibraryTest : close : FAIL ' + closeErr.message); + console.info('mediaLibraryTest : close : FAIL ' + closeErr); console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); } else { @@ -1117,7 +1403,7 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback **Example** -``` +```js async function example() { let fileKeyObj = mediaLibrary.FileKey let imageType = mediaLibrary.MediaType.IMAGE; @@ -1130,7 +1416,7 @@ async function example() { const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }); } ``` @@ -1154,9 +1440,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1168,7 +1454,7 @@ async function example() { const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }); } ``` @@ -1197,9 +1483,9 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1212,7 +1498,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size) .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail Successful '+ pixelmap); }) .catch((err) => { console.info('mediaLibraryTest : getThumbnail fail'+ err); @@ -1239,9 +1525,9 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1281,9 +1567,9 @@ Favorites or unfavorites this file asset. This API uses a promise to return the **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1319,9 +1605,9 @@ Checks whether this file asset is favorited. This API uses an asynchronous callb **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1359,9 +1645,9 @@ Checks whether this file asset is favorited. This API uses a promise to return t **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1400,9 +1686,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1445,9 +1731,9 @@ Files in the trash are not actually deleted. You can set **isTrash** to **false* **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1483,9 +1769,9 @@ Checks whether this file asset is in the trash. This API uses an asynchronous ca **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1495,18 +1781,13 @@ async function example() { }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); - asset.isTrash(isTrashCallBack); - function isTrashCallBack(err, isTrash) { - if (isTrash == true) { - console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK isTrash = ' + isTrash); - asset.trash(true, istrashCallBack); - - } else { - console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessful = ' + err); - console.info('mediaLibraryTest : ASSET_CALLBACK isTrash : FAIL'); - - } - } + asset.isTrash((err, isTrash) => { + if (isTrash == undefined) { + console.error('Failed to get trash state: ' + err); + return; + } + console.info('Get trash state success: ' + isTrash); + }); } ``` @@ -1528,22 +1809,21 @@ Checks whether this file asset is in the trash. This API uses a promise to retur **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', selectionArgs: [imageType.toString()], order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", }; const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.isTrash().then(function(isTrash){ - console.info("isTrash result:"+ isTrash); + console.info("isTrash result: " + isTrash); }).catch(function(err){ - console.info("isTrash failed with error:"+ err); + console.error("isTrash failed with error: " + err); }); } ``` @@ -1568,9 +1848,9 @@ Obtains the total number of files in the result set. **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let fileType = mediaLibrary.MediaType.FILE; let getFileCountOneOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1599,9 +1879,9 @@ Checks whether the cursor is in the last row of the result set. **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1637,9 +1917,9 @@ Releases and invalidates this **FetchFileResult** instance. Other APIs in this i **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1668,9 +1948,9 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1705,9 +1985,9 @@ Obtains the first file asset in the result set. This API uses a promise to retur **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1740,9 +2020,9 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1777,9 +2057,9 @@ Obtains the next file asset in the result set. This API uses a promise to return **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1810,9 +2090,9 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1847,9 +2127,9 @@ Obtains the last file asset in the result set. This API uses a promise to return **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1879,9 +2159,9 @@ Obtains a file asset with the specified index in the result set. This API uses a **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1922,9 +2202,9 @@ Obtains a file asset with the specified index in the result set. This API uses a **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1934,9 +2214,9 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getPositionObject(1) .then(function (fileAsset){ - console.log('[Demo] fileAsset.displayName : ' + fileAsset.displayName); + console.log('fileAsset.displayName : ' + fileAsset.displayName); }).catch(function (err) { - console.info("[Demo] getFileAssets failed with error:" + err); + console.info("getFileAssets failed with error:" + err); }); } ``` @@ -1957,9 +2237,9 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -1969,11 +2249,13 @@ async function example() { }; let fetchFileResult = await media.getFileAssets(getImageOp); fetchFileResult.getAllObject((err, fileAsset) => { - if (err) { + if (err) { console.error('Failed '); return; - } - console.log('fileAsset.displayName : ' + fileAsset.displayName); + } + for (let i = 0; i < fetchFileResult.getCount(); i++) { + console.log('fileAsset.displayName : ' + fileAsset[i].displayName); + } }) } ``` @@ -1994,9 +2276,9 @@ Obtains all the file assets in the result set. This API uses a promise to return **Example** -``` +```js async function example() { - let fileKeyObj = mediaLibrary.FileKey + let fileKeyObj = mediaLibrary.FileKey; let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { selections: fileKeyObj.MEDIA_TYPE + '= ?', @@ -2045,7 +2327,7 @@ Commits the modification in the album attributes to the database. This API uses **Example** -``` +```js async function example() { let AlbumNoArgsfetchOp = { selections: '', @@ -2082,7 +2364,7 @@ Commits the modification in the album attributes to the database. This API uses **Example** -``` +```js async function example() { let AlbumNoArgsfetchOp = { selections: '', @@ -2118,7 +2400,7 @@ Obtains the file assets in this album. This API uses an asynchronous callback to **Example** -``` +```js async function example() { let AlbumNoArgsfetchOp = { selections: '', @@ -2161,7 +2443,7 @@ Obtains the file assets in this album. This API uses a promise to return the res **Example** -``` +```js async function example() { let AlbumNoArgsfetchOp = { selections: '', @@ -2170,7 +2452,7 @@ async function example() { let fileNoArgsfetchOp = { selections: '', selectionArgs: [], - } + }; const albumList = await media.getAlbums(AlbumNoArgsfetchOp); const album = albumList[0]; album.getFileAssets(fileNoArgsfetchOp).then(function(albumFetchFileResult){ @@ -2184,7 +2466,8 @@ async function example() { ## PeerInfo8+ Describes information about a registered device. -This is a system API. + +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore @@ -2256,7 +2539,8 @@ Enumerates directory types. ## DeviceType8+ Enumerates device types. -This is a system API. + +**System API**: This is a system API. **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore @@ -2280,7 +2564,7 @@ Describes options for fetching media files. | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | | selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | -| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC" | +| order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " ASC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | | networkId8+ | string | Yes | Yes | No | Network ID of the registered device. | | extendArgs8+ | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | @@ -2288,6 +2572,7 @@ Describes options for fetching media files. ## Size8+ Describes the image size. + **System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Type | Readable | Writable | Description | diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index e26e01dc8f8d7fbb6472d11217f1156ceb1b41b8..f08032456915595af5da869b74aa0ab1888ffb6b 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,10 +1,10 @@ -# ProcessRunningInfo +# ProcessRunningInfo(deprecated) The **ProcessRunningInfo** 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. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-processrunninginformation.md) instead. +> - The initial APIs of this module are supported since API version 8. ## Usage @@ -19,9 +19,9 @@ appManager.getProcessRunningInfos((error,data) => { ## 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.| | uid | number | Yes| No| User ID.| diff --git a/en/application-dev/reference/apis/js-apis-processrunninginformation.md b/en/application-dev/reference/apis/js-apis-processrunninginformation.md new file mode 100644 index 0000000000000000000000000000000000000000..a5add77380e1a9173f9d1d1b1e44b2dfee5be38c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-processrunninginformation.md @@ -0,0 +1,29 @@ +# ProcessRunningInformation9+ + +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<string> | Yes| No| Names of all running bundles in the process.| diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index b590efb7ca3455c95c3d217b86e741848c5ac547..77dd0bc0560d11837a5cfbb68f38fd3f39075310 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1041,7 +1041,7 @@ promise1.then(() => { console.log('connect success'); let promise2 = tcp.getRemoteAddress(); promise2.then(() => { - console.log('getRemoteAddress success:' + JSON.stringify(data)); + console.log('getRemoteAddress success'); }).catch(err => { console.log('getRemoteAddressfail'); }); @@ -1120,7 +1120,7 @@ promise.then(() => { console.log('connect success'); let promise1 = tcp.getState(); promise1.then(() => { - console.log('getState success:' + JSON.stringify(data)); + console.log('getState success'); }).catch(err => { console.log('getState fail'); }); diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index a551dea9a8f79c5d153649ce69dc912f93ddd4b6..7df5f6675bb53168935ada36ca1d0675e49da978 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -21,9 +21,9 @@ import sensor from '@system.sensor'; ## Error Codes -| Error Code | Description | -| ---- | -------------- | -| 900 | The current device does not support the corresponding sensor.| +| Error Code | Description | +| ---------- | ---------------------------------------- | +| 900 | The current device does not support the corresponding sensor. | ## sensor.subscribeAccelerometer @@ -37,19 +37,19 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | ------- | -| x | number | Acceleration on the x-axis.| -| y | number | Acceleration on the y-axis.| -| z | number | Acceleration on the z-axis.| +| Name | Type | Description | +| ---- | ------ | --------------------------- | +| x | number | Acceleration on the x-axis. | +| y | number | Acceleration on the y-axis. | +| z | number | Acceleration on the z-axis. | **Example** @@ -97,16 +97,16 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the compass sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the compass sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ---------- | -| direction | number | Direction of the device, in degrees.| +| Name | Type | Description | +| --------- | ------ | ------------------------------------ | +| direction | number | Direction of the device, in degrees. | **Example** @@ -149,16 +149,16 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ----------------- | -| success | Function | Yes | Called when the proximity sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the proximity sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | --------------------- | -| distance | number | Distance between a visible object and the device screen.| +| Name | Type | Description | +| -------- | ------ | ---------------------------------------- | +| distance | number | Distance between a visible object and the device screen. | **Example** @@ -201,16 +201,16 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the ambient light sensor data changes| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the ambient light sensor data changes | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------ | -| intensity | number | Light intensity, in lux.| +| Name | Type | Description | +| --------- | ------ | ------------------------ | +| intensity | number | Light intensity, in lux. | **Example** @@ -255,16 +255,16 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the step counter sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the step counter sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------ | --------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Description | +| ----- | ------ | ---------------------------------------- | +| steps | number | Number of counted steps after the sensor is restarted.
| **Example** @@ -302,7 +302,7 @@ sensor.unsubscribeStepCounter(); ## sensor.subscribeBarometer -subcribeBarometer(Object): void +subscribeBarometer(Object): void Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -310,16 +310,16 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the barometer sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the barometer sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | ----------- | -| pressure | number | Pressure, in pascal.| +| Name | Type | Description | +| -------- | ------ | -------------------- | +| pressure | number | Pressure, in pascal. | **Example** @@ -366,16 +366,16 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ---- | -| heartRate | number | Heart rate.| +| Name | Type | Description | +| --------- | ------ | ----------- | +| heartRate | number | Heart rate. | **Example** @@ -421,16 +421,16 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------- | -| success | Function | Yes | Called when the wearing state changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | -------------------------------------- | +| success | Function | Yes | Called when the wearing state changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Description | +| ----- | ------- | ------------------------------------ | +| value | boolean | Whether the wearable device is worn. | **Example** @@ -473,17 +473,17 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ------------ | -| success | Function | No | Callback upon success.| -| fail | Function | No | Callback upon failure.| -| complete | Function | No | Called when the execution is complete.| +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | -------------------------------------- | +| success | Function | No | Callback upon success. | +| fail | Function | No | Callback upon failure. | +| complete | Function | No | Called when the execution is complete. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Description | +| ----- | ------- | ------------------------------------ | +| value | boolean | Whether the wearable device is worn. | **Example** @@ -510,18 +510,18 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | +| Name | Type | Description | | ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| +| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth. | +| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth. | +| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth. | **Example** @@ -571,19 +571,19 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | --------- | -| x | number | Rotation angular velocity of the X axis.| -| y | number | Rotation angular velocity of the Y axis.| -| z | number | Rotation angular velocity of the Z axis.| +| Name | Type | Description | +| ---- | ------ | ---------------------------------------- | +| x | number | Rotation angular velocity of the X axis. | +| y | number | Rotation angular velocity of the Y axis. | +| z | number | Rotation angular velocity of the Z axis. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md new file mode 100644 index 0000000000000000000000000000000000000000..60690327946699362eb5b86deaaae3b438897e3e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -0,0 +1,81 @@ +# Facial Authentication + +The **userIAM.faceAuth** module provides APIs for face enrollment. + +> **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 APIs provided by this module are system APIs. + +## Modules to Import + +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +``` + +## FaceAuthManager + +Provides APIs for facial authentication management. + +### constructor + +constructor() + +A constructor used to create a **FaceAuthManager** object. + +**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| [FaceAuthManager](#faceauthmanager) | **FaceAuthManager** object.| + +**Example** + + ```js + import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + + let faceAuthManager = new userIAM_faceAuth.FaceAuthManager() + ``` + +### setSurfaceId + +setSurfaceId(surfaceId: string): ResultCode; + +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. + +**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------- | ---- | -------------------------- | +| surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| + +**Return value** + +| Type | Description | +| ---------- | ------------------------------------------------------------ | +| [ResultCode](#resultcode) | Operation result code.| + +**Example** + + ```js + import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + + let faceAuthManager = new userIAM_faceAuth.FaceAuthManager() + faceAuthManager.setSurfaceId("0"); + ``` + +## ResultCode + + Enumerates the operation result codes. + + **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +| Name | Default Value| Description | +| ----------------------- | ------ | -------------------- | +| SUCCESS | 0 | The operation is successful. | +| FAIL | 1 | The operation fails. | diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index d98f43faaf7bc2a575cfa80907a776d9436bfbff..a43b77bcf631b9ad1c2882a841af545fbe9669fd 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -119,8 +119,6 @@ constructor() A constructor used to create an **authenticator** object. -**Required permissions**: ohos.permission.ACCESS_BIOMETRIC - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** @@ -279,7 +277,8 @@ Cancels an authentication. // contextId can be obtained using auth(). In this example, it is defined here. let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let cancelCode = auth.cancel(contextId); + let auth = new userIAM_userAuth.UserAuth(); + let cancelCode = auth.cancelAuth(contextId); if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("cancel auth success"); } else { @@ -492,11 +491,10 @@ getAuthenticator(): Authenticator Obtains an **Authenticator** object for user authentication. -**Required permissions**: ohos.permission.ACCESS_BIOMETRIC - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** + | Type | Description | | ----------------------------------------- | ------------ | | [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| @@ -516,7 +514,7 @@ Provides methods to manage an **Authenticator** object. ### execute(deprecated) -execute(type: string, level: string, callback: AsyncCallback<number>): void +execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void > **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). @@ -531,8 +529,8 @@ Performs user authentication. This API uses asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| | callback | AsyncCallback<number> | No | Callback used to return the result. | Parameters returned in callback @@ -543,19 +541,20 @@ Performs user authentication. This API uses asynchronous callback to return the **Example** ```js - authenticator.execute("FACE_ONLY", "S2", (code)=>{ - if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { + let authenticator = userIAM_userAuth.getAuthenticator(); + authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { console.info("auth success"); return; } console.error("auth fail, code = " + code); - }) + }); ``` ### execute(deprecated) -execute(type:string, level:string): Promise<number> +execute(type:AuthType, level:SecureLevel): Promise<number> > **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). @@ -567,26 +566,28 @@ Performs user authentication. This API uses a promise to return the result. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| **Return value** + | Type | Description | | --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** -```js -let authenticator = userIAM_userAuth.getAuthenticator(); -authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); -}).catch((code)=>{ - console.error("auth fail, code = " + code); -}); -``` + ```js + let authenticator = userIAM_userAuth.getAuthenticator(); + authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); + }).catch((error)=>{ + console.error("auth fail, code = " + error); + }); + ``` ## AuthenticationResult(deprecated) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index 066da49683ce647db66b9c8cdecd551550b23844..2ce4c7d3b07a6e8dbdcd47c4d3143ec8e4b285df 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -20,44 +20,44 @@ Not supported In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -| Name | Type | Default Value | Mandatory | Description | -| -------------------------------- | ----------------------- | --------- | ---- | ---------------------------------------- | -| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| -| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | -| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | -| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| -| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**.| -| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | -| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| -| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| -| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | -| menuoptions5+ | Array<MeunOption> | - | No | Menu options displayed after users click the **More** button. | -| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| -| selectedstart6+ | number | -1 | No | Start position for text selection. | -| selectedend6+ | number | -1 | No | End position for text selection. | -| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | -| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | +| Name | Type | Default Value | Mandatory | Description | +| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded. | +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. | +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. | +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard. | +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. | +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. | +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | **Table 1** MenuOption5+ -| Name | Type | Description | -| ------- | ------ | ----------- | -| icon | string | Path of the icon for a menu option.| -| content | string | Text content of a menu option.| +| Name | Type | Description | +| ------- | ------ | ----------------------------------- | +| icon | string | Path of the icon for a menu option. | +| content | string | Text content of a menu option. | ## Styles In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory | Description | -| ------------------------ | -------------------------- | ---------- | ---- | ---------------------------------------- | -| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | -| font-size | <length> | 16px | No | Font size of the single-line text box or button. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | -| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | -| caret-color6+ | <color> | - | No | Color of the caret. | +| Name | Type | Default Value | Mandatory | Description | +| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | +| caret-color6+ | <color> | - | No | Color of the caret. | ## Events @@ -65,31 +65,31 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - - | Name | Parameter | Description | + + | Name | Parameter | Description | | ------------------------- | ---------------------------------------- | ---------------------------------------- | - | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| - | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| - | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| - | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| - | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| - | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| - | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | + | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered. | + | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. | + | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. | + | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. | + | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. | + | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. | + | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | - When **type** is set to **checkbox** or **radio**, the following events are supported. - - | Name | Parameter | Description | - | ------ | ---------------------------------------- | ---------------------------------------- | - | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| + + | Name | Parameter | Description | + | ------ | --------------------------------- | ---------------------------------------- | + | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes. | ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | +| Name | Parameter | Description | | ------------------- | ---------------------------------------- | ---------------------------------------- | -| focus | {
focus: true\|false
}:
If **focus** is not passed, the default value **true** is used.| Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. | -| showError | {
error: string
} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| focus | {
focus: true\|false
}:
If **focus** is not passed, the default value **true** is used. | Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. | +| showError | {
error: string
} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | | delete6+ | - | Deletes text based on the current caret position when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**; deletes the last character and displays the caret if the current input component does not have a caret. | ## Example diff --git a/en/application-dev/reference/arkui-js/js-components-media-video.md b/en/application-dev/reference/arkui-js/js-components-media-video.md index 18c3fbef3bff790dfea6359d7a5d7c5516d0ecd5..c024cbe0058093b754c98f04f579b1cd7dac620f 100644 --- a/en/application-dev/reference/arkui-js/js-components-media-video.md +++ b/en/application-dev/reference/arkui-js/js-components-media-video.md @@ -3,17 +3,17 @@ > **NOTE** > -> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. +> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. > -> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. -> ``` -> "abilities": [ -> { -> "configChanges": ["orientation"], -> ... -> } -> ] -> ``` +> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**. +> ``` +> "abilities": [ +> { +> "configChanges": ["orientation"], +> ... +> } +> ] +> ``` The **\