diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 351c3199cdaec9cfb233f29eea1ed1d4f627aa92..36341ce166af7e58ac0ef74483d9f83e7baa33d8 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -3,7 +3,7 @@ - [Application Development Overview](application-dev-guide.md) - About OpenHarmony - [OpenHarmony Project](../OpenHarmony-Overview.md) - - [Glossary](../device-dev/glossary/glossary.md) + - [Glossary](../glossary.md) - [OpenHarmony Release Notes](../release-notes/Readme.md) - Getting Started - [Getting Started with Application Development](quick-start/Readme-EN.md) diff --git a/en/application-dev/ability/Readme-EN.md b/en/application-dev/ability/Readme-EN.md index 8be4858131c0b947639fdeed77bf4f99b3dfb10c..f32b4f7c02be64ac5839f23b77665889130e4a4d 100644 --- a/en/application-dev/ability/Readme-EN.md +++ b/en/application-dev/ability/Readme-EN.md @@ -6,4 +6,7 @@ - [FA Widget Development](fa-formability.md) - Other + - [WantAgent Development](wantagent.md) - [Ability Assistant Usage](ability-assistant-guidelines.md) + - [Test Framework Usage](ability-delegator.md) + diff --git a/en/application-dev/ability/ability-assistant-guidelines.md b/en/application-dev/ability/ability-assistant-guidelines.md index de9f35adbce1e77603fa1a15ba8db8512c0fc8c0..09feb5e590a67df877035069f0d80d8765831fd5 100644 --- a/en/application-dev/ability/ability-assistant-guidelines.md +++ b/en/application-dev/ability/ability-assistant-guidelines.md @@ -28,13 +28,13 @@ The ability assistant is pre-installed in the device environment. You can direct Starts an ability. - | Name | Description | - | --------- | ---------------------- | - | -h/--help | Help information. | + | Name | Description | + | --------- | -------------------------- | + | -h/--help | Help information. | | -d | Device ID. This parameter is optional. | | -a | Ability name. This parameter is mandatory.| | -b | Bundle name. This parameter is mandatory. | - | -D | Debugging mode. This parameter is optional. | + | -D | Debugging mode. This parameter is optional. | **Return value** @@ -82,13 +82,20 @@ The ability assistant is pre-installed in the device environment. You can direct | -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. | | -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.| - **Method** - + ``` aa dump -a ``` - + ![aa-dump-a](figures/aa-dump-a.PNG) + ``` + aa dump -l + ``` + ![aa-dump-l](figures/aa-dump-l.PNG) + ``` + aa dump -i 12 + ``` + ![aa-dump-i](figures/aa-dump-i.PNG) - **force-stop** Forcibly stops a process based on the bundle name. diff --git a/en/application-dev/ability/ability-delegator.md b/en/application-dev/ability/ability-delegator.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf823bacad7b9781d90c8a86224893740444f35 --- /dev/null +++ b/en/application-dev/ability/ability-delegator.md @@ -0,0 +1,139 @@ +# Test Framework Usage + +## Overview +The delegator test framework provides a self-test framework (environment) for OpenHarmony applications. Using this framework, you can start an ability, schedule its lifecycle, listen for its state changes, run a shell command, and print the test result. + +## Constraints + +The APIs provided by the test framework can be used only in the test HAP. They take effect only after the test framework is started by running the **aa test** command or using the Integrated Development Environment (IDE). + + +## Starting the Test Framework + +The test framework can be started using either of the following methods: + +- Method 1: Run the **aa test** command. +- Method 2: Use the IDE. + +### Running aa test + +You can run the **aa test** command to start the test framework. You can specify the **TestRunner** to be used and the package name or module name of the HAP where the **TestRunner** is located. + +An example command in the FA model is as follows: + +```javascript +aa test -p com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 +``` + +An example command in the stage model is as follows: +```javascript +aa test -m com.example.myapplicationfaets -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -w 20 +``` +| Parameter | Mandatory| Description | +| --------------- | -------- | ------------------------------------------------------------ | +| -p | Yes | Package name of the HAP where the **TestRunner** is located. This parameter is used by the FA model. | +| -m | Yes | Module name of the HAP where the **TestRunner** is located. This parameter is used by the stage model. | +| -s unittest | Yes | Name of the **TestRunner** to be used. The TestRunner name must be the same as the file name. | +| -w | No | Timeout interval of a test case, in seconds. If this parameter is not specified, the test framework exits only after **finishTest** is invoked.| +| -s | No | It can be any parameter in the key-value format. The entered parameters can be obtained in key-value mode through **AbilityDelegatorArgs.parameters**. For example, in **-s classname myTest**, **classname** is the key and **myTest** is the value.| + +### Using the IDE + +For details about how to start the IDE, see [IDE Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-openharmony-test-framework-0000001263160453#section1034420367508). + +## Introduction to TestRunner + +**TestRunner** is the entry class of the test framework test process. When the test process is started, the system calls related APIs in **TestRunner**. You need to inherit this class and override the **onPrepare** and **onRun** APIs. When creating an application template, the IDE initializes the default **TestRunner** and starts the default **TestAbility** in the **onRun** API. You can modify the test code of **TestAbility** or override **onPrepare** and **onRun** in **TestRunner** to implement your own test code. For details, see [TestRunner](../reference/apis/js-apis-testRunner.md). + +## Introduction to AbilityMonitor + +**AbilityMonitor** is provided by the test framework for binding to and listening for abilities. You can use **AbilityMonitor** to bind to an **Ability** instance and add **AbilityMonitor** to the listening list. After an ability is bound, the creation and lifecycle changes of the ability will trigger the related callback in **AbilityMonitor**. You can test and verify the ability in these callbacks. For details, see [AbilityMonitor](../reference/apis/js-apis-application-abilityMonitor.md). + +**Example** + +```javascript +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +function onAbilityCreateCallback() { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor).then((void) => { + console.info("addAbilityMonitor promise"); +}); +``` + +## Introduction to AbilityDelegator + +**AbilityDelegator** is a main function class of the test framework. It provides the functions of starting an ability, obtaining an **Ability** instance, scheduling the ability lifecycle, listening for the ability state, and printing test results. + +**Modules to Import** + +```javascript +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + +```javascript +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() +``` + +### Starting an Ability and Listening for the Ability State + +Use **AbilityDelegator** and **AbilityMonitor** to start an ability, obtain an **Ability** instance, and listen for the ability state. + +**Example** + +```javascript +var abilityDelegator; +var ability; +var timeout = 100; + +function onAbilityCreateCallback() { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityMonitor(monitor, timeout, (err, data) => { + ability = data; + console.info("waitAbilityMonitor callback"); +}); + +var want = { + bundleName: "bundleName", + abilityName: "abilityName" +}; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.startAbility(want, (err, data) => { + console.info("startAbility callback"); +}); +``` + +### Scheduling the Ability Lifecycle + +**AbilityDelegator** provides APIs to display and schedule the ability lifecycle and supports the foreground and background. It works with **AbilityMonitor** to listen for the ability lifecycle. For details, see [AbilityDelegator](../reference/apis/js-apis-application-abilityDelegator.md). + +### Running a Shell Command + +**AbilityDelegator** provides APIs to run shell commands. You can run a shell command in the test code. This feature takes effect only in the test environment. +**Example** + +```javascript + var abilityDelegator; + var cmd = "cmd"; + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + abilityDelegator.executeShellCommand(cmd, (err,data) => { + console.info("executeShellCommand callback"); + }); +``` diff --git a/en/application-dev/ability/fa-brief.md b/en/application-dev/ability/fa-brief.md index baf58d144162435b5a7834c88440777ef84621a6..db7346a6f4723cdf5589a8e5671944d95ea3878f 100644 --- a/en/application-dev/ability/fa-brief.md +++ b/en/application-dev/ability/fa-brief.md @@ -1,19 +1,32 @@ # FA Model Overview ## Overall Architecture -The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling. In the FA model, three types of abilities are provided: Page, Service, and Data. The Page ability has the ArkUI and therefore provides the capability of interacting with users. The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke. The Data ability does not have a UI. It also runs in the background and enables other abilities to insert, delete, and query data. +The development of an OpenHarmony application is essentially the development of one or more abilities. By scheduling abilities and managing their lifecycle, OpenHarmony implements application scheduling. + +The Feature Ability (FA) model applies to application development using API 8 and earlier versions. In this model, there are Page, Service, Data, and Form abilities. +- The Page ability implements the ArkUI and provides the capability of interacting with users. +- The Service ability does not have a UI. It runs in the background and provides custom services for other abilities to invoke. +- The Data ability does not have a UI. It also runs in the background and enables other abilities to insert, delete, and query data. +- The Form ability provides a widget, which is a UI display mode. ## Application Package Structure **The following figure shows the application package structure.** + ![fa-package-info](figures/fa-package-info.png) +For details about the application package structure, see [Description of the Application Package Structure Configuration File](../quick-start/package-structure.md). + ## Lifecycle +Among all abilities, the Page ability has the most complex lifecycle, because it has a UI and is the interaction entry of applications. **The following figure shows the lifecycle of the Page ability.** ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) -You can override lifecycle functions in **app.js/app.ets** to process application logic. +The other abilities do not involve the foreground/background switchover and the **onShow** callback. +You can override the lifecycle callbacks in **app.js/app.ets** to process application logic. + +Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. ## Process and Thread Model diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability/fa-dataability.md index fc8cc8da0850badaaf1f8c8cfe9984dadb7d9420..4b098d095df7ca0bec73c485f1a83d70ae43fb3d 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -1,138 +1,94 @@ # Data Ability Development - -## Basic Concepts +## When to Use A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. -## Creating a Data Ability -### 1. Implementation of the Data Subsystem -1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class to provide batch data processing. The traversal logic has been implemented by the **BatchInsert** and **ExecuteBatch** APIs. -2. The APIs used in the lifecycle of the Data ability are as follows: - - - onInitialized - - Called during ability initialization to initialize the relational database (RDB). - - - update - - Updates data in the database. - - - query - - Queries data in the database. - - - delete - - Deletes one or multiple data records from the database. - - - normalizeUri - - Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced. - - - batchInsert - - Inserts multiple data records into the database. - - - denormalizeUri +## Available APIs + +**Table 1** Data ability lifecycle callbacks +|API|Description| +|:------|:------| +|onInitialized|Called during ability initialization to initialize the relational database (RDB).| +|update|Updates data in the database.| +|query|Queries data in the database.| +|delete|Deletes one or multiple data records from the database.| +|normalizeUri|Normalizes the URI. A normalized URI applies to cross-device use, persistence, backup, and restore. When the context changes, it ensures that the same data item can be referenced.| +|batchInsert|Inserts multiple data records into the database.| +|denormalizeUri|Converts a normalized URI generated by **normalizeUri** into a denormalized URI.| +|insert|Inserts a data record into the database.| +|openFile|Opens a file.| +|getFileTypes|Obtains the MIME type of a file.| +|getType|Obtains the MIME type matching the data specified by the URI.| +|executeBatch|Operates data in the database in batches.| +|call|A customized API.| + + +## How to Develop +### Creating a Data Ability - Converts a normalized URI generated by **normalizeUri** into a denormalized URI. - - - insert - - Inserts a data record into the database. - - - openFile - - Opens a file. - - - getFileTypes - - Obtains the MIME type of a file. - - - getType - - Obtains the MIME type matching the data specified by the URI. - - - executeBatch - - Operates data in the database in batches. - - - call - - A customized API. - +1. To meet the basic requirements of the database storage service, implement the **Insert**, **Query**, **Update**, and **Delete** APIs in the **Data** class to provide batch data processing. The traversal logic has been implemented by the **BatchInsert** and **ExecuteBatch** APIs. - The following code snippet shows how to create a Data ability: + The following code snippet shows how to create a Data ability: ```javascript - import dataAbility from '@ohos.data.dataability' - import dataRdb from '@ohos.data.rdb' - - const TABLE_NAME = 'book' - const STORE_CONFIG = { name: 'book.db', encryptKey: new Uint8Array([]) } - const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, introduction TEXT NOT NULL)' - let rdbStore = undefined - export default { - onInitialized(abilityInfo) { - console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) - dataRdb.getRdbStore(STORE_CONFIG, 1, (err, store) => { - console.info('DataAbility getRdbStore callback') - store.executeSql(SQL_CREATE_TABLE, []) - rdbStore = store - }); - }, - insert(uri, valueBucket, callback) { - console.info('DataAbility insert start') - rdbStore.insert(TABLE_NAME, valueBucket, callback) - }, - batchInsert(uri, valueBuckets, callback) { - console.info('DataAbility batch insert start') - for (let i = 0;i < valueBuckets.length; i++) { - console.info('DataAbility batch insert i=' + i) - if (i < valueBuckets.length - 1) { - rdbStore.insert(TABLE_NAME, valueBuckets[i], (num: number) => { - console.info('DataAbility batch insert ret=' + num) - }) - } else { - rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) - } + onInitialized(abilityInfo) { + console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName) + dataRdb.getRdbStore(STORE_CONFIG, 1, (err, store) => { + console.info('DataAbility getRdbStore callback') + store.executeSql(SQL_CREATE_TABLE, []) + rdbStore = store + }); + }, + insert(uri, valueBucket, callback) { + console.info('DataAbility insert start') + rdbStore.insert(TABLE_NAME, valueBucket, callback) + }, + batchInsert(uri, valueBuckets, callback) { + console.info('DataAbility batch insert start') + for (let i = 0;i < valueBuckets.length; i++) { + console.info('DataAbility batch insert i=' + i) + if (i < valueBuckets.length - 1) { + rdbStore.insert(TABLE_NAME, valueBuckets[i], (num: number) => { + console.info('DataAbility batch insert ret=' + num) + }) + } else { + rdbStore.insert(TABLE_NAME, valueBuckets[i], callback) } - }, - query(uri, columns, predicates, callback) { - console.info('DataAbility query start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.query(rdbPredicates, columns, callback) - }, - update(uri, valueBucket, predicates, callback) { - console.info('DataAbilityupdate start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.update(valueBucket, rdbPredicates, callback) - }, - delete(uri, predicates, callback) { - console.info('DataAbilitydelete start') - let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) - rdbStore.delete(rdbPredicates, callback) } + }, + query(uri, columns, predicates, callback) { + console.info('DataAbility query start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.query(rdbPredicates, columns, callback) + }, + update(uri, valueBucket, predicates, callback) { + console.info('DataAbilityupdate start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.update(valueBucket, rdbPredicates, callback) + }, + delete(uri, predicates, callback) { + console.info('DataAbilitydelete start') + let rdbPredicates = dataAbility.createRdbPredicates(TABLE_NAME, predicates) + rdbStore.delete(rdbPredicates, callback) + } }; - ``` +2. Submodule Configuration -### 2. Subsystem Configuration - -| JSON Field | Description | -| ------------- | ------------------------------------------------------------ | -| "name" | Ability name, corresponding to the **Data** class name derived from **Ability**. | -| "type" | Ability type, which is **Data** for a Data ability. | -| "uri" | URI used for communication. | -| "visible" | Whether the Data ability is visible to other applications. When this parameter is set to **true**, the Data ability can communicate with other applications.| + | JSON Field| Description | + | ------------ | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **Data** class name derived from **Ability**. | + | "type" | Ability type, which is **Data** for a Data ability. | + | "uri" | URI used for communication. | + | "visible" | Whether the Data ability is visible to other applications. When this parameter is set to **true**, the Data ability can communicate with other applications.| -**config.json configuration example** + **config.json configuration example** -```json -"abilities":[{ + ```json + "abilities":[{ "srcPath": "DataAbility", "name": ".DataAbility", "icon": "$media:icon", @@ -141,121 +97,142 @@ Data ability providers can customize data access-related APIs such as data inser "type": "data", "visible": true, "uri": "dataability://ohos.samples.etsdataability.DataAbility" -}] -``` + }] + ``` + +### Accessing a Data ability +#### Development Preparations + +Import the basic dependency packages and obtain the URI string for communicating with the Data submodule. + +The basic dependency packages include: +- @ohos.ability.featureAbility +- @ohos.data.dataability +- @ohos.data.rdb + +#### Data Ability API Development -## Accessing a Data ability -### 1. Preparing for JS Application Development -Basic dependency packages: - 1. @ohos.ability.featureAbility - 2. @ohos.data.dataability - 3. @ohos.data.rdb -URI string used for communication with the Data ability. -### 2. JS Application Development APIs -Create a utility API object. -```js -// Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). -var urivar = "dataability:///com.ix.DataAbility" -var DAHelper = featureAbility.acquireDataAbilityHelper( +1. Create a Data ability helper. + + For details about the APIs provided by **DataAbilityHelper**, see [DataAbilityHelper Module](../reference/apis/js-apis-dataAbilityHelper.md). + ```js + // Different from the URI defined in the config.json file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). + var urivar = "dataability:///com.ix.DataAbility" + var DAHelper = featureAbility.acquireDataAbilityHelper( urivar -); -``` -Construct RDB data. -```js -var valuesBucket = {"name": "gaolu"} -var da = new ohos_data_ability.DataAbilityPredicates() -var valArray =new Array("value1"); -var cars = new Array({"batchInsert1" : "value1",}); -``` -Use **insert** to insert data to the Data subsystem. -```js -// Callback mode: -DAHelper.insert( + ); + ``` +2. Construct RDB data. + ```js + var valuesBucket = {"name": "gaolu"} + var da = new ohos_data_ability.DataAbilityPredicates() + var valArray =new Array("value1"); + var cars = new Array({"batchInsert1" : "value1",}); + ``` +3. Use **insert** to insert data to the Data submodule. + ```js + // Callback mode: + DAHelper.insert( urivar, valuesBucket, (error, data) => { expect(typeof(data)).assertEqual("number") } -); -// Promise mode: -var datainsert = await DAHelper.insert( + ); + ``` + + ```js + // Promise mode: + var datainsert = await DAHelper.insert( urivar, valuesBucket -); -``` -Use **delete** to delete data from the Data subsystem. -```js -// Callback mode: -DAHelper.delete( + ); + ``` +4. Use **delete** to delete data from the Data submodule. + ```js + // Callback mode: + DAHelper.delete( urivar, da, (error, data) => { expect(typeof(data)).assertEqual("number") } -); -// Promise mode: -var datadelete = await DAHelper.delete( + ); + ``` + + ```js + // Promise mode: + var datadelete = await DAHelper.delete( urivar, da, -); -``` -Use **update** to update data in the Data subsystem. -```js -// Callback mode: -DAHelper.update( + ); + ``` +5. Use **update** to update data in the Data submodule. + ```js + // Callback mode: + DAHelper.update( urivar valuesBucket, da, (error, data) => { expect(typeof(data)).assertEqual("number") } -); -// Promise mode: -var dataupdate = await DAHelper.update( + ); + ``` + + ```js + // Promise mode: + var dataupdate = await DAHelper.update( urivar, valuesBucket, da, -); -``` -Use **query** to query data in the Data subsystem. -```js -// Callback mode: -DAHelper.query( + ); + ``` +6. Use **query** to query data in the Data submodule. + ```js + // Callback mode: + DAHelper.query( urivar, valArray, da, (error, data) => { expect(typeof(data)).assertEqual("object") } -); -// Promise mode: -var dataquery = await DAHelper.query( + ); + ``` + + ```js + // Promise mode: + var dataquery = await DAHelper.query( urivar, valArray, da -); -``` -Use **batchInsert** to insert data in batches to the Data subsystem. -```js -// Callback mode: -DAHelper.batchInsert( + ); + ``` +7. Use **batchInsert** to insert data in batches to the Data submodule. + ```js + // Callback mode: + DAHelper.batchInsert( urivar, cars, (error, data) => { expect(typeof(data)).assertEqual("number") } -); -// Promise mode: -var databatchInsert = await DAHelper.batchInsert( + ); + ``` + + ```js + // Promise mode: + var databatchInsert = await DAHelper.batchInsert( urivar, cars -); -``` -Use **executeBatch** to process data in batches in the Data subsystem. -```js -// Callback mode: -DAHelper.executeBatch( + ); + ``` +8. Use **executeBatch** to process data in batches in the Data submodule. + ```js + // Callback mode: + DAHelper.executeBatch( urivar, [ { @@ -271,9 +248,12 @@ DAHelper.executeBatch( (error, data) => { expect(typeof(data)).assertEqual("object") } -); -// Promise mode: -var dataexecuteBatch = await DAHelper.executeBatch( + ); + ``` + + ```js + // Promise mode: + var dataexecuteBatch = await DAHelper.executeBatch( urivar, [ { @@ -289,16 +269,16 @@ var dataexecuteBatch = await DAHelper.executeBatch( interrupted:true, } ] -); -``` + ); + ``` ## Development Example The following sample is provided to help you better understand how to develop a Data ability: -- [eTSDataAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSDataAbility) +- [DataAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility) -This **eTSDataAbility** sample shows how to: +This sample shows how to: Create a Data ability in the **data.ts** file in the **DataAbility** directory. diff --git a/en/application-dev/ability/fa-formability.md b/en/application-dev/ability/fa-formability.md index 89a110ed2fefaedb379bc7adffaa132dd6548721..49f2cf96d7d515fe60c9b8d85e793e7c9fbb9111 100644 --- a/en/application-dev/ability/fa-formability.md +++ b/en/application-dev/ability/fa-formability.md @@ -1,39 +1,39 @@ # FA Widget Development ## Widget Overview -A Form ability presents a widget, which is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. +A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. -A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget client is responsible for displaying the service widget. +A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget. Basic concepts: - Widget provider The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. -- Widget client - The widget client is an application that displays the widget content and controls the position where the widget is displayed in the host application. +- Widget host + The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application. - Widget Manager The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The widget client and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. +> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. -You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget client and Widget Manager. +You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. The widget provider controls the widget content to display, component layout, and click events bound to components. ## Scenario -Form ability development refers to the development conducted by the widget provider based on the Feature Ability (FA) model(fa-brief.md). As a widget provider, you need to carry out the following operations: +Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: -- Develop the lifecycle callback functions in **FormAbility**. +- Develop the lifecycle callbacks in **LifecycleForm**. - Create a **FormBindingData** object. - Update a widget through **FormProvider**. - Develop the widget UI page. ## Available APIs -The table below describes the lifecycle callback functions provided **FormAbility**. +The table below describes the lifecycle callbacks provided **LifecycleForm**. -**Table 1** FormAbility APIs +**Table 1** LifecycleForm APIs | API | Description | | :----------------------------------------------------------- | :------------------------------------------- | @@ -43,7 +43,7 @@ The table below describes the lifecycle callback functions provided **FormAbilit | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | -| onConfigurationUpdated(config: Configuration): void; | Called when the configuration of the environment where the ability is running is updated. | +| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. | For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). @@ -58,9 +58,9 @@ For details about the **FormProvider** APIs, see [FormProvider](../reference/api ## How to Develop -### Creating a Form Ability +### Creating LifecycleForm -To create a widget in the FA model, you need to implement the lifecycle callback functions of **FormAbility**. The sample code is as follows: +To create a widget in the FA model, you need to implement the lifecycles of **LifecycleForm**. The sample code is as follows: 1. Import the required modules. @@ -70,7 +70,7 @@ To create a widget in the FA model, you need to implement the lifecycle callback import formProvider from '@ohos.application.formProvider' ``` -2. Implement the lifecycle callback functions of **FormAbility**. +2. Implement the lifecycle callbacks of **LifecycleForm**. ```javascript export default { @@ -85,11 +85,11 @@ To create a widget in the FA model, you need to implement the lifecycle callback return formData; }, onCastToNormal(formId) { - // Called when the widget client converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. console.log('FormAbility onCastToNormal'); }, onUpdate(formId) { - // To support scheduled update, periodic update, or update requested by the widget client for a widget, override this method for data update. + // To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. console.log('FormAbility onUpdate'); let obj = { "title": "titleOnUpdate", @@ -101,7 +101,7 @@ To create a widget in the FA model, you need to implement the lifecycle callback }); }, onVisibilityChange(newStatus) { - // Called when the widget client initiates an event about visibility changes. The widget provider should do something to respond to the notification. + // Called when the widget host initiates an event about visibility changes. The widget provider should do something to respond to the notification. console.log('FormAbility onVisibilityChange'); }, onEvent(formId, message) { @@ -129,7 +129,7 @@ Configure the **config.json** file for the **Form** ability. | -------- | ------------------------------------------------------------ | -------- | ------------------------ | | name | Name of a JavaScript component. The default value is **default**. | String | No | | pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | - | window | Window-related configurations. This field applies only to phones, tablets, smart TVs, head units, and wearable devices.| Object | Yes | + | window | Window-related configurations. | Object | Yes | | type | Type of the JavaScript component. Available values are as follows:
**normal**: indicates that the JavaScript component is an application instance.
**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| | mode | Development mode of the JavaScript component. | Object | Yes (initial value: left empty) | @@ -147,28 +147,26 @@ Configure the **config.json** file for the **Form** ability. }] ``` -- The **abilities** module in the **config.json** file corresponds to the **Form** ability. The internal field structure is described as follows: +- The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal field structure is described as follows: | Field | Description | Data Type | Default | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | - | type | Type of the widget. Available values are as follows:
**Java**: indicates a Java-programmed widget.
**JS**: indicates a JavaScript-programmed widget.| String | No | + | type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | - | landscapeLayouts | Landscape layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | - | portraitLayouts | Portrait layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | - | formConfigAbility | Name of the facility or activity used to adjust a widget. | String | Yes (initial value: left empty) | - | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | - | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This field is required only by JavaScript-programmed widgets.| String | No | + | formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | + | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | + | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | | customizeData | Custom information about the widget. | Object array | Yes (initial value: left empty) | - + A configuration example is as follows: ```json @@ -180,10 +178,12 @@ Configure the **config.json** file for the **Form** ability. "label": "$string:form_FormAbility_label", "srcPath": "FormAbility", "type": "service", + "srcLanguage": "ets", + "formsEnabled": true, "forms": [{ "colorMode": "auto", "defaultDimension": "2*2", - "description": "This is a service widget.", + "description": "This is a widget.", "formVisibleNotify": true, "isDefault": true, "jsComponentName": "widget", @@ -233,13 +233,13 @@ You should override **onDestroy** to delete widget data. For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md). -Note that the **Want** passed by the widget client to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. +Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. -Normal widget: a widget that will be persistently used by the widget client +Normal widget: a widget that will be persistently used by the widget host -Temporary widget: a widget that is temporarily used by the widget client +Temporary widget: a widget that is temporarily used by the widget host -Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget client may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. +Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. ### Developing the Widget UI Page You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. @@ -325,3 +325,11 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme Now you've got a widget shown below. ![fa-form-example](figures/fa-form-example.png) + +## Development Example + +The following sample is provided to help you better understand how to develop a widget on the FA model: + +[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility) + +This sample provides a widget. Users can create, update, and delete widgets on the home screen of their phones or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. diff --git a/en/application-dev/ability/fa-pageability.md b/en/application-dev/ability/fa-pageability.md index 1fe34335238f17e3318128b9c52cf59ba00b12e8..9d26c220e5f691e29d03c8ab4a9ad6c3752c99d4 100644 --- a/en/application-dev/ability/fa-pageability.md +++ b/en/application-dev/ability/fa-pageability.md @@ -2,11 +2,13 @@ ## Overview ### Concepts -The Page ability has the ArkUI and therefore provides the capability of interacting with users. When you create an ability in the integrated development environment (IDE), the IDE automatically creates template code. The capabilities related to the Page ability are exposed through the singleton **featureAbility**, and the lifecycle callbacks are exposed through the callback functions in **app.js/app.ets**. +The Page ability implements the ArkUI and provides the capability of interacting with developers. When you create an ability in the integrated development environment (IDE), the IDE automatically creates template code. The capabilities related to the Page ability are implemented through the **featureAbility**, and the lifecycle callbacks are implemented through the callbacks in **app.js/app.ets**. ### Page Ability Lifecycle -The ability lifecycle is a general term for all states of an ability (either a Page or a Service ability), such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. +**Ability lifecycle** + +The Page ability lifecycle is a general term for all states of a Page ability, such as **INACTIVE**, **ACTIVE**, and **BACKGROUND**. The following figure shows the lifecycle state transition of the Page ability. @@ -15,21 +17,34 @@ The following figure shows the lifecycle state transition of the Page ability. Description of ability lifecycle states: - - **UNINITIALIZED**: The ability is not initialized. This is a temporary state. An ability changes directly to the **INITIAL** state upon its creation. + - **UNINITIALIZED**: The Page ability is not initialized. This is a temporary state. A Page ability changes directly to the **INITIAL** state upon its creation. - - **INITIAL**: This state refers to the initial or stopped state. The ability in this state is not running. The ability enters the **INACTIVE** state after it is started. + - **INITIAL**: This state refers to the initial or stopped state. The Page ability in this state is not running. The Page ability enters the **INACTIVE** state after it is started. - **INACTIVE**: The ability is visible but does not gain focus. - **ACTIVE**: The ability runs in the foreground and gains focus. - - **BACKGROUND**: The ability returns to the background. After being re-activated, the ability enters the **ACTIVE** state. After being destroyed, the ability enters the **INITIAL** state. + - **BACKGROUND**: The Page ability returns to the background. After being re-activated, the Page ability enters the **ACTIVE** state. After being destroyed, the Page ability enters the **INITIAL** state. -**The following figure shows the lifecycle of the Page ability.** +**The following figure shows the relationship between lifecycle callbacks and lifecycle states of the Page ability.** ![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png) -You can override the lifecycle callback functions provided by the Page ability in **app.js/app.ets**. +You can override the lifecycle callbacks provided by the Page ability in the **app.js/app.ets** file. Currently, the **app.js** file provides only the **onCreate** and **onDestroy** callbacks, and the **app.ets** file provides the full lifecycle callbacks. + +### Launch Type +The ability supports three launch types: singleton, multi-instance, and instance-specific. +The **launchType** item in the **config.json** file is used to specify the launch type. + +| Launch Type | Description |Description | +| ----------- | ------- |---------------- | +| standard | Multi-instance | A new instance is started each time an ability starts.| +| singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.| +| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| + +By default, **standard** is used. + ## Development Guidelines ### Available APIs @@ -46,48 +61,48 @@ You can override the lifecycle callback functions provided by the Page ability i ### Starting a Local Page Ability -* Modules to Import +**Modules to Import** +```js + import featureAbility from '@ohos.ability.featureAbility' ``` -import featureAbility from '@ohos.ability.featureAbility' -``` -* Example + +**Example** ```javascript -import featureAbility from '@ohos.ability.featureAbility' -featureAbility.startAbility({ + import featureAbility from '@ohos.ability.featureAbility' + featureAbility.startAbility({ want: { action: "", entities: [""], type: "", options: { - // Grant the permission to read the URI. + // Grant the permission to perform read operations on the URI. authReadUriPermission: true, - // Grant the permission to write the URI. + // Grant the permission to perform write operations on the URI. authWriteUriPermission: true, - // Forward the intent result to the origin ability. + // Support forwarding the Want result to the ability. abilityForwardResult: true, - // Mark the ability start-up triggered by continuation. + // Enable abiligy continuation. abilityContinuation: true, // Specify that a component does not belong to ohos. notOhosComponent: true, - // Specify whether an ability is started. + // Specify that an ability is started. abilityFormEnabled: true, - // Grant the permission to persist the URI. + // Grant the permission for possible persisting on the URI. authPersistableUriPermission: true, - // Grant the permission to persist the URI. + // Grant the permission for possible persisting on the prefix URI. authPrefixUriPermission: true, - // Support distributed scheduling and start-up across multiple devices. + // Support distributed scheduling system startup on multiple devices. abilitySliceMultiDevice: true, - // An ability using the Service template is started regardless of whether the - // host application has been started. + // A service ability is started regardless of whether the host application has been started. startForegroundAbility: true, // Install the specified ability if it is not installed. installOnDemand: true, - // Return the result to the origin ability slice. + // Return the result to the ability slice. abilitySliceForwardResult: true, - // Install the specified ability with the background mode if it is not installed. + // Install the specified ability with background mode if it is not installed. installWithBackgroundMode: true }, deviceId: "", @@ -95,14 +110,17 @@ featureAbility.startAbility({ abilityName: "com.example.startability.MainAbility", uri: "" }, -}, -); + }, + ); ``` + You can also include **parameters** in the **want** parameter and set its value in the key-value format. -* Example + +**Example** + ```javascript -import featureAbility from '@ohos.ability.featureAbility' -featureAbility.startAbility({ + import featureAbility from '@ohos.ability.featureAbility' + featureAbility.startAbility({ want: { bundleName: "com.example.startability", @@ -111,44 +129,115 @@ featureAbility.startAbility({ abilityName: "com.example.startability.MainAbility" } }, -}, -); + }, + ); ``` -### Starting a Remote Page Ability +### Starting a Remote Page Ability (Applying only to System Applications) +>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Page ability startup applies only to system applications. -* Modules to Import +**Modules to Import** ``` -import featureAbility from '@ohos.ability.featureAbility' + import featureAbility from '@ohos.ability.featureAbility' + import deviceManager from '@ohos.distributedHardware.deviceManager'; ``` -* Example +**Example** +```ts + function onStartRemoteAbility() { + console.info('onStartRemoteAbility begin'); + let params; + let wantValue = { + bundleName: 'ohos.samples.etsDemo', + abilityName: 'ohos.samples.etsDemo.RemoteAbility', + deviceId: getRemoteDeviceId(), + parameters: params + }; + console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue)); + featureAbility.startAbility({ + want: wantValue + }).then((data) => { + console.info('onStartRemoteAbility finished, ' + JSON.stringify(data)); + }); + console.info('onStartRemoteAbility end'); + } +``` -```javascript -var promise = await featureAbility.startAbility({ - want: - { - deviceId: this.deviceId, - bundleName: "com.example.test", - abilityName: "com.example.test.MainAbility", - }, -} -); +Obtain **deviceId** from **DeviceManager**. The sample code is as follows: + +```ts + import deviceManager from '@ohos.distributedHardware.deviceManager'; + let dmClass; + function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } + } +``` + +In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: + +```ts + import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; + import bundle from '@ohos.bundle'; + async function RequestPermission() { + console.info('RequestPermission begin'); + let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; + let bundleFlag = 0; + let tokenID = undefined; + let userID = 100; + let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + let atManager = abilityAccessCtrl.createAtManager(); + let requestPermissions: Array = []; + for (let i = 0;i < array.length; i++) { + let result = await atManager.verifyAccessToken(tokenID, array[i]); + console.info("verifyAccessToken result:" + JSON.stringify(result)); + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + } else { + requestPermissions.push(array[i]); + } + } + console.info("requestPermissions:" + JSON.stringify(requestPermissions)); + if (requestPermissions.length == 0 || requestPermissions == []) { + return; + } + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data requestCode:" + data.requestCode); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); + console.info('RequestPermission end'); + } ``` + ### Lifecycle APIs -**Table 2** Lifecycle callback functions + +**Table 2** Lifecycle callbacks | API | Description | | ------------ | ------------------------------------------------------------ | -| onShow() | Invoked when the ability is switched from the background to the foreground. In this case, the ability is visible to users.| -| onHide() | Invoked when the ability is switched from the foreground to the background. In this case, the ability is invisible.| -| onDestroy() | Invoked when the ability is destroyed. In this callback, you can make preparations for app exit, such as recycling resources and clearing the cache.| -| onCreate() | Invoked when the ability is created for the first time. You can initialize the application in this callback.| -| onInactive() | Invoked when the ability loses focus. An ability loses focus before entering the background state.| -| onActive() | Invoked when the ability is switched to the foreground and gains focus. | - -* Example -You need to override the lifecycle callback functions in **app.js/app.ets**. The IDE template generates **onCreate()** and **onDestroy()** by default. You need to override the other functions. +| onShow() | Called when the ability is switched from the background to the foreground. In this case, the ability is visible to users.| +| onHide() | Called when the ability is switched from the foreground to the background. In this case, the ability is invisible.| +| onDestroy() | Called when the ability is destroyed. In this callback, you can make preparations for app exit, such as recycling resources and clearing the cache.| +| onCreate() | Called when the ability is created for the first time. You can initialize the application in this callback.| +| onInactive() | Called when the ability loses focus. An ability loses focus before entering the background state.| +| onActive() | Called when the ability is switched to the foreground and gains focus. | + +**Example** + +You need to override the lifecycle callbacks in **app.js/app.ets**. The IDE template generates **onCreate()** and **onDestroy()** by default. You need to override the other callbacks. + ```javascript export default { onCreate() { @@ -174,6 +263,6 @@ export default { ### Development Example The following sample is provided to help you better understand how to develop a Page ability: -- [DMS](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) +[DMS](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) This sample describes how to start a local ability and remote ability. diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 41811571ccd7bc2b48bead35cd5c8c77a6e0a516..1d3ffc44f8402225a5dbdea0df7c89531abaa5c5 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -1,34 +1,27 @@ # Service Ability Development -## Basic Concepts +## When to Use A Service ability is used to run tasks in the background, such as playing music or downloading files. It does not provide a UI for user interaction. Service abilities can be started by other applications or abilities and can remain running in the background even after the user switches to another application. -## Creating a Service Ability +## Available APIs -1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability: - - - onStart() - - This callback is invoked for initializing a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null. - - - onCommand() - - This callback is invoked every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback. - - - onConnect() - - This callback is invoked when another ability is connected to the Service ability. It returns an **IRemoteObject**. You can use this callback to generate a channel for the other ability to interact with the Service ability during inter-process communication (IPC). An ability can connect to the same Service ability for multiple times. When the first client is connected to a Service ability, the system calls **onConnect()** to generate an **IRemoteObject** for the Service ability, and the generated **IRemoteObject** will then be cached and used for all clients that are connected to this Service ability without having to call **onConnect()** again. - - - onDisconnect() - - This callback is invoked when another ability is disconnected from the Service ability. +**Table 1** Service ability lifecycle callbacks +|API|Description| +|:------|:------| +|onStart|Called to initialize a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null.| +|onCommand|Called every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback.| +|onConnect|Called when another ability is connected to the Service ability.| +|onDisconnect|Called when another ability is disconnected from the Service ability.| +|onStop|Called when the Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners.| - - onStop() +## How to Develop - This callback is invoked when a Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners. +### Creating a Service Ability +1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability: + The following code snippet shows how to create a Service ability: - + ```javascript export default { onStart(want) { @@ -49,11 +42,11 @@ A Service ability is used to run tasks in the background, such as playing music } ``` -2. Register a Service ability. - - You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. +2. Register a Service ability. - ```javascript + You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. + + ```javascript { "module": { "abilities": [ @@ -68,14 +61,13 @@ A Service ability is used to run tasks in the background, such as playing music } ... } - ``` + ``` - -## Starting the Service Ability +### Starting a Service ability -The **Ability** class provides the **startAbility()** method for you to start another Service ability by passing a **Want** object. +The **Ability** class provides the **startAbility()** API for you to start another Service ability by passing a **Want** object. To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. The meanings of the parameters are as follows: @@ -86,7 +78,7 @@ The following code snippet shows how to start a Service ability running on the l ```javascript import featureAbility from '@ohos.ability.featureability'; -var promise = await featureAbility.startAbility( +let promise = await featureAbility.startAbility( { want: { @@ -97,29 +89,49 @@ var promise = await featureAbility.startAbility( ); ``` -- After the preceding code is executed, the **startAbility()** method is called to start the Service ability. - - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. - - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. +After the preceding code is executed, the **startAbility()** API is called to start the Service ability. +- If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. +- If the Service ability is running, the system directly calls **onCommand()** on the Service ability. -- Stopping a Service ability - Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateAbility()** on a Service ability to stop it or call **stopAbility()** on another ability to stop the specified Service ability. + +### Stopping a Service ability + + Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateSelf()** on a Service ability to stop it or call **stopAbility()** on another ability to stop the specified Service ability. -## Connecting to a Local Service Ability +### Connecting to a Local Service Ability If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. -When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the method. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. +When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. The following code snippet shows how to implement the callbacks: ```javascript -var mRemote; +let mRemote; function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect Callback') + console.log('onConnectLocalService onConnectDone element: ' + element); + console.log('onConnectLocalService onConnectDone remote: ' + remote); mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "onConnectLocalService not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "onConnectLocalService connect result: " + msg, + duration: 3000 + }); } function onDisconnectCallback(element){ @@ -135,7 +147,7 @@ The following code snippet shows how to connect to a local Service ability: ```javascript import featureAbility from '@ohos.ability.featureability'; -var connId = featureAbility.connectAbility( +let connId = featureAbility.connectAbility( { bundleName: "com.jstest.serviceability", abilityName: "com.jstest.serviceability.MainAbility", @@ -155,7 +167,7 @@ The following code snippet shows how the Service ability instance returns itself ```javascript import rpc from "@ohos.rpc"; -var mMyStub; +let mMyStub; export default { onStart(want) { class MyStub extends rpc.RemoteObject{ @@ -166,6 +178,16 @@ export default { return null; } onRemoteRequest(code, message, reply, option) { + console.log("ServiceAbility onRemoteRequest called"); + if (code === 1) { + let op1 = data.readInt(); + let op2 = data.readInt(); + console.log("op1 = " + op1 + ", op2 = " + op2); + reply.writeInt(op1 + op2); + } else { + console.log("ServiceAbility unknown request code"); + } + return true; } } mMyStub = new MyStub("ServiceAbility-test"); @@ -186,19 +208,38 @@ export default { } ``` -## Connecting to a Remote Service Ability +### Connecting to a Remote Service Ability (Applying only to System Applications) +>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Service ability startup applies only to system applications. If you need to connect a Service ability to a Page ability on another device or to a Service ability in another application on another device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows other abilities on another device to connect to it through **connectAbility()**. -When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the method. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. +When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the API. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. The following code snippet shows how to implement the callbacks: -```javascript -var mRemote; +```ts +let mRemote; function onConnectCallback(element, remote){ - console.log('ConnectRemoteAbility onConnect Callback') + console.log('onConnectLocalService onConnectDone element: ' + element); + console.log('onConnectLocalService onConnectDone remote: ' + remote); mRemote = remote; + if (mRemote == null) { + prompt.showToast({ + message: "onConnectLocalService not connected yet" + }); + return; + } + let option = new rpc.MessageOption(); + let data = new rpc.MessageParcel(); + let reply = new rpc.MessageParcel(); + data.writeInt(1); + data.writeInt(99); + await mRemote.sendRequest(1, data, reply, option); + let msg = reply.readInt(); + prompt.showToast({ + message: "onConnectLocalService connect result: " + msg, + duration: 3000 + }); } function onDisconnectCallback(element){ @@ -210,17 +251,35 @@ function onFailedCallback(code){ } ``` -The **Want** of the target Service ability must contain the remote **deviceId**, which can be obtained through **deviceManager**. +The **Want** of the target Service ability must contain the remote **deviceId**, which can be obtained from **DeviceManager**. The sample code is as follows: + +```ts +import deviceManager from '@ohos.distributedHardware.deviceManager'; +let dmClass; +function getRemoteDeviceId() { + if (typeof dmClass === 'object' && dmClass != null) { + let list = dmClass.getTrustedDeviceListSync(); + if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { + console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); + return; + } + console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); + return list[0].deviceId; + } else { + console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + } +} +``` The following code snippet shows how to connect to a remote Service ability: -```javascript +```ts import featureAbility from '@ohos.ability.featureability'; -var connId = featureAbility.connectAbility( +let connId = featureAbility.connectAbility( { - deviceId: deviceId, - bundleName: "com.jstest.serviceability", - abilityName: "com.jstest.serviceability.MainAbility", + deviceId: getRemoteDeviceId(), + bundleName: "ohos.samples.etsDemo", + abilityName: "ohos.samples.etsDemo.ServiceAbility", }, { onConnect: onConnectCallback, @@ -229,53 +288,124 @@ var connId = featureAbility.connectAbility( }, ); ``` +In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: + +```ts +import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; +import bundle from '@ohos.bundle'; +async function RequestPermission() { + console.info('RequestPermission begin'); + let array: Array = ["ohos.permission.DISTRIBUTED_DATASYNC"]; + let bundleFlag = 0; + let tokenID = undefined; + let userID = 100; + let appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + let atManager = abilityAccessCtrl.createAtManager(); + let requestPermissions: Array = []; + for (let i = 0;i < array.length; i++) { + let result = await atManager.verifyAccessToken(tokenID, array[i]); + console.info("verifyAccessToken result:" + JSON.stringify(result)); + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + } else { + requestPermissions.push(array[i]); + } + } + console.info("requestPermissions:" + JSON.stringify(requestPermissions)); + if (requestPermissions.length == 0 || requestPermissions == []) { + return; + } + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data requestCode:" + data.requestCode); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); + console.info('RequestPermission end'); +} +``` When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. The following code snippet shows how the Service ability instance returns itself to the calling ability: -```javascript +```ts import rpc from "@ohos.rpc"; -var mMyStub; -export default { - onStart(want) { - class MyStub extends rpc.RemoteObject{ - constructor(des) { - if (typeof des === 'string') { - super(des); - } - return null; - } - onRemoteRequest(code, message, reply, option) { - } +class FirstServiceAbilityStub extends rpc.RemoteObject{ + constructor(des) { + if (typeof des === 'string') { + super(des); + } else { + return null; } - mMyStub = new MyStub("ServiceAbility-test"); + } + onRemoteRequest(code, data, reply, option) { + console.log("ServiceAbility onRemoteRequest called"); + if (code === 1) { + let op1 = data.readInt(); + let op2 = data.readInt(); + console.log("op1 = " + op1 + ", op2 = " + op2); + reply.writeInt(op1 + op2); + } else { + console.log("ServiceAbility unknown request code"); + } + return true; + } +} + +export default { + onStart() { + console.info('ServiceAbility onStart'); }, - onCommand(want, restart, startId) { - console.log('ServiceAbility onCommand'); + onStop() { + console.info('ServiceAbility onStop'); }, onConnect(want) { - console.log('ServiceAbility OnConnect'); - return mMyStub; - }, - onDisconnect() { - console.log('ServiceAbility OnDisConnect'); + console.log("ServiceAbility onConnect"); + try { + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); + } catch(error) { + console.log("ServiceAbility error:" + error); + } + return new FirstServiceAbilityStub("first ts service stub"); }, - onStop() { - console.log('ServiceAbility onStop'); + onDisconnect(want) { + console.log("ServiceAbility onDisconnect"); + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); }, -} + onCommand(want, startId) { + console.info('ServiceAbility onCommand'); + let value = JSON.stringify(want); + console.log("ServiceAbility want:" + value); + console.log("ServiceAbility startId:" + startId); + } +}; ``` ## Development Example -The following sample is provided to help you better understand how to develop a Service ability: +### The following sample is provided to help you better understand how to develop a Service ability: + +- [ServiceAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility) -- [eTSServiceAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/eTSServiceAbility) -This **eTSServiceAbility** sample shows how to: +This sample shows how to: Create a local Service ability in the **service.ts** file in the **ServiceAbility** directory. Encapsulate the process of starting and connecting to the local Service ability in the **MainAbility** directory. + + +### The following sample is provided to help you better understand how to develop a remote Service ability: + +- [DMS](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS) + +This **DMS** sample shows how to: + +Create a remote Service ability in the **service.ts** file in the **ServiceAbility** directory. + +Encapsulate the process of connecting to the remote Service ability in the **RemoteAbility** directory. diff --git a/en/application-dev/ability/figures/AbilityComponentInstanceMission.png b/en/application-dev/ability/figures/AbilityComponentInstanceMission.png new file mode 100644 index 0000000000000000000000000000000000000000..ce349b7a3544739dd2d3314d35f5b8e3ee68357c Binary files /dev/null and b/en/application-dev/ability/figures/AbilityComponentInstanceMission.png differ diff --git a/en/application-dev/ability/figures/aa-dump-a.PNG b/en/application-dev/ability/figures/aa-dump-a.PNG new file mode 100644 index 0000000000000000000000000000000000000000..ae8d41f65f68d73895be5bbbb539c0d220b2a9a5 Binary files /dev/null and b/en/application-dev/ability/figures/aa-dump-a.PNG differ diff --git a/en/application-dev/ability/figures/aa-dump-i.PNG b/en/application-dev/ability/figures/aa-dump-i.PNG new file mode 100644 index 0000000000000000000000000000000000000000..12998c5ba3e7d667d1147b6e825f8d110d5c5c5e Binary files /dev/null and b/en/application-dev/ability/figures/aa-dump-i.PNG differ diff --git a/en/application-dev/ability/figures/aa-dump-l.PNG b/en/application-dev/ability/figures/aa-dump-l.PNG new file mode 100644 index 0000000000000000000000000000000000000000..a6797eef284990e3fa25e71562ac8afbddf0821d Binary files /dev/null and b/en/application-dev/ability/figures/aa-dump-l.PNG differ diff --git a/en/application-dev/ability/figures/fa-package-info.png b/en/application-dev/ability/figures/fa-package-info.png index 20f01625eed79a95962fdc0d8105e62c29d9dbb0..86da707408da8fdb149ea62d92298fed605132ca 100644 Binary files a/en/application-dev/ability/figures/fa-package-info.png and b/en/application-dev/ability/figures/fa-package-info.png differ diff --git a/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png b/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png index 3093a7765a9055a28527edd4280c4f476adf6d33..ab6e01af0cf96f852c37696fe0c23425219eca39 100644 Binary files a/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png and b/en/application-dev/ability/figures/fa-pageAbility-lifecycle.png differ diff --git a/en/application-dev/ability/wantagent.md b/en/application-dev/ability/wantagent.md new file mode 100644 index 0000000000000000000000000000000000000000..d092ea537ec46bd0c380549cbbf67364f57ff311 --- /dev/null +++ b/en/application-dev/ability/wantagent.md @@ -0,0 +1,72 @@ +# WantAgent Development +### Introduction +The **WantAgent** class encapsulates a **Want** object that specifies a particular action. To trigger a **WantAgent**, you can either call **wantAgent.trigger** to trigger it directly or add it to a notification so that it will be triggered when users tap the notification. + +You can use a **WantAgent** in a notification to start an ability or publish a common event. + +### When to Use +Start another ability through a **WantAgent**. + +### Available APIs +| API | Description| +| ---------------------------------------------------------------------------------------------- | ----------- | +| wantAgent.getWantAgentInfo(info: WantAgentInfo, callback: AsyncCallback\) | Creates a **WantAgent** object. This API uses an asynchronous callback to return the result.| +| wantAgent.getWantAgent(info: WantAgentInfo): Promise\; | Creates a **WantAgent** object. This API uses a promise to return the result.| +| commonEvent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Triggers a **WantAgent**.| + +### How to Develop +1. Import the **WantAgent** module. + +```javascript +import wantAgent from '@ohos.wantAgent'; +``` + +2. Create a **WantAgentInfo** object. For details about the data types and parameters of **WantAgentInfo**, see [WantAgent Module](../reference/apis/js-apis-wantAgent.md#wantagentinfo). + +```javascript +private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. + +//wantAgentInfo +var wantAgentInfo = { + wants: [ + { + deviceId: "", + bundleName: "com.example.test", + abilityName: "com.example.test.MainAbility", + action: "", + entities: [], + uri: "", + parameters: {} + } + ], + operationType: OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.CONSTANT_FLAG] +} +``` + +3. Create a **WantAgent** object and save the returned **wantAgentObj** for subsequent trigger operations. + +```javascript +// Create a WantAgent object. +wantAgent.getWantAgent(wantAgentInfo, (err, wantAgentObj) => { + if (err.code) { + console.error("[WantAgent]getWantAgent err=" + JSON.stringify(err)) + } else { + console.log("[WantAgent]getWantAgent success") + this.wantAgentObj = wantAgentObj + } +}) +``` + +4. Trigger the **WantAgent**. + +``` +// Trigger the WantAgent. +var triggerInfo = { + code:0 +} +wantAgent.trigger(wantAgentObj, triggerInfo, (completeData) => { + console.log("[WantAgent]getWantAgent success, completeData: ", + JSON.stringify(completeData)) +}) +``` diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md index c504299cc8de51b6a992545fb939154cb5365a82..c96dfca665cf33065c35a7351786fec35a02654b 100644 --- a/en/application-dev/background-task-management/background-task-dev-guide.md +++ b/en/application-dev/background-task-management/background-task-dev-guide.md @@ -36,12 +36,12 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; - + let myReason = 'test requestSuspendDelay'; let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { console.info("Request suspension delay will time out."); }); - + var id = delayInfo.requestId;console.info("requestId is: " + id); ``` @@ -106,36 +106,53 @@ ohos.permission.KEEP_BACKGROUND_RUNNING | function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void;
function stopBackgroundRunning(context: Context): Promise<void>; | Cancels the continuous task.| -For details about **WantAgent**, see [WantAgent](../reference/apis/js-apis-notification.md#WantAgent). - +For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md). **Table 4** Background modes -| Name| ID Value| Description| -| -------- | -------- | -------- | -| DATA_TRANSFER | 1 | Data transfer.| -| AUDIO_PLAYBACK | 2 | Audio playback.| -| AUDIO_RECORDING | 3 | Audio recording.| -| LOCATION | 4 | Positioning and navigation.| -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.| -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.| -| WIFI_INTERACTION | 7 | WLAN-related task (reserved).| -| VOIP | 8 | Voice and video call (reserved).| -| TASK_KEEPING | 9 | Computing task (for PC only).| + +| Name| ID Value| Description| Item| +| -------- | -------- | -------- | -------- | +| DATA_TRANSFER | 1 | Data transfer.| dataTransfer | +| AUDIO_PLAYBACK | 2 | Audio playback.| audioPlayback | +| AUDIO_RECORDING | 3 | Audio recording.| audioRecording | +| LOCATION | 4 | Positioning and navigation.| location | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.| bluetoothInteraction | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.| multiDeviceConnection | +| WIFI_INTERACTION | 7 | WLAN-related task (reserved).| wifiInteraction | +| VOIP | 8 | Voice and video call (reserved).| voip | +| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping | ## How to Develop -1. Declare the continuous task permission in the **config.json** file. +1. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**. ```json "module": { - "package": "com.example.myapplication", - ..., - "reqPermissions": [ - { - "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" - } - ] + "package": "com.example.myapplication", + + "abilities": [ + + { + "backgroundModes": [ + "dataTransfer", + "location", + + ], + + "type": "service" + } + ], + "defPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ], + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ] } ``` @@ -174,13 +191,13 @@ For details about **WantAgent**, see [WantAgent](../reference/apis/js-apis-notif ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; - + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { console.info("Operation succeeded"); }).catch((err) => { console.error("Operation failed Cause: " + err); }); - + ``` ## Development Examples diff --git a/en/application-dev/background-task-management/background-task-overview.md b/en/application-dev/background-task-management/background-task-overview.md index 37db9e3dbbb04532b2a724d07d1f75b54ea89628..5062447a9c9491ee0854963f4360c610fb2815f6 100644 --- a/en/application-dev/background-task-management/background-task-overview.md +++ b/en/application-dev/background-task-management/background-task-overview.md @@ -28,9 +28,9 @@ Adhere to the following constraints and rules when using transient tasks: - **When to request**: An application can request a transient task only when it is running in the foreground or before it is suspended in the background. Otherwise, the application may be suspended, resulting in request failure. By default, an application has 6–12 seconds of running time (subject to the application scenario) before it is suspended in the background. -- **Timeout**: The system notifies the application of the suspension delay timeout by using a callback. The application must then cancel the delayed suspension or apply for delayed suspension again. Otherwise, the application will be forcibly suspended. +- **Timeout**: If a suspension delay is about to time out, the system notifies the application of the timeout by using a callback. The application must then cancel the delayed suspension. Otherwise, the application will be forcibly terminated. -- **When to cancel**: The requesting application shall cancel the request when the transient task is complete. If the request is forcibly canceled by the system, the time frame allowed for the application to run in the background will be affected. +- **When to cancel**: The requesting application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, the time frame allowed for the application to run in the background will be affected. - **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) @@ -52,7 +52,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas | multiDeviceConnection | Distributed interconnection| A distributed task is running.| | | wifiInteraction | WLAN transmission| A WLAN-related task is running.| System API, which is available only to system applications| | voip | Voice and video calls over VoIP| A call-related task is running.| System API, which is available only to system applications| -| taskKeeping | Computing task| A computing task is running| PC-specific, valid only on PCs| +| taskKeeping | Computing task| A computing task is running| Effective only for specific devices| ### Restrictions on Using Continuous Tasks - If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user. diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index b489633d984a08010bf61cc18b226757fa5343f9..ea338c1320315efaedae09b2523b6e1558a0096e 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -15,7 +15,7 @@ Call **createDistributedObject()** to create a distributed data object instance. **Table 1** API for creating a distributed data object instance | Package| API| Description| | -------- | -------- | -------- | -| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.| +| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
-  **source**: attributes of the **distributedObject** set.
-  **DistributedObject**: returns the distributed object created.| ### Generating a Session ID @@ -33,7 +33,7 @@ Call setSessionId() to set the session ID for a distributed data object. The ses **Table 3** API for setting a session ID | Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.| +| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.
 **sessionId**: ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| ### Observing Data Changes @@ -43,7 +43,7 @@ Call **on()** to subscribe to data changes of a distributed data object. When th | Class| API| Description| | -------- | -------- | -------- | | DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes.| -| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void | Unsubscribes from data changes.| +| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void | Unsubscribes from data changes. Callback used to return changes of the distributed object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| ### Observing Online or Offline Status @@ -72,6 +72,7 @@ The following example shows how to implement a distributed data object synchroni ```js var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, parent:undefined, list:undefined}); + var sessionId = distributedObject.genSessionId(); ``` @@ -82,13 +83,13 @@ The following example shows how to implement a distributed data object synchroni ```js // Local object var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, - parent:{mother:"jack mom",father:"jack Dad"},[{mother:"jack mom"}, {father:"jack Dad"}]}; - local_object.setsessionId(sessionId); + parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]}); + local_object.setSessionId(sessionId); // Remote object var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, parent:undefined, list:undefined}); - remote_object.setsessionId(sessionId); + remote_object.setSessionId(sessionId); // After obtaining that the device status goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. ``` @@ -97,7 +98,7 @@ The following example shows how to implement a distributed data object synchroni The sample code is as follows: ```js - changeCallback : function (sessionId, changeData) { + function changeCallback(sessionId, changeData) { console.info("change" + sessionId); if (changeData != null && changeData != undefined) { @@ -147,22 +148,22 @@ The following example shows how to implement a distributed data object synchroni 8. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. The sample code is as follows: ```js - statusCallback : function (sessionId, networkid, status) { + function statusCallback(sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; } - local_object.on("status", this.changeCallback); + local_object.on("status", this.statusCallback); ``` 9. Unsubscribe from the status changes of the distributed data object. You can specify the callback to unsubscribe from. If you do not specify the callback, all status change callbacks will be unsubscribe from. The sample code is as follows: ```js - // Unsubscribe from changeCallback. - local_object.off("status", changeCallback); + // Unsubscribe from statusCallback. + local_object.off("status", statusCallback); // unsubscribe from all status change callbacks. local_object.off("status"); ``` -10. Remove the distributed data object from the synchronization network. After the distributed data object is removed from the network, the data changes on the local end will not be synchronized to the remote end. +10. Remove a distributed data object from the synchronization network. After the distributed data object is removed from the network, the data changes on the local end will not be synchronized to the remote end. The sample code is as follows: ```js diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index 6094f0453f58144d9955db7093f73818a80d60fa..c817a54826a3932a3279fa80bcf5702e1c1e0cae 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ On the basis of the SQLite database, the relational database (RDB) allows you to ## Available APIs -**Creating and Deleting an RDB Store** +### Creating or Deleting an RDB Store The following table describes the APIs available for creating and deleting an RDB store. @@ -17,51 +17,55 @@ The following table describes the APIs available for creating and deleting an RD | -------- | -------- | |getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | Obtains an RDB store. This method uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| |getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **config**: configuration of the RDB store.
- **version**: RDB version.| -|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +|deleteRdbStore(name: string, callback: AsyncCallback<void>): void | Deletes an RDB store. This method uses a callback to return the result.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| | deleteRdbStore(name: string): Promise<void> | Deletes an RDB store. This method uses a promise to return the result.
- **name**: RDB store to delete.| -**Managing Data in an RDB Store** +### Managing Data in an RDB Store The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. -- **Inserting data**
+- **Inserting data** + The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. - + **Table 2** APIs for inserting data | Class| API| Description| | -------- | -------- | -------- | | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This method uses a callback to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This method uses a promise to return the result.
- **name**: name of the target table.
- **values**: data to be inserted into the table.| - -- **Updating data**
+ +- **Updating data** + Call the **update()** method to pass new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. - + **Table 3** APIs for updating data | Class| API| Description| | -------- | -------- | -------- | | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise | Updates data in the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **rdbPredicates**: conditions for updating data.| - -- **Deleting data**
+ +- **Deleting data** + Call the **delete()** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. - + **Table 4** APIs for deleting data | Class| API| Description| | -------- | -------- | -------- | | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows deleted.| | RdbStore | delete(rdbPredicates: RdbPredicates): Promise | Deletes data from the RDB store based on the specified **RdbPredicates** object. This method uses a promise to return the result.
- **rdbPredicates**: conditions for deleting data.| + +- **Querying data** -- **Querying data**
You can query data in an RDB store in either of the following ways: - Call the **query()** method to query data based on the predicates, without passing any SQL statement. - Run the native SQL statement. **Table 5** APIs for querying data - + | Class| API| Description| | -------- | -------- | -------- | | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This method uses a callback to return the result.
- **rdbPredicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| @@ -69,7 +73,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| -**Using Predicates** +### Using Predicates The RDB provides **RdbPredicates** for you to set database operation conditions. @@ -108,12 +112,12 @@ The RDB provides **RdbPredicates** for you to set database operation conditions. | RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -**Using the Result Set** +### Using the Result Set A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. > ![icon-notice.gif](../public_sys-resources/icon-notice.gif) **NOTICE**
-> After a result set is used, you must call the **close()** method to close it explicitly. +> After a result set is used, you must call the **close()** method to close it explicitly.** **Table 7** APIs for using the result set @@ -133,26 +137,13 @@ A result set can be regarded as a row of data in the queried results. It allows | ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| | ResultSet | close(): void | Closes the result set.| -**Changing the Encryption Key for an RDB Store** - -You can encrypt an RDB store. - -When creating an RDB store, you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. You can change the key but cannot delete it. -Once an RDB store is created without a key, you can no longer add a key for it. -**Table 8** APIs for changing the encryption key - -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array, callback: AsyncCallback<number>):void; | Changes the encryption key for this RDB store. This method uses a callback to return the result. If the operation is successful, **0** will be returned. Otherwise, a non-zero value will be returned.| -| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array): Promise<number>; | Changes the encryption key for this RDB store. This method uses a promise to return the result. If the operation is successful, **0** will be returned. Otherwise, a non-zero value will be returned.| +### Setting Distributed Tables **Setting Distributed Tables** -You can set a list of distributed tables for data operations across devices. - -**Table 9** APIs for setting distributed tables +**Table 8** APIs for setting distributed tables | Class| API| Description| | -------- | -------- | -------- | @@ -163,7 +154,7 @@ You can set a list of distributed tables for data operations across devices. You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device. -**Table 10** API for obtaining the distributed table name of a remote device +**Table 9** APIs for obtaining the distributed table name of a remote device | Class| API| Description| | -------- | -------- | -------- | @@ -172,17 +163,16 @@ You can obtain the distributed table name for a remote device based on the local **Synchronizing Data Between Devices** -**Table 11** APIs for synchronizing data between devices +**Table 10** APIs for synchronizing data between devices | Class| API| Description| | -------- | -------- | -------- | | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void;| Synchronizes data between devices. This method uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise>;| Synchronizes data between devices. This method uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC\_MODE\_PUSH** means to push data from the local device to a remote device. **SYNC\_MODE\_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | - **Registering an RDB Store Observer** -**Table 12** API for registering an observer +**Table 11** API for registering an observer | Class| API| Description| | -------- | -------- | -------- | @@ -190,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local **Unregistering an RDB Store Observer** -**Table 13** API for unregistering an observer +**Table 12** API for unregistering an observer | Class| API| Description| | -------- | -------- | -------- | @@ -211,9 +201,10 @@ You can obtain the distributed table name for a remote device based on the local const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = {name: "rdbstore.db",} - - let rdbStore = await data_rdb.getRdbStore(STORE_CONFIG, 1); - await rdbStore.executeSql(CREATE_TABLE_TEST); + data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info('create table done.') + }) ``` 2. Insert data. @@ -238,16 +229,16 @@ You can obtain the distributed table name for a remote device based on the local ``` let predicates = new data_rdb.RdbPredicates("test"); predicates.equalTo("name", "Tom") - let resultSet = await rdbStore.query(predicates) - - resultSet.goToFirstRow() - const id = await resultSet.getLong(resultSet.getColumnIndex("id")) - const name = await resultSet.getString(resultSet.getColumnIndex("name")) - const age = await resultSet.getLong(resultSet.getColumnIndex("age")) - const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) - const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) - - resultSet.close() + let promisequery = rdbStore.query(predicates) + promisequery.then((resultSet) => { + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const age = resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + resultSet.close() + }) ``` 4. Set the distributed tables to be synchronized. @@ -261,7 +252,7 @@ You can obtain the distributed table name for a remote device based on the local promise.then(() => { console.info("setDistributedTables success.") }).catch((err) => { - console.info("setDistributedTables failed."") + console.info("setDistributedTables failed.") }) ``` @@ -276,7 +267,7 @@ You can obtain the distributed table name for a remote device based on the local let predicate = new data_rdb.RdbPredicates('test') predicate.inDevices(['12345678abcde']) let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate) - promise.then(result) { + promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) diff --git a/en/application-dev/device/sensor-guidelines.md b/en/application-dev/device/sensor-guidelines.md index 88d24d59bc4885135b92302c3446c7c81bd33d5d..734d75b2573d18ef261ea4f430ab907002fe1e3c 100644 --- a/en/application-dev/device/sensor-guidelines.md +++ b/en/application-dev/device/sensor-guidelines.md @@ -22,16 +22,16 @@ ## Available APIs - | Module | API | Description | +| Module| API| Description| | -------- | -------- | -------- | -| ohos.sensor | sensor.on(sensorType,callback:AsyncCallback<Response>):void | Subscribes to data changes of a type of sensor. | -| ohos.sensor | sensor.once(sensorType,callback:AsyncCallback<Response>):void | Subscribes to only one data change of a type of sensor. | -| ohos.sensor | sensor.off(sensorType,callback:AsyncCallback<void>):void | Unsubscribes from sensor data changes. | +| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback<Response>): void | Subscribes to data changes of a type of sensor.| +| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback<Response>): void | Subscribes to only one data change of a type of sensor.| +| ohos.sensor | sensor.off(sensorType, callback:AsyncCallback<void>): void | Unsubscribes from sensor data changes.| ## How to Develop -1. To obtain data from a type of sensor, configure the request permissions in the **config.json** file. +1. To obtain data from a type of sensor, configure the request permissions in the **config.json** file. ``` "reqPermissions":[ @@ -67,67 +67,59 @@ "when":"inuse" } }, - { - "name":"ohos.permission.VIBRATE", - "reason"":"", - "usedScene":{ - "ability": [".MainAbility"], - "when":"inuse" - } - }, ] ``` - + 2. Subscribe to data changes of a type of sensor. ``` import sensor from "@ohos.sensor" - sensor.on(type:sensorType,function(error,data){ - if (error) {// The call fails, and error.code and error.message are printed. - console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); - return; - }; + sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ console.info("Subscription succeeded. data = "+ data);// The call is successful, and the obtained sensor data is printed. } ); ``` - + The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. - + ![en-us_image_0000001241693881](figures/en-us_image_0000001241693881.png) 3. Unsubscribe from sensor data changes. ``` import sensor from "@ohos.sensor" - sensor.off(type:sensorType,function(error) { - if (error) {// The unsubscription fails, and error.code and error.message are printed. - console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message); - return; - }; + sensor.off(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function() { console.info("Succeeded in unsubscribing from acceleration sensor data.");// The unsubscription is successful, and the result is printed. } ); ``` - + The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. - + ![en-us_image_0000001196654004](figures/en-us_image_0000001196654004.png) 4. Subscribe to only one data change of a type of sensor. ``` import sensor from "@ohos.sensor" - sensor.once(tyep:sensorType,function(error, data) { - if (error) {// The call fails, and error.code and error.message are printed. - console.error("Failed to obtain data. Error code: " + error.code + "; message: " + error.message); - return; - }; - console.info("Data obtained successfully. data="+data);// The call is successful, and the obtained sensor data is printed. + sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { + console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed. } ); ``` - + The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. - + ![en-us_image_0000001241733907](figures/en-us_image_0000001241733907.png) + + If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: + + ``` + try { + sensor.once(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data) { + console.info("Data obtained successfully. data=" + data);// The call is successful, and the obtained sensor data is printed. + }); + } catch (error) { + console.error(error); + } + ``` diff --git a/en/application-dev/device/usb-guidelines.md b/en/application-dev/device/usb-guidelines.md index 1c7aa85a9c52a07e5761e1df52fc17c7eb15e05b..71c6d0b796827db454b51c1e439deec9ddb738c7 100644 --- a/en/application-dev/device/usb-guidelines.md +++ b/en/application-dev/device/usb-guidelines.md @@ -170,9 +170,9 @@ You can set a USB device as a host to connect to a device for data transfer. The var pipe = usb.connectDevice(deviceList[0]); /* Claim the corresponding interface from deviceList. - interface must be one present in the device configuration. + interface1 must be one present in the device configuration. */ - usb.claimInterface(pipe , interface, true); + usb.claimInterface(pipe , interface1, true); ``` 4. Perform data transfer. diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index 88bdeb6884eee52e1591993ec60099d31eb77e3c..982d6c9b0983684729ea41b1d3b45ab9409a43e5 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -8,20 +8,20 @@ You can set different vibration effects as needed, for example, customizing vibr ## Available APIs - | Module | API | Description | + | Module| API| Description| | -------- | -------- | -------- | -| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result. | -| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | -| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | -| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result. | -| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | -| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | +| ohos.vibrator | vibrate(duration: number): Promise<void> | Triggers vibration with the specified duration. This API uses a promise to return the result.| +| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result.| +| ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result.| +| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| +| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result.| +| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result.| ## How to Develop -1. Declare the permissions required for controlling vibrators on the hardware device in the **config.json** file. - +1. Declare the permissions required for controlling vibrators on the hardware device in the **config.json** file. + ``` "reqPermissions":[ { @@ -58,26 +58,26 @@ You can set different vibration effects as needed, for example, customizing vibr ``` 2. Trigger the device to vibrate. - + ``` import vibrator from "@ohos.vibrator" - vibrator.vibrate(duration: number).then((error)=>{ - if(error){// The call fails, and error.code and error.message are printed. - console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); - }else{// The call succeeded. The device starts to vibrate. - console.log("Promise returned to indicate a successful vibration.") + vibrator.vibrate(1000).then((error)=>{ + if (error) {// The call fails, and error.code and error.message are printed. + Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); + }else{// The call is successful, and the device starts to vibrate. + Console.log("Promise returned to indicate a successful vibration.") }; }) ``` 3. Stop the vibration. - + ``` import vibrator from "@ohos.vibrator" - vibrator.stop(stopMode: VibratorStopMode).then((error)=>{ - if(error){// The call fails, and error.code and error.message are printed. - console.log("Promise return failed. error.code"+error.code+"error.message"+error.message); - }else{// The call succeeded. The device stops vibration. + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ + if (error) {// The call fails, and error.code and error.message are printed. + Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); + }else{// The call is successful, and the device stops vibration. Console.log("Promise returned to indicate a successful stop."); }; }) diff --git a/en/application-dev/device/vibrator-overview.md b/en/application-dev/device/vibrator-overview.md index 3d8f187054dd1f0da3e3099bd10e3cb28e5a9b15..88460b4fe415d836a687363c10ceda68c1e98390 100644 --- a/en/application-dev/device/vibrator-overview.md +++ b/en/application-dev/device/vibrator-overview.md @@ -6,10 +6,11 @@ The vibrator service opens up the latest capabilities of the vibrator hardware t ## Working Principles -The vibrator is a Misc device that consists of four modules: Vibrator API, Vibrator Framework, Vibrator Service, and HD_IDL. +The vibrator is a Misc device that consists of four modules: Vibrator API, Vibrator Framework, Vibrator Service, and HDF layer. - **Figure1** Vibrator in Misc devices - ![en-us_image_0000001180249428](figures/en-us_image_0000001180249428.png) + **Figure 1** Vibrator in Misc devices + +![0752d302-aeb9-481a-bb8f-e5524eb61eeb](figures/0752d302-aeb9-481a-bb8f-e5524eb61eeb.png) - Vibrator API: provides basic vibrator APIs, including the APIs for querying the vibrator list, querying the vibrator by effect, and triggering and stopping vibration. @@ -17,9 +18,9 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra - Vibrator Service: manages services of vibrators. -- HD_IDL: adapts to different devices. +- HDF layer: adapts to different devices. ## Constraints -When using a vibrator, you need to declare and obtain the **ohos.permission.VIBRATE** permission first so that you can control the vibration effect. +When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**. diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 414dc3c33099b8225a4a73bcd70fad79604583cf..13c782e5ac7b4a5fc523a865bc2b9826273c2799 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -8,69 +8,21 @@ The event logging function helps applications log various information generated JS application event logging APIs are provided by the **hiAppEvent** module. -**APIs for event logging:** +**APIs for Event Logging** | API | Return Value | Description | | ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | | write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. | | write(string eventName, EventType type, object keyValues): Promise\ | Promise\ | Logs application events in asynchronous mode. This method uses a promise to return the result. | -- **eventName**: event name you customized. The event name can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. - -- **type**: event type enumerated by **EventType**. - - | Type | Description | - | --------- | ----------------- | - | FAULT | Fault event | - | STATISTIC | Statistical event | - | SECURITY | Security event | - | BEHAVIOR | Behavior event | - -- **keyValues**: event parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value. - - A parameter name must be a string, and a parameter value must be a string, number, boolean, or array (which is a basic element). - - The number of event parameters must be less than or equal to 32. - - The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_). - - A string value can contain a maximum of 8*1024 characters. - - An array value can contain a maximum of 100 elements. Excess elements will be truncated. -- **callback**: callback function used to process the received return value. The value **0** indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously. A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored. A value smaller than **0** indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously. - When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](hiappevent-overview.md#Event Verification Result Codes). -**APIs for event logging configuration:** +**APIs for Event Logging Configuration** | API | Return Value | Description | | ------------------------------ | ------------ | ------------------------------------------------------------ | | configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.
The value **true** indicates that the operation is successful, and value **false** indicates the opposite. | -- **config**: configuration options for application event logging. - - Configuration options for application event logging (**ConfigOption**) - - | Name | Type | Mandatory | Description | - | ---------- | ------- | --------- | ------------------------------------------------------------ | - | disable | boolean | No | Sets the application event logging switch. The value **true** means to disable the application event logging function, and value **false** means the opposite. | - | maxStorage | string | No | Specifies the maximum size of the event file storage directory. The default value is 10M. | - -**Predefined event name constants (Event)**: - -| Constant | Type | Description | -| ------------------------- | ------ | ---------------------------------------------- | -| USER_LOGIN | string | Name of the user login event. | -| USER_LOGOUT | string | Name of the user logout event. | -| DISTRIBUTED_SERVICE_START | string | Name of the distributed service startup event. | - - - -**Predefined parameter name constants (Param):** - -| Constant | Type | Description | -| ------------------------------- | ------ | -------------------------------- | -| USER_ID | string | Custom user ID. | -| DISTRIBUTED_SERVICE_NAME | string | Distributed service name. | -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID. | - - - ## How to Develop In this example, an application event is logged after the application startup execution page is loaded. @@ -103,8 +55,7 @@ In this example, an application event is logged after the application startup ex }).catch((err) => { console.error(`failed to write event because ${err.code}`); }); - }); - + // 3. Set the application event logging switch. hiAppEvent.configure({ disable: true @@ -118,6 +69,4 @@ In this example, an application event is logged after the application startup ex } ``` -2. Tap the run button on the application UI to run the project. - - +2. Tap the run button on the application UI to run the project. \ No newline at end of file diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md index 7d3f414331c99f06e2470f6dce14586a50448a33..a123c647e36d943de41b5878d07c06df0324e386 100644 --- a/en/application-dev/dfx/hiappevent-overview.md +++ b/en/application-dev/dfx/hiappevent-overview.md @@ -6,9 +6,7 @@ HiAppEvent provides event logging APIs for applications to log the fault, statis The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data. -- **Logging** - - Logs changes caused by user operations to provide service data for development, product, and O&M analysis. +**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis. ## Event Verification Result Codes diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 3d5ad83f4113c75a3282a8e6a559cf67d71fbab5..6ab74d3e9ce4501f8205e9c401946fac245a6b88 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -6,18 +6,14 @@ - [Audio Playback Development](audio-playback.md) - - [Audio Playback Development Using AudioRenderer](audio-renderer.md) + - [Audio Rendering Development](audio-renderer.md) - [Audio Recording Development](audio-recorder.md) - - [Audio Recorder Development Using AudioCapturer](audio-capturer) - + - [Audio Capture Development](audio-capturer) - Video - [Video Playback Development](video-playback.md) - - - [Video Recording Development](video-recorder.md) - - Image - [Image Development](image.md) diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index a5762b949e5f870f0d6bece4cee17486ca5a02bf..00ff76707d2e8d6a2d0ee7dee92fbe8ff92adc84 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -1,4 +1,4 @@ -# Audio Recorder Development Using AudioCapturer +# Audio Capture Development --- ## ***Note***: @@ -41,7 +41,7 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. 2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. - There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more details. + There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details. ``` audioCapturer.on('stateChange',(state) => { console.info('AudioCapturerLog: Changed State to : ' + state) @@ -149,4 +149,4 @@ That is, the AudioCapturer has an internal state that the application must alway The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state. ## **Other APIs** -See [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. +See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**. diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index a8ea5a537fb0090b79d0449270ffbe09cc9178f2..2124319f5e48f70657ce21c8d4f90b35136b2a37 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -16,7 +16,7 @@ You can use audio playback APIs to convert audio data into audible analog signal ## How to Develop -For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). +For details about the APIs used for audio playback, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md). ### Full-Process Scenario diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index 138b1de2deb794a31f9cb0a384c1d3aa4b2e3e7a..56f72dc5a475a6ba697e204117488c17a8c6846d 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -16,7 +16,7 @@ During audio recording, audio signals are captured, encoded, and saved to files. ## How to Develop -For details about the APIs used for audio recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). +For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md). ### Full-Process Scenario @@ -127,7 +127,7 @@ import mediaLibrary from '@ohos.multimedia.mediaLibrary' let testFdNumber; -function SetCallBack(audioPlayer) { +function SetCallBack(audioRecorder) { audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); // The recording page is ready. You can click the Record button to start recording. diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md index 251b6bf822a67f305ab1c28d502ab5b35be20793..f9dfb75c2a08d6c8d641bbe0c8e7960efc6bc6ee 100644 --- a/en/application-dev/media/audio-renderer.md +++ b/en/application-dev/media/audio-renderer.md @@ -1,4 +1,4 @@ -# Audio Playback Development Using AudioRenderer +# Audio Rendering Development --- ## ***Note***: @@ -17,7 +17,7 @@ When a higher priority stream wants to play, the AudioRenderer framework interru For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ With the sample code below, we'll look at how AudioInterrupt works in detail.\
-Please see [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. +Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. ## **Usage** @@ -267,8 +267,8 @@ The system may throw an error/exception or generate other undefined behaviour if ## **Asynchronous Operations:** Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ For each API, the framework provides both callback and promises functions.\ -In the example, promise functions are used for simplicity. [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) +In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) provides reference for both callback and promise. ## **Other APIs:** -See [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. +See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md index 67472950556a999cbaed31279222c22087965f91..cabbd86899cc050a81ee5dba5d834593d6e7b9ee 100644 --- a/en/application-dev/media/image.md +++ b/en/application-dev/media/image.md @@ -6,7 +6,7 @@ You can use image development APIs to decode images into pixel maps and encode t ## Available APIs -For details about the APIs, see [js-apis-image.md](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md). +For details about the APIs, see [Image Processing](../reference/apis/js-apis-image.md). ## How to Develop diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index 05b002296fc52b6931993f1c512e968f3eb9acf8..946e975a2bf13af7c1ce8d159ad144a66baf720c 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -20,9 +20,22 @@ Note: Video playback requires hardware capabilities such as display, audio, and 2. The third-party application transfers the surface ID to the VideoPlayer JS. 3. The media service flushes the frame data to the surface buffer. +## Compatibility + +You are advised to use the mainstream playback formats and resolutions, rather than custom or abnormal streams to avoid playback failure, frame freezing, and artifacts. The system is not affected by incompatibility issues. If such an error occurs, you can exit stream playback mode. + +The table below lists the mainstream playback formats and resolutions. + +| Video Container Specification| Specification Description | Resolution | +| :----------: | :-----------------------------------------------: | :--------------------------------: | +| mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| ts | Video format: H.264/MPEG-2/MPEG-4; audio format: AAC/MP3 | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| +| webm | Video format: VP8; audio format: VORBIS | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p| + ## How to Develop -For details about the APIs used for video playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). +For details about the APIs, see [VideoPlayer in the Media API](../reference/apis/js-apis-media.md). ### Full-Process Scenario diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md deleted file mode 100644 index 11af1d39846ee5216d7b40cd4ec24b3e22179eb5..0000000000000000000000000000000000000000 --- a/en/application-dev/media/video-recorder.md +++ /dev/null @@ -1,147 +0,0 @@ -# Video Recording Development - -## When to Use - -During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording. - -**Figure 1** Video recording state transition - -![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) - - - -**Figure 2** Layer 0 diagram of video recording - -![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) - -## How to Develop - -For details about the APIs used for video recording, see [js-apis-media.md](../reference/apis/js-apis-media.md). - -### Full-Process Scenario - -The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources. - -```js -import media from '@ohos.multimedia.media' -import mediaLibrary from '@ohos.multimedia.mediaLibrary' - -let testFdNumber; - -// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Movies/01.mp4. -// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA. -async function getFd(pathName) { - let displayName = pathName; - const mediaTest = mediaLibrary.getMediaLibrary(); - let fileKeyObj = mediaLibrary.FileKey; - let mediaType = mediaLibrary.MediaType.VIDEO; - let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO); - let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath); - if (dataUri != undefined) { - let args = dataUri.id.toString(); - let fetchOp = { - selections : fileKeyObj.ID + "=?", - selectionArgs : [args], - } - let fetchFileResult = await mediaTest.getFileAssets(fetchOp); - let fileAsset = await fetchFileResult.getAllObject(); - let fdNumber = await fileAsset[0].open('Rw'); - fdNumber = "fd://" + fdNumber.toString(); - testFdNumber = fdNumber; - } -} - -await getFd('01.mp4'); - -let videoProfile = { - audioBitrate : 48000, - audioChannels : 2, - audioCodec : 'audio/mp4a-latm', - audioSampleRate : 48000, - fileFormat : 'mp4', - videoBitrate : 48000, - videoCodec : 'video/mp4v-es', - videoFrameWidth : 640, - videoFrameHeight : 480, - videoFrameRate : 30 -} - -let videoConfig = { - audioSourceType : 1, - videoSourceType : 0, - profile : videoProfile, - url: testFdNumber, // testFdNumber is generated by getFd. - orientationHint : 0, - location : { latitude : 30, longitude : 130 }, -} - -// Error callback triggered in the case of an error -function failureCallback(error) { - console.info('error happened, error name is ' + error.name); - console.info('error happened, error code is ' + error.code); - console.info('error happened, error message is ' + error.message); -} - -// Error callback triggered in the case of an exception -function catchCallback(error) { - console.info('catch error happened, error name is ' + error.name); - console.info('catch error happened, error code is ' + error.code); - console.info('catch error happened, error message is ' + error.message); -} - -let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called. -let surfaceID = null; // Used to save the surface ID returned by getInputSurface. - -// Create a VideoRecorder object. -await media.createVideoRecorder().then((recorder) => { - console.info('case createVideoRecorder called'); - if (typeof (recorder) != 'undefined') { - videoRecorder = recorder; - console.info('createVideoRecorder success'); - } else { - console.info('createVideoRecorder failed'); - } -}, failureCallback).catch(catchCallback); - -// Obtain the surface ID, save it, and pass it to camera-related interfaces. -await videoRecorder.getInputSurface().then((surface) => { - console.info('getInputSurface success'); - surfaceID = surface; -}, failureCallback).catch(catchCallback); - -// Video recording depends on camera-related interfaces. The following operations can be performed only after the video output start interface is invoked. - -// Start video recording. -await videoRecorder.start().then(() => { - console.info('start success'); -}, failureCallback).catch(catchCallback); - -// Pause video playback before the video output stop interface is invoked. -await videoRecorder.pause().then(() => { - console.info('pause success'); -}, failureCallback).catch(catchCallback); - -// Resume video playback after the video output start interface is invoked. -await videoRecorder.resume().then(() => { - console.info('resume success'); -}, failureCallback).catch(catchCallback); - -// Stop video recording after the video output stop interface is invoked. -await videoRecorder.stop().then(() => { - console.info('stop success'); -}, failureCallback).catch(catchCallback); - -// Reset the recording configuration. -await videoRecorder.reset().then(() => { - console.info('reset success'); -}, failureCallback).catch(catchCallback); - -// Release the video recording resources and camera object resources. -await videoRecorder.release().then(() => { - console.info('release success'); -}, failureCallback).catch(catchCallback); - -// Set the related object to null. -videoRecorder = null; -surfaceID = null; -``` diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..2a0df0e3a4f6f2bbc27739a97b44df5f72569de5 --- /dev/null +++ b/en/application-dev/notification/Readme-EN.md @@ -0,0 +1,17 @@ +# Common Event and Notification + +[Common Event and Notification Overview](notification-brief.md) + +### Common Event + +* [Common Event Development](common-event.md) + +### Notification + +* [Notification Development](notification.md) + + + +### Debugging Tools + +* [Debugging Assistant Usage](assistant-guidelines.md) diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..35d3eaeaaddd023861056fe819fbe4016c59bb01 --- /dev/null +++ b/en/application-dev/notification/assistant-guidelines.md @@ -0,0 +1,134 @@ +# Debugging Assistant Usage + +The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell. + +### cem Debugging Assistant + +##### publish + +* Functionality + + Publishes a common event. + +* Usage + + `cem publish []` + + The table below describes the available options. + + | Option | Description | + | ------------ | ------------------------------------------ | + | -e/--event | Indicates the name of the common event to publish. Mandatory. | + | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published.| + | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. | + | -c/--code | Indicates the result code of the common event. Optional. | + | -d/--data | Indicates the data carried in the common event. Optional. | + | -h/--help | Indicates the help Information | + +* Example + + `cem publish --event "testevent"` + + Publish a common event named **testevent**. + + ![cem-publish-event](figures/cem-publish-event.png) + + + + `cem publish -e "testevent" -s -o -c 100 -d "this is data" ` + + Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**. + + ![cem-publish-all](figures/cem-publish-all.png) + +##### dump + +* Functionality + + Displays information about common events. + +* Usage + + `cem dump []` + + The table below describes the available options. + + | Option | Description | + | ---------- | -------------------------------------------- | + | -a/--all | Displays information about all common events that have been sent since system startup.| + | -e/--event | Displays information about a specific event. | + | -h/--help | Displays the help information. | + +* Example + +​ `cem dump -e "testevent"` + +​ Display information about the common event testevent. + +​ ![cem-dump-e](figures/cem-dump-e.png) + +##### help + +* Functionality + + Displays the help information. + +* Usage + + `cem help` + +* Example + + ![cem-help](figures/cem-help.png) + + + +### anm Debugging Assistant + +##### dump + +* Functionality + + Displays information about notifications. + +* Usage + + `anm dump []` + + The table below describes the available options. + + | Option | Description | + | ---------------- | ---------------------------------------- | + | -A/--active | Displays information about all active notifications. | + | -R/--recent | Displays information about the recent notifications. | + | -D/--distributed | Displays information about distributed notifications from other devices. | + | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional.| + | -h/--help | Displays the help information. | + +* Example + + `anm dump -A` + + Displays information about all active notifications. + + ![anm-dump-A](figures/anm-dump-A.png) + + + + `anm dump --setRecentCount 10` + + Set the number of the cached recent notifications to be displayed to 10. + +##### help + +* Functionality + + Displays the help information. + +* Usage + + `anm help` + +* Example + + ![anm-help](figures/anm-help.png) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md new file mode 100644 index 0000000000000000000000000000000000000000..cd139f0700d01475ad7f6fb358744e52ffafb913 --- /dev/null +++ b/en/application-dev/notification/common-event.md @@ -0,0 +1,179 @@ +# Common Event Development +### Introduction +OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events. + +Common events are classified into system common events and custom common events. + ++ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation. + ++ Custom common event: customized by applications to implement cross-application event communication. + +Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application. + +## Common Event Subscription Development + +### When to Use +You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md). + +### Available APIs +| API | Description| +| ---------------------------------------------------------------------------------------------- | ----------- | +| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| +| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | +| commonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| + +### How to Develop +1. Import the **commonEvent** module. + +```javascript +import commonEvent from '@ohos.commonEvent'; +``` + +2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). + +```javascript +private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information +var subscribeInfo = { + events: ["event"], +} +``` + +3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. + +```javascript +// Callback for subscriber creation. +commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { + if (err.code) { + console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err)) + } else { + console.log("[CommonEvent]CreateSubscriber") + this.subscriber = subscriber + this.result = "Create subscriber succeed" + } +}) +``` + +4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). + +```javascript +// Callback for common event subscription. +if (this.subscriber != null) { + commonEvent.subscribe(this.subscriber, (err, data) => { + if (err.code) { + console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err)) + } else { + console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data)) + this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code + } + }) + this.result = "Subscribe succeed" +} else { + prompt.showToast({ message: "Need create subscriber" }) +} +``` + +## Public Event Publishing Development + +### When to Use +You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. + +### Available APIs +| API | Description| +| ---------------------------------- | ------ | +| commonEvent.publish(event: string, callback: AsyncCallback) | Publishes a common event.| +| commonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| + +### How to Develop +#### Development for Publishing a Common Event +1. Import the **commonEvent** module. + +```javascript +import commonEvent from '@ohos.commonEvent'; +``` + +2. Pass in the common event name and callback, and publish the event. + +```javascript +// Publish a common event. +commonEvent.publish("event", (err) => { + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish1") + } +}) +``` + +#### Development for Publishing a Common Event with Given Attributes +1. Import the **commonEvent** module. + +```javascript +import commonEvent from '@ohos.commonEvent' +``` + +2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). + +```javascript +// Attributes of a common event. +var options = { + code: 1, // Result code of the common event + data: "initial data";// Result data of the common event +} +``` + +3. Pass in the common event name, attributes of the common event, and callback, and publish the event. + +```javascript +// Publish a common event. +commonEvent.publish("event", options, (err) => { + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish2") + } +}) +``` + +## Common Event Unsubscription Development + +### When to Use +You can use the **unsubscribe** API to unsubscribe from a common event. + +### Available APIs +| API | Description| +| ---------------------------------- | ------ | +| commonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| + +### How to Develop +1. Import the **commonEvent** module. + +```javascript +import commonEvent from '@ohos.commonEvent'; +``` + +2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). +3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. + +```javascript +if (this.subscriber != null) { + commonEvent.unsubscribe(this.subscriber, (err) => { + if (err.code) { + console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err)) + } else { + console.log("[CommonEvent]Unsubscribe") + this.subscriber = null + this.result = "Unsubscribe succeed" + } + }) +} +``` + +## Development Example + +The following sample is provided to help you better understand how to use the common event functionality: + +- [CommonEvent](https://gitee.com/openharmony/app_samples/tree/master/ability/CommonEvent) + +This sample shows how to use **CommonEvent** APIs in Extended TypeScript (eTS) to create subscribers and subscribe to, publish, and unsubscribe from common events. diff --git a/en/application-dev/notification/figures/anm-dump-A.png b/en/application-dev/notification/figures/anm-dump-A.png new file mode 100644 index 0000000000000000000000000000000000000000..368e6f2d810976486e786a4c8f0603a87ad48540 Binary files /dev/null and b/en/application-dev/notification/figures/anm-dump-A.png differ diff --git a/en/application-dev/notification/figures/anm-help.png b/en/application-dev/notification/figures/anm-help.png new file mode 100644 index 0000000000000000000000000000000000000000..d80ac8e76a70c2be383f0a05a12e3e707dcf242b Binary files /dev/null and b/en/application-dev/notification/figures/anm-help.png differ diff --git a/en/application-dev/notification/figures/ans.png b/en/application-dev/notification/figures/ans.png new file mode 100644 index 0000000000000000000000000000000000000000..8be552d2acedbef962326365fb2d19ded3838c14 Binary files /dev/null and b/en/application-dev/notification/figures/ans.png differ diff --git a/en/application-dev/notification/figures/cem-dump-e.png b/en/application-dev/notification/figures/cem-dump-e.png new file mode 100644 index 0000000000000000000000000000000000000000..c2422ba0e51011174c333985ad7647f170e0f126 Binary files /dev/null and b/en/application-dev/notification/figures/cem-dump-e.png differ diff --git a/en/application-dev/notification/figures/cem-help.png b/en/application-dev/notification/figures/cem-help.png new file mode 100644 index 0000000000000000000000000000000000000000..8ca4bc0605f9c1f75a8cb45f8ab77c9c5d6f04e4 Binary files /dev/null and b/en/application-dev/notification/figures/cem-help.png differ diff --git a/en/application-dev/notification/figures/cem-publish-all.png b/en/application-dev/notification/figures/cem-publish-all.png new file mode 100644 index 0000000000000000000000000000000000000000..99526e1f7245d101914354e2a89d5e97d710c27f Binary files /dev/null and b/en/application-dev/notification/figures/cem-publish-all.png differ diff --git a/en/application-dev/notification/figures/cem-publish-event.png b/en/application-dev/notification/figures/cem-publish-event.png new file mode 100644 index 0000000000000000000000000000000000000000..f0ca7e73093f1be72c743bd7c08467f11e2a0e05 Binary files /dev/null and b/en/application-dev/notification/figures/cem-publish-event.png differ diff --git a/en/application-dev/notification/figures/ces.png b/en/application-dev/notification/figures/ces.png new file mode 100644 index 0000000000000000000000000000000000000000..b1aa5438a19ac79899e0f45791f3e1a79e4242dc Binary files /dev/null and b/en/application-dev/notification/figures/ces.png differ diff --git a/en/application-dev/notification/figures/notification.png b/en/application-dev/notification/figures/notification.png new file mode 100644 index 0000000000000000000000000000000000000000..93029e29a91d6dd435a9a768cb79c5fc48184565 Binary files /dev/null and b/en/application-dev/notification/figures/notification.png differ diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md new file mode 100644 index 0000000000000000000000000000000000000000..8be39b2cc823398e4572a77469909f9fd06e2a5f --- /dev/null +++ b/en/application-dev/notification/notification-brief.md @@ -0,0 +1,23 @@ +# Common Event and Notification Overview + +The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, or warning information. + +Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events. + +![ces](figures/ces.png) + +- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. + +- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. + + The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: + + - Display received SMS messages and instant messages. + + - Display push messages of applications, such as advertisements, version updates, and news notifications. + + - Display ongoing events, such as music playback, navigation information, and download progress. + +Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. + +![ans](figures/ans.png) diff --git a/en/application-dev/notification/notification.md b/en/application-dev/notification/notification.md new file mode 100644 index 0000000000000000000000000000000000000000..a8822563cd639844817b860fb5760ee605edb307 --- /dev/null +++ b/en/application-dev/notification/notification.md @@ -0,0 +1,248 @@ + + +# Notification Development + +## When to Use + +OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI. + +Below are some typical use cases for notifications: + +- Display received SMS messages and instant messages. +- Display push messages of applications, such as advertisements and version updates. +- Display ongoing events, such as navigation information and download progress. + + + +## Notification Service Process + +The notification service process involves the ANS subsystem, notification sender, and notification subscriber. + +A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber. + +System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database. + +![1648113187545](figures/notification.png) + + + +## Available APIs + +Certain APIs can be invoked only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md). + +**Table 1** APIs for notification enabling + +| API | Description | +| ------------------------------------------------------------ | ---------------- | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void | Checks whether notification is enabled.| +| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void | Sets whether to enable notification. | + +If the notification function of an application is disabled, it cannot send notifications. + + + +**Table 2** APIs for notification subscription + +| API | Description | +| ------------------------------------------------------------ | ---------------- | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void | Subscribes to a notification with the subscription information specified.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Subscribes to all notifications. | +| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Unsubscribes from a notification. | + +The subscription APIs support subscription to all notifications or notifications from specific applications. + + + +**Table 3** Notification subscription callbacks + +| API | Description | +| ------------------------------------------------ | ---------------- | +| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. | +| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. | +| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.| +| onConnect?:() => void; | Callback for subscription. | +| onDisconnect?:() => void; | Callback for unsubscription. | + + + +**Table 4** APIs for notification sending + +| API | Description | +| ------------------------------------------------------------ | ------------------------ | +| publish(request: NotificationRequest, callback: AsyncCallback): void | Publishes a notification. | +| publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void | Publishes a notification to the specified user. | +| cancel(id: number, label: string, callback: AsyncCallback): void | Cancels a specified notification. | +| cancelAll(callback: AsyncCallback): void; | Cancels all notifications published by the application.| + +The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. + + + +## Development Guidelines + +The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications. + +### Modules to Import + +```js +import Notification from '@ohos.notification'; +``` + + + +### Subscribing to Notifications + +The notification recipient preferentially initiates a notification subscription request to the notification subsystem. + +```js +var subscriber = { + onConsume: function (data) { + let req = data.request; + console.info('===>onConsume callback req.id: ' + req.id); + }, + onCancel: function (data) { + let req = data.request; + console.info('===>onCancel callback req.id: : ' + req.id); + }, + onUpdate: function (data) { + console.info('===>onUpdate in test===>'); + }, + onConnect: function () { + console.info('===>onConnect in test===>'); + }, + onDisconnect: function () { + console.info('===>onDisConnect in test===>'); + }, + onDestroy: function () { + console.info('===>onDestroy in test===>'); + }, + }; + + Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result. + if (err.code) { + console.error('===>failed to subscribe because ' + JSON.stringify(err)); + return; + } + console.info('===>subscribeTest success : ' + JSON.stringify(data)); + }); +``` + + + +### Publishing Notifications + +Before publishing a notification, make sure the notification feature is enabled for your application. This feature is disabled by default and can be enabled in the notification settings. + +##### Publishing Notifications + +To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published. + +Normal Text Notification + +```js +// Create a NotificationRequest object. +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +// Publish the notification. +Notification.publish(notificationRequest) .then((data) => { + console.info('===>publish promise success req.id : ' + notificationRequest.id); +}).catch((err) => { + console.error('===>publish promise failed because ' + JSON.stringify(err)); +}); +``` + + + +Notification Containing WantAgent. + +For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md). + +- Create a **WantAgent** object. + +```js +import wantAgent from '@ohos.wantAgent'; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + bundleName: 'ohos.samples.eTSNotification', + abilityName: 'ohos.samples.eTSNotification.MainAbility', + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// WantAgent object +var WantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("===>getWantAgentCallback===>"); + if (err.code == 0) { + WantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} + +// Obtain the WantAgent object. +wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +``` + +- Publish the notification. + +```js +// Create a NotificationRequest object. +var notificationRequest = { + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "AceApplication_Title", + text: "AceApplication_Text", + additionalText: "AceApplication_AdditionalText" + }, + }, + id: 1, + label: 'TEST', + wantAgent: WantAgent, + slotType: Notification.SlotType.OTHER_TYPES, + deliveryTime: new Date().getTime() +} + +// Publish the notification. +Notification.publish(notificationRequest) .then((data) => { + console.info('===>publish promise success req.id : ' + notificationRequest.id); +}).catch((err) => { + console.error('===>publish promise failed because ' + JSON.stringify(err)); +}); +``` + + + +- Cancel the notification. + +An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself. + +```js +// cancel callback +function cancelCallback(err) { + console.info("===>cancelCallback===>"); +} + +Notification.cancel(1, "label", cancelCallback) +``` + + diff --git a/en/device-dev/bundles/public_sys-resources/icon-caution.gif b/en/application-dev/notification/public_sys-resources/icon-caution.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-caution.gif rename to en/application-dev/notification/public_sys-resources/icon-caution.gif diff --git a/en/device-dev/bundles/public_sys-resources/icon-danger.gif b/en/application-dev/notification/public_sys-resources/icon-danger.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-danger.gif rename to en/application-dev/notification/public_sys-resources/icon-danger.gif diff --git a/en/device-dev/bundles/public_sys-resources/icon-note.gif b/en/application-dev/notification/public_sys-resources/icon-note.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-note.gif rename to en/application-dev/notification/public_sys-resources/icon-note.gif diff --git a/en/device-dev/bundles/public_sys-resources/icon-notice.gif b/en/application-dev/notification/public_sys-resources/icon-notice.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-notice.gif rename to en/application-dev/notification/public_sys-resources/icon-notice.gif diff --git a/en/device-dev/bundles/public_sys-resources/icon-tip.gif b/en/application-dev/notification/public_sys-resources/icon-tip.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-tip.gif rename to en/application-dev/notification/public_sys-resources/icon-tip.gif diff --git a/en/device-dev/bundles/public_sys-resources/icon-warning.gif b/en/application-dev/notification/public_sys-resources/icon-warning.gif similarity index 100% rename from en/device-dev/bundles/public_sys-resources/icon-warning.gif rename to en/application-dev/notification/public_sys-resources/icon-warning.gif diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index f58cdcbec9ef695965bfdde9703880fbbc5e6ac8..675d011f660bfbea605bff1f7e212e38e93b64fc 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -2,11 +2,12 @@ - Getting Started - [Preparations](start-overview.md) - - [Getting Started with eTS](start-with-ets.md) + - [Getting Started with eTS in the Traditional Coding Approach](start-with-ets.md) + - [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md) - [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md) - [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md) - - Development Fundamentals - - [Directory Structure](package-structure.md) - - [Resource File](basic-resource-file-categories.md) + - [Application Development Package Structure ](package-structure.md) + - [Resource File Categories](basic-resource-file-categories.md) + - [SysCap](syscap.md) diff --git a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md index 3051831470bdb57400a00583c97913cbfda2523f..464e0d32b54907bb3faac50a3df382a33e520745 100644 --- a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md +++ b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @@ -1,2 +1,19 @@ -# DevEco Studio \(OpenHarmony\) User Guide +# DevEco Studio (OpenHarmony) User Guide + + +DevEco Studio is a one-stop, distributed platform developed based on the IntelliJ IDEA Community (Open Source) Edition. It helps you develop versatile all-device, all-scenario applications, offering distributed multi-device development, debugging, and simulation, as well as comprehensive quality and security safeguards. + +[DevEco Studio 3.0 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) stands out in the following aspects: + +- One-stop information acquisition platform +- A wide range of device project templates +- Efficient code editing +- Visualized UI development +- Bidirectional and instsant UI preview +- High-performing compilation tool Hvigor +- Support for application development based on the device Syscap capability set +- Automatic application signature mechanism +- A diverse array of code debugging and profiling features + +For more information, see [DevEco Studio (OpenHarmony) User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). diff --git a/en/application-dev/quick-start/figures/20220329-103626.gif b/en/application-dev/quick-start/figures/20220329-103626.gif new file mode 100644 index 0000000000000000000000000000000000000000..1f3a67796fd41dce99b4256a115fd1d0733ebb79 Binary files /dev/null and b/en/application-dev/quick-start/figures/20220329-103626.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png b/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png new file mode 100644 index 0000000000000000000000000000000000000000..6d8b4f343d3744e245a656987a85a6da2c9bb18e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233208980.gif b/en/application-dev/quick-start/figures/en-us_image_0000001233208980.gif new file mode 100644 index 0000000000000000000000000000000000000000..c373859c5b39169033f88d6ad7ec8458e9e92cb2 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233208980.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png b/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png new file mode 100644 index 0000000000000000000000000000000000000000..890e12eee8b4534a2b94206c6b73edc81d1ee3ee Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png b/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png new file mode 100644 index 0000000000000000000000000000000000000000..dd28ccedfa20424aad7e01ee52d9246788b72eb8 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png new file mode 100644 index 0000000000000000000000000000000000000000..cd1603f14f7a5d30c79613201e85ed240f10a409 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png new file mode 100644 index 0000000000000000000000000000000000000000..890e12eee8b4534a2b94206c6b73edc81d1ee3ee Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png new file mode 100644 index 0000000000000000000000000000000000000000..ab2ae3c740dfee9b303d6319516c9facb3574184 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png new file mode 100644 index 0000000000000000000000000000000000000000..6d8b4f343d3744e245a656987a85a6da2c9bb18e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png new file mode 100644 index 0000000000000000000000000000000000000000..dd28ccedfa20424aad7e01ee52d9246788b72eb8 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001235731706.gif b/en/application-dev/quick-start/figures/en-us_image_0000001235731706.gif new file mode 100644 index 0000000000000000000000000000000000000000..85d496e777b607878e2e753870c3d17edbe9ac84 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001235731706.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001235732402.gif b/en/application-dev/quick-start/figures/en-us_image_0000001235732402.gif new file mode 100644 index 0000000000000000000000000000000000000000..52c44c8b2924878e6fc1156039a815b266dfcfae Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001235732402.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001235745716.png b/en/application-dev/quick-start/figures/en-us_image_0000001235745716.png new file mode 100644 index 0000000000000000000000000000000000000000..d42c9c66018ee55f3c200ff108fb0a77b6c82df3 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001235745716.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001235892798.png b/en/application-dev/quick-start/figures/en-us_image_0000001235892798.png new file mode 100644 index 0000000000000000000000000000000000000000..a1ac0507eae1ecbc825075ef08c09e01b4f4858e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001235892798.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277488977.gif b/en/application-dev/quick-start/figures/en-us_image_0000001277488977.gif new file mode 100644 index 0000000000000000000000000000000000000000..12998de5ba839e83c7b88f35b7428f81569b6464 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277488977.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png b/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png b/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png b/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png new file mode 100644 index 0000000000000000000000000000000000000000..12978dc861aaa1f826404d9c6838bb8628381615 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png new file mode 100644 index 0000000000000000000000000000000000000000..4d6994bf5bf8dd05baf7eac6274f56de27fc23b3 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png new file mode 100644 index 0000000000000000000000000000000000000000..6d8b4f343d3744e245a656987a85a6da2c9bb18e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png new file mode 100644 index 0000000000000000000000000000000000000000..cc3ca5fd7274be67f62b32e531fcbbaf294317c1 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png new file mode 100644 index 0000000000000000000000000000000000000000..64bb2a8edf4720cdb4d4d3b6055baa03c81b0a54 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png new file mode 100644 index 0000000000000000000000000000000000000000..335548669bb32a22f146d76f9ab88527e52f515a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png new file mode 100644 index 0000000000000000000000000000000000000000..6c1ea01d448434e7cfd94e174474e72b57d3b4cc Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001280255513.gif b/en/application-dev/quick-start/figures/en-us_image_0000001280255513.gif new file mode 100644 index 0000000000000000000000000000000000000000..59d7dffeadc05a792920a481cdf2e2422147434f Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001280255513.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001280383937.gif b/en/application-dev/quick-start/figures/en-us_image_0000001280383937.gif new file mode 100644 index 0000000000000000000000000000000000000000..28a648445a7936a190fa3b129489c68dea97f963 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001280383937.gif differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001280385809.png b/en/application-dev/quick-start/figures/en-us_image_0000001280385809.png new file mode 100644 index 0000000000000000000000000000000000000000..9b93b35e975769a97c817a70f55908452768101a Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001280385809.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064841782.png b/en/application-dev/quick-start/figures/image-20220326064841782.png new file mode 100644 index 0000000000000000000000000000000000000000..57ee1a1ca5a7e62893195a296795ffb8eec00bdc Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326064841782.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064913834.png b/en/application-dev/quick-start/figures/image-20220326064913834.png new file mode 100644 index 0000000000000000000000000000000000000000..c55df52abc42e8f9a4d0a9d5fc098aa3a3456a0e Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326064913834.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326064955505.png b/en/application-dev/quick-start/figures/image-20220326064955505.png new file mode 100644 index 0000000000000000000000000000000000000000..db4f6fa370cd5c02b3d2cd98b187e324848e8d99 Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326064955505.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065043006.png b/en/application-dev/quick-start/figures/image-20220326065043006.png new file mode 100644 index 0000000000000000000000000000000000000000..997acad905475baa43f0debf936508efdcfa2c5f Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326065043006.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065124911.png b/en/application-dev/quick-start/figures/image-20220326065124911.png new file mode 100644 index 0000000000000000000000000000000000000000..a028e5447476a9d03bcd58285af6fb6dd4aa7d1d Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326065124911.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326065201867.png b/en/application-dev/quick-start/figures/image-20220326065201867.png new file mode 100644 index 0000000000000000000000000000000000000000..e64cc86fef41a31e4a6b93a96faf2ee7eda03e86 Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326065201867.png differ diff --git a/en/application-dev/quick-start/figures/image-20220326072448840.png b/en/application-dev/quick-start/figures/image-20220326072448840.png new file mode 100644 index 0000000000000000000000000000000000000000..dac0f9dfe41d8f7667e21f2224563910e3aa9429 Binary files /dev/null and b/en/application-dev/quick-start/figures/image-20220326072448840.png differ diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md index b9e4caa013ad468f43ca0a7a3ee486623018a028..1b3d88f8b378aa84ce9d571c97320b5b6c861494 100644 --- a/en/application-dev/quick-start/package-structure.md +++ b/en/application-dev/quick-start/package-structure.md @@ -1,10 +1,24 @@ -# Directory Structure -In an application development project, you need to declare the package structure of the application in the **config.json** file. -The following is an example of the configuration file: +# Application Package Structure Configuration File -``` +In an application development project, you need to declare the package structure of the application in the **config.json** file. + +## Internal Structure of the config.json File + +The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and ***module***. See Table 1 for details. + +Table 1 Internal structure of the config.json file + +| Tag | Description | Data Type| Default| +| ------------ | ------------------------------------------------------------ | -------- | ---------- | +| app | Global configuration of an application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#Internal-structure-of-the-app-tag).| Object | No | +| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#Internal-structure-of-the-deviceconfig-tag).| Object | No | +| module | Configuration of a HAP file. The ***module*** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#Internal-structure-of-the-module-tag).| Object | No | + +Example of config.json: + +```json { "app": { "bundleName": "com.example.myapplication", @@ -27,7 +41,6 @@ The following is an example of the configuration file: "default" ], "distro": { - "deliveryWithInstall": true, "moduleName": "entry", "moduleType": "entry" }, @@ -67,9 +80,681 @@ The following is an example of the configuration file: } ``` -Note the following when declaring the package structure: +### Internal Structure of the app Tag + +The **app** tag contains the global configuration information of the application. For details about the internal structure, see Table 2. + +Table 2 Internal structure of the app tag + +| Attribute | Description | Data Type| Default | +| ---------- | ------------------------------------------------------------ | -------- | ------------------ | +| bundleName | Bundle name of the application. It uniquely identifies the application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain name suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | +| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| version | Version information of the application. For details, see Table 3. | Object | No | +| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty)| + +Table 3 Internal structure of version + +| Attribute | Description | Data Type| Default | +| ------------------------ | ------------------------------------------------------------ | -------- | -------------------------- | +| name | Application version number visible to users. The value can be customized and cannot exceed 127 bytes. The customization rules are as follows:
API 5 and earlier versions: A three-segment version number is recommended, for example, A.B.C (also compatible with A.B). In the version number, A, B, and C are integers ranging from 0 to 999. Other formats are not supported.
A indicates the major version number.
B indicates the minor version number.
C indicates the patch version number.
API 6 and later versions: A four-segment version number is recommended, for example, A.B.C.D. In the version number, A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
A indicates the major version number.
B indicates the minor version number.
C indicates the feature version number.
D indicates the patch version number.| Number | No | +| code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The value rules are as follows:
API 5 and earlier versions: It is a non-negative integer less than 32 bits in binary mode, converted from the value of version.name as follows: The conversion rules are as follows:
Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001.
API 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer ranging from 2 to 31. Note that the value must be updated each time the application version is updated. The value for a later version must be greater than that for an earlier version.| Number | No | +| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with the version on other devices in the cross-device scenario.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| + +Table 4 Internal structure of apiVersion + +| Attribute | Description | Data Type| Default| +| ----------- | ----------------------------------------------------------- | -------- | ---------- | +| compatible | Minimum API version required for running the application. The value ranges from 0 to 2147483647. | Integer | Yes | +| target | Target API version required for running the application. The value ranges from 0 to 2147483647.| Integer | Yes | +| releaseType | Type of the target API version required for running the application. | String | Yes | + +Example of the app tag structure: + +```json +"app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 5, + "releaseType": "Beta1" + } + } +``` + +### Internal Structure of the deviceConfig Tag + +The **deviceConfig** tag contains the application configuration information on the device, including attributes such as **default**, **tv**, **car**, **wearable**, and **liteWearable**. The **default** configuration applies to all types of devices. You need to declare the peculiar configuration of a specific device type in the associated sub-tag of this type. For details about the internal structure, see Table 5. + +Table 5 Internal structure of the deviceConfig tag + +| Attribute | Description | Data Type| Default | +| ------------ | ----------------------------------------------- | -------- | ------------------ | +| default | Application configuration applied to all types of devices. See Table 6. | Object | No | +| tablet | Application configuration specific to tablets. See Table 6. | Object | Yes (initial value: left empty)| +| tv | Application configuration specific to smart TVs. See Table 6. | Object | Yes (initial value: left empty)| +| car | Application configuration specific to head units. See Table 6. | Object | Yes (initial value: left empty)| +| wearable | Application configuration specific to wearables. See Table 6. | Object | Yes (initial value: left empty)| +| liteWearable | Application configuration specific to lite wearables. See Table 6.| Object | Yes (initial value: left empty)| + +For details about the internal structures of device attributes, see Table 6. + +Table 6 Internal structure of device attributes + +| Attribute | Description | Data Type| Default | +| ------------------ | ------------------------------------------------------------ | -------- | ----------------------- | +| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters. | String | Yes | +| supportBackup | Whether the application supports backup and restoration. If this attribute is set to **false**, backup or restoration will not be performed for the application.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | Boolean | Yes (initial value: **false**)| +| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. If this attribute is set to **false**, the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | Boolean | Yes (initial value: **true**) | +| directLaunch | Whether the application can be started when the device is locked. If you want to start the application without unlocking the device, set this attribute to **true**. Devices running OpenHarmony do not support this attribute.| Boolean | Yes (initial value: **false**)| +| ark | Maple configuration. See Table 7. | Object | Yes (initial value: left empty) | +| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. See Table 9.| Object | Yes (initial value: left empty) | + +Table 7 Internal structure of the **ark** attribute + +| Attribute | Description | Data Type| Default | +| ---------- | -------------------------------- | -------- | ------------------------------ | +| reqVersion | Maple version required for the application. For details, see Table 8.| Object | No | +| flag | Type of the Maple application. | String | No (available options: **m**, **mo**, **z**).| + +Table 8 Internal structure of the reqVersion attribute + +| Attribute | Description | Data Type| Default| +| ---------- | --------------------------------------------------------- | -------- | ---------- | +| compatible | Minimum Maple version required for the application. The value is a 32-bit unsigned integer.| Integer | No | +| target | Type of the Maple application. The value is a 32-bit unsigned integer. | Integer | No | + +Table 9 Internal structure of the network attribute + +| Attribute | Description | Data Type| Default | +| ---------------- | ------------------------------------------------------------ | -------- | ----------------------- | +| cleartextTraffic | Whether to allow the application to use plaintext traffic, for example, plaintext HTTP traffic.
**true**: The application is allowed to use plaintext traffic.
**false**: The application is not allowed to use plaintext traffic.| Boolean | Yes (initial value: **false**)| +| securityConfig | Network security configuration of the application. For details, see Table 10. | Object | Yes (initial value: left empty) | + +Table 10 Internal structure of the securityConfig attribute + +| Attribute | Sub-attribute | Description | Data Type| Default | +| -------------- | ------------------ | ------------------------------------------------------------ | -------- | ---------------- | +| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. To be more specific, the **domainSettings** object of a large domain can be nested with the **domainSettings** objects of small network domains.| Object| Yes (initial value: left empty)| +| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | +| | domains | Domain name configuration. This attribute consists of the **subdomains** and **name** sub-attributes.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | + +Example of the deviceConfig tag structure: + +```json +"deviceConfig": { + "default": { + "process": "com.example.test.example", + "supportBackup": false, + "network": { + "cleartextTraffic": true, + "securityConfig": { + "domainSettings": { + "cleartextPermitted": true, + "domains": [ + { + "subdomains": true, + "name": "example.ohos.com" + } + ] + } + } + } + } +} +``` + +### Internal Structure of the module Tag + +The **module** tag contains the configuration information of the HAP file. For details about the internal structure, see Table 11. + +Table 11 Internal structure of the module tag + +| Attribute | Description | Data Type | Default | +| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | +| package | Structure name of the HAP file. The value must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | No | +| name | Class name of the HAP file. The value is in the reverse domain name notation. The prefix must be the same as the package name specified by the **package** label at the same level. The value can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | No | +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: left empty) | +| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | +| deviceType | Type of device on which the abilities can run. The device types predefined in the system include **tablet**, **tv**, **car**, **wearable**, and **liteWearable**. | String array| No | +| distro | Distribution description of the current HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. For details, see Table 12. | Object | No | +| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | +| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | +| js | A set of JS modules developed using the ArkUI framework. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | +| shortcuts | Shortcut information of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | +| reqPermissions | Permissions that the application applies for from the system before its running. For details, see Table 21. | Object array | Yes (initial value: left empty) | +| colorMode | Color mode of the application.
**dark**: Resources applicable for the dark mode are selected.
**light**: Resources applicable for the light mode are selected.
**auto**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: **auto**) | +| distroFilter | Application distribution rules.
This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Applications can be distributed by API version, screen shape, or screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty) Configure this attribute when an application has multiple entry modules.| +| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | +| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | +| allowClassMap | Metadata of the HAP file. The value can be **true** or **false**. If the value is **true**, the HAP file uses the Java object proxy mechanism provided by the OpenHarmony framework. | Boolean | No (initial value: **false**) | +| entryTheme | Keyword of an OpenHarmony internal topic. Set it to the resource index of the name.| String | Yes (initial value: left empty) | + +Example of the module tag structure: + +```json +"module": { + "mainAbility": "MainAbility", + "package": "com.example.myapplication.rntry", + "name": ".MyOHOSAbilityPackage", + "description": "$string:description_application", + "supportModes": [ + "drive" + ], + "deviceType": [ + "car" + ], + "distro": { + "moduleName": "ohos_entry", + "moduleType": "entry" + }, + "abilities": [ + ... + ], + "shortcuts": [ + ... + ], + "js": [ + ... + ], + "reqPermissions": [ + ... + ], + "colorMode": "light" +} +``` + +Table 12 Internal structure of the distro attribute + +| Attribute | Description | Data Type| Default| +| ---------------- | ------------------------------------------------------------ | -------- | ---------- | +| moduleName | Name of the current HAP file. The maximum length is 31 characters. | String | No | +| moduleType | Type of the current HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**.| String | No | +| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements.| Boolean | No | + +Example of the distro attribute structure: + +```json +"distro": { + "moduleName": "ohos_entry", + "moduleType": "entry", + "installationFree": true +} +``` + +Table 13 Internal structure of the metaData attribute + +| Attribute | Description | Data Type| Default | +| ------------- | ------------------------------------------------------------ | -------- | -------------------- | +| parameters | Metadata of the parameters to be passed for calling the ability. The metadata of each parameter consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 14.| Object array| Yes (initial value: left empty) | +| results | Metadata of the ability return value. The metadata of each return value consists of the **description**, **name**, and **type** sub-attributes. For details, see Table 15.| Object array| Yes (initial value: left empty)| +| customizeData | Custom metadata of the parent component. **parameters** and **results** cannot be configured in **application**. For details, see Table 16.| Object array| Yes (initial value: left empty)| + +Table 14 Internal structure of the parameters attribute + +| Attribute | Description | Data Type| Default | +| ----------- | ------------------------------------------------------------ | -------- | ------------------ | +| description | Description of the parameter. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| +| name | Name of the parameter. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| +| type | Type of the parameter, for example, **Integer**. | String | No | + +Table 15 Internal structure of the results attribute + +| Attribute | Description | Data Type| Default | +| ----------- | ------------------------------------------------------------ | -------- | -------------------- | +| description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| +| name | Name of the return value. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| +| type | Type of the return value, for example, **Integer**. | String | No | + +Table 16 Internal structure of the customizeData attribute + +| Attribute| Description | Data Type| Default | +| -------- | ---------------------------------------------------------- | -------- | -------------------- | +| name | Key of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Custom format of the data element. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| + +Example of the metaData attribute structure: + +```json +"metaData": { + "parameters" : [{ + "name" : "string", + "type" : "Float", + "description" : "$string:parameters_description" + }], + "results" : [{ + "name" : "string", + "type" : "Float", + "description" : "$string:results_description" + }], + "customizeData" : [{ + "name" : "string", + "value" : "string", + "extra" : "$string:customizeData_description" + }] +} +``` + +Table 17 Internal structure of the abilities attribute + +| Attribute | Description | Data Type | Default | +| ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | +| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | +| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types.
Note: When you use DevEco Studio to create a project, the configuration of the first ability is generated by default, including the **MainAbility.java** file and the class name **MainAbility** defaulted in the **name** string for the **abilities** attribute in **config.json**. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters. | String | No | +| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) | +| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | +| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 characters. | String | Yes (No for abilities using the Data template) | +| launchType | Startup type of the ability. The value can be **standard**, **singleMission**, or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup.
Most abilities can use this type.
**singleMission**: Only a single **Ability** instance can be created in each task stack during startup.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: **standard**) | +| visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean | Yes (initial value: **false**) | +| permissions | Permissions required for abilities of another application to call the current ability, generally in the format of a reverse domain name. The value can be either the permissions predefined in the OS or your custom permissions.| String array| Yes (initial value: left empty) | +| skills | Types of the **want** that can be accepted by the ability. | Object array | Yes (initial value: left empty) | +| deviceCapability | Device capabilities required to run the ability.| String array| Yes (initial value: left empty) | +| metaData | Metadata. For details, see Table 13. | Object | Yes (initial value: left empty) | +| type | Type of the ability. Available values are as follows:
**page**: FA developed using the Page template to provide the capability of interacting with users.
**service**: PA developed using the Service template to provide the capability of running tasks in the background.
**data**: PA developed using the Data template to provide unified data access for external systems.
**CA**: ability that can be started by other applications as a window.| String | No | +| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
unspecified: indicates that the system automatically determines the display orientation of the ability.
**landscape**: indicates the landscape orientation.
**portrait**: indicates the portrait orientation.
**followRecent**: indicates that the orientation follows the most recent application in the stack.| String | Yes (initial value: **unspecified**) | +| backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This attribute applies only to the ability using the Service template. Available values are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**pictureInPicture**: picture in picture (PiP) and small-window video playback services
**voip**: voice/video call and VoIP services
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services
**wifiInteraction**: WLAN scanning, connection, and transmission services
**screenFetch**: screen recording and screenshot services
**multiDeviceConnection**: multi-device interconnection service| String array| Yes (initial value: left empty) | +| grantPermission | Whether permissions can be granted for any data in the ability. | Boolean | Yes (initial value: left empty) | +| readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: left empty) | +| writePermission | Permission required for writing data to the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: left empty) | +| configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. Available values are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user has selected a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty) | +| mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: bundle name of the application) | +| targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | String | Yes (initial value: left empty, indicating that the current ability is not an alias)| +| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | Boolean | Yes (initial value: **false**) | +| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. | Boolean | Yes (initial value: **false**) | +| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) | +| forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | +| srcLanguage | Programming language used to develop the ability. | String | The value can be **java**, **js**, or **ets**. | +| srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) | +| uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | + +Table 18 Internal structure of the uriPermission attribute + +| Attribute| Description | Data Type| Default | +| -------- | ----------------------- | -------- | ------------------------- | +| path | Path identified by **uriPermission**.| String | No | +| mode | Mode matching the **uriPeimission**.| String | Yes (initial value: *default***)| + +Example of the abilities attribute structure: + +```json +"abilities": [ + { + "name": ".MainAbility", + "description": "test main ability", + "icon": "$media:ic_launcher", + "label": "$media:example", + "launchType": "standard", + "orientation": "unspecified", + "permissions": [ + ], + "visible": true, + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ], + "configChanges": [ + "locale", + "layout", + "fontSize", + "orientation" + ], + "type": "page" + }, + { + "name": ".PlayService", + "description": "example play ability", + "icon": "$media:ic_launcher", + "label": "$media:example", + "launchType": "standard", + "orientation": "unspecified", + "visible": false, + "skills": [ + { + "actions": [ + "action.play.music", + "action.stop.music" + ], + "entities": [ + "entity.audio" + ] + } + ], + "type": "service", + "backgroundModes": [ + "audioPlayback" + ] + }, + { + "name": ".UserADataAbility", + "type": "data", + "uri": "dataability://com.example.world.test.UserADataAbility", + "visible": true + } +] +``` + +Table 19 Internal structure of the skills attribute + +| Attribute| Description | Data Type | Default | +| -------- | ------------------------------------------------------------ | ---------- | -------------------- | +| actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| +| entities | Entities of the **want** that can be accepted by the ability, such as video and Home application.| String array| Yes (initial value: left empty)| +| uris | URIs of the **want** that can be accepted by the ability. For details, see Table 20.| Object array | Yes (initial value: left empty)| + +Table 20 Internal structure of the uris attribute + +| Attribute | Description | Data Type| Default | +| ------------- | -------------------------- | -------- | -------------------- | +| scheme | Scheme in the URI. | String | No | +| host | Host in the URI. | String | Yes (initial value: left empty)| +| port | Port number in the URI. | String | Yes (initial value: left empty)| +| pathStartWith | **pathStartWith** value in the URI.| String | String | +| path | Path in the URI. | String | Yes (initial value: left empty)| +| pathRegx | **pathRegx** value in the URI. | String | Yes (initial value: left empty)| +| type | Type of the URI. | String | Yes (initial value: left empty)| + +Example of the skills attribute structure: + +```json +"skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ], + "uris": [ + { + "scheme": "http", + "host": "www.example.com", + "port": "8080", + "path": "query/student/name", + "type": "text/*" + } + ] + } +] +``` + +Table 21 reqPermissions + +| Attribute | Description | **Type**| **Value Range** | **Default Value** | **Restrictions** | +| --------- | ------------------------------------------------------------ | -------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | +| name | Permission name, which is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | +| reason | Reason for applying for the permission, which is mandatory only when applying for the **user_grant** permission.| String | The displayed text cannot exceed 256 bytes. | Empty | This field is mandatory for the **user_grant** permission. If it is left empty, application release will be rejected. Multi-language adaptation is required.| +| usedScene | Description of the application scenario and timing for using the permission, which is mandatory only when applying for the **user_grant** permission. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured.| Object | **ability**: ability name; **when**: **inuse** or **always**| **ability**: left empty; **when**: **inuse**| The **ability** sub-attribute is mandatory for the **user_grant** permission, and the **when** field is optional. | + +Table 22 Internal structure of the js attribute + +| Attribute| Description | Data Type| Default | +| -------- | ------------------------------------------------------------ | -------- | ------------------------ | +| name | Name of a JavaScript component. The default value is **default**. | String | No | +| pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | +| window | Window-related configurations. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device type types. For details, see Table 23. | Object | Yes | +| type | Type of the JavaScript component. Available values are as follows:
**normal**: indicates that the JavaScript component is an application instance.
**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| +| mode | Development mode of the JavaScript component. For details, see Table 24. | Object | Yes (initial value: left empty) | + +Table 23 Internal structure of the window attribute + +| Attribute | Description | Data Type| Default | +| --------------- | ------------------------------------------------------------ | -------- | ----------------------- | +| designWidth | Baseline width for page design, in pixels. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | +| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| + +Table 24 Internal structure of the **mode** attribute + +| Attribute| Description | Data Type | Default | +| -------- | -------------------- | ----------------------------------- | --------------------------- | +| type | Type of the JavaScript component.| String. The value can be **pageAbility** or **form**.| Yes (initial value: **pageAbility**)| +| syntax | Syntax type of the JavaScript component.| String. The value can be **hml** or **ets**. | Yes (initial value: **hml**) | + +Example of the js attribute structure: + +```json +"js": [ + { + "name": "default", + "pages": [ + "pages/index/index", + "pages/detail/detail" + ], + "window": { + "designWidth": 720, + "autoDesignWidth": false + }, + "type": "form" + } +] +``` + +Table 25 Internal structure of the shortcuts attribute + +| Attribute | Description | Data Type| Default | +| ---------- | ------------------------------------------------------------ | -------- | ------------------ | +| shortcutId | Shortcut ID. The value is a string with a maximum of 63 bytes. | String | No | +| label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| +| icon | Icon of the shortcut. The value is a resource index to the description. | String | Yes (initial value: left empty)| +| intents | Intents to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes. For details, see Table 26.| Object array| Yes (initial value: left empty)| + +Table 26 Internal structure of the intents attribute + +| Attribute | Description | Data Type| Default | +| ------------ | --------------------------------------- | -------- | -------------------- | +| targetClass | Class name for the target ability of the shortcut. | String | Yes (initial value: left empty)| +| targetBundle | Application bundle name for the target ability of the shortcut.| String | Yes (initial value: left empty)| + +Example of the shortcuts attribute structure: + +```json +"shortcuts": [ + { + "shortcutId": "id", + "label": "$string:shortcut", + "intents": [ + { + "targetBundle": "com.example.world.test", + "targetClass": "com.example.world.test.entry.MainAbility" + } + ] + } +] +``` + +Table 27 Internal structure of the forms attribute + +| Attribute | Description | Data Type | Default | +| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | +| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | +| type | Type of the widget. Available values are as follows:
**Java**: indicates a Java-programmed widget.
**JS**: indicates a JavaScript-programmed widget.| String | No | +| colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| +| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | +| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | +| landscapeLayouts | Landscape layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | +| portraitLayouts | Portrait layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | +| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | +| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | +| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | +| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | +| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | +| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | +| metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | +| customizeData | Custom information about the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | + +Table 28 Internal structure of the customizeData attribute + +| Attribute| Description | Data Type| Default | +| -------- | --------------------------------------------------- | -------- | -------------------- | +| name | Name in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Format of the current custom data. The value is the resource value of **extra**.| String | Yes (initial value: left empty)| + +Example of the forms attribute structure: + +```json +"forms": [ + { + "name": "Form_Js", + "description": "It's Js Form", + "type": "JS", + "jsComponentName": "card", + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "11:00", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "2*2", + "2*4", + "4*4" + ] + }, + { + "name": "Form_Java", + "description": "It's Java Form", + "type": "Java", + "colorMode": "auto", + "isDefault": false, + "updateEnabled": true, + "scheduledUpdateTime": "21:05", + "updateDuration": 1, + "defaultDimension": "1*2", + "supportDimensions": [ + "1*2" + ], + "landscapeLayouts": [ + "$layout:ability_form" + ], + "portraitLayouts": [ + "$layout:ability_form" + ], + "formConfigAbility": "ability://com.example.myapplication.fa/.MainAbility", + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "com.example.weather.testWidget" + } + ] + } + } +] +``` + +Table 29 Internal structure of the distroFilter attribute + +| Attribute | Description | Data Type| Default| +| ------------- | ------------------------------------------------------------ | -------- | ---------- | +| apiVersion | Supported API versions. For details, see Table 30. | Object | No | +| screenShape | Supported screen shapes. For details, see Table 31. | Object array| No | +| screenWindow | Supported window resolutions when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| No | +| screenDensity | Pixel density of the screen, in dots per inch (DPI). For details, see Table 33. | Object array| No | +| countryCode | Country code used during application distribution. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| No | + +Table 30 Internal structure of the apiVersion attribute + +| Attribute| Description | Data Type| Default | +| -------- | ------------------------------------------------------------ | -------- | -------------------- | +| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**.**include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| +| value | An integer of the existing API version, for example, 4, 5, or 6. Example: If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| + +Table 31 Internal structure of the screenShape attribute + +| Attribute| Description | Data Type| Default | +| -------- | ------------------------------------------------------------ | -------- | -------------------- | +| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**.**include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| +| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and that with a rectangular face.| Array | Yes (initial value: left empty)| + +Table 32 Internal structure of the screenWindow attribute + +| Attribute| Description | Data Type| Default | +| -------- | ------------------------------------------------------------ | -------- | -------------------- | +| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**.**include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| +| value | Width and height of the screen. The value of a single string is in the format of Width x Height in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| + +Table 33 Internal structure of the screenDensity attribute + +| Attribute| Description | Data Type| Default | +| -------- | ------------------------------------------------------------ | -------- | -------------------- | +| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**.**include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| +| value | Available values are as follows:
**sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].
**xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].
**xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].
**xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640].| Array | Yes (initial value: left empty)| + +Table 34 Internal structure of the countryCode attribute + +| Attribute| Description | Data Type | Default | +| -------- | ------------------------------------------------------------ | ---------- | -------------------- | +| policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**.**include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| +| value | Country code of the area to which the application is to be distributed. The value is a string array, of which each substring indicates a country or region. The substring consists of two uppercase letters.| String array| Yes (initial value: left empty)| + +Example of the distroFilter attribute structure: + +```json +"distroFilter": { + "apiVersion": { + "policy": "include", + "value": [4,5] + }, + "screenShape": { + "policy": "include", + "value": ["circle","rect"] + }, + "screenWindow": { + "policy": "include", + "value": ["454*454","466*466"] + }, + "screenDensity":{ + "policy": "exclude", + "value": ["ldpi","xldpi"] + }, + "countryCode": { + "policy":"include", + "value":["CN", "HK"] + } +} +``` + +Table 35 Internal structure of the commonEvents attribute -- The value of **package** must be unique for the applications with the same **bundleName**. -- Only one ability can be declared in the **abilities** field. -- The **name** field under **abilities** must be unique for the applications with the same **bundleName**. +| Attribute | Description | Data Type | Default | +| ---------- | ------------------------------------------------------------ | ---------- | ------------------ | +| name | Name of a static broadcast. | String | No | +| permission | Permission that needs to be applied for to implement the static common event. | String array| Yes (initial value: left empty)| +| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| +| type | Type array of the current static common event. | String array| Yes (initial value: left empty)| +| events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No | +Example of the commonEvents attribute structure: + +```json +"commonEvents": [ + { + "name":"MainAbility", + "permission": "string", + "data":[ + "string", + "string" + ], + "events": [ + "string", + "string" + ] + } +] +``` diff --git a/en/application-dev/quick-start/start-overview.md b/en/application-dev/quick-start/start-overview.md index 4d3323b64842149c07d51dc14745bae8d3f969c9..9247564043b0f412361075d79f2082fd3e0f61b4 100644 --- a/en/application-dev/quick-start/start-overview.md +++ b/en/application-dev/quick-start/start-overview.md @@ -23,7 +23,11 @@ ArkUI comes with two development paradigms: JavaScript-based web-like developmen | Web-like development paradigm | JavaScript | Data-driven | Applications and service widgets with simple UIs | Frontend web developers | | Declarative development paradigm | Extended TypeScript (eTS) | Data-driven | Applications involving technological sophistication and teamwork | Mobile application and system application developers | -For DevEco Studio V2.2 Beta1 and later versions, both the traditional coding mode and the low-code mode are supported when the JS language is used for development. On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features complying with JS Development Specifications. +For DevEco Studio V2.2 Beta1 and later versions, both the traditional coding mode and the low-code mode are supported when the JS language is used for development. + +For eTS language development, DevEco Studio V3.0 Beta3 and later versions support low-code development in addition to the traditional code development mode. + +On the OpenHarmony low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. ### Ability @@ -43,4 +47,4 @@ This document provides a Page ability instance with two pages. For more informat 2. Install DevEco Studio and configure the development environment. For details, see [Configuring the OpenHarmony SDK](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443). -When you are done, follow the instructions in [Getting Started with eTS](start-with-ets.md),[Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md), and [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md). +When you are done, follow the instructions in [Getting Started with eTS in the Traditional Coding Approach](start-with-ets.md),[Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md), [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md), and [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md). diff --git a/en/application-dev/quick-start/start-with-ets-low-code.md b/en/application-dev/quick-start/start-with-ets-low-code.md new file mode 100644 index 0000000000000000000000000000000000000000..0c3e851c3912b2f768dceb2622c461ab919d946a --- /dev/null +++ b/en/application-dev/quick-start/start-with-ets-low-code.md @@ -0,0 +1,189 @@ +# Getting Started with eTS in the Low-Code Approach + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> This feature is supported in DevEco Studio V3.0 Beta3 and later versions. +> +> The component lineup that supports low-code development in eTS is now at its preliminary stage and will be expanding in coming versions. +> +> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development. + + +On the OpenHarmony low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. + + +You can develop applications or services in the low-code approach using either of the following methods: + + +- Create a project that supports low-code development. This method is used as an example in this topic. + +- In an existing project, create a .visual file for development. + + +## Creating a Project That Supports Low-Code Development + +1. Open DevEco Studio, choose **File** > **New** > **Create Project**, select **Empty Ability**, and click **Next**. + ![en-us_image_0000001233528152](figures/en-us_image_0000001233528152.png) + +2. Go to the project configuration page, select **Enable Super Visual**, set **UI Syntax** to **eTS**, and retain the default values for other parameters. + ![en-us_image_0000001277728569](figures/en-us_image_0000001277728569.png) + +3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. + + +## Low-code Project Files + +After the project synchronization is complete, a low-code directory structure is automatically generated in the project, as shown below. + +![en-us_image_0000001277809333](figures/en-us_image_0000001277809333.png) + +- **entry > src > main > ets > MainAbility > pages > index.ets**: defines logical relationships, such as data and events, used on low-code pages. For details, see [About Syntactic Sugar](../ui/ts-syntactic-sugar.md). If multiple low-code development pages are created, a page folder and the corresponding **.ets** file will be created for each of these pages. + +- **entry > src > main > supervisual > MainAbility > pages > index.visual**: stores the data model of the low-code development page. You can double-click the file to open the low-code development page. If multiple low-code development pages are created, a page folder and the corresponding **.visual** file will be created for each of these pages. + + +## Building the First Page + +After the project synchronization is complete, the default first page contains the **Column** and **Text** (**Hello World**) components. To better understand low-code development, we'll delete these template components from the canvas and set the page from scratch. + +Add **Column**, **Text**, and **Button** components to the first page. A column is a container component whose child components are vertically arranged. For details, see [Column](../reference/arkui-ts/ts-container-column.md). + +1. Delete the existing template components from the canvas. + Open the index.visual file, right-click the existing template components on the canvas, and choose **Delete** from the shortcut menu to delete them. Below is an illustration of the operations. + + ![en-us_image_0000001233208980](figures/en-us_image_0000001233208980.gif) + +2. Add a **Column** component and set its styles and attributes. + Drag the **Column** component from the **UI Control** area to the canvas. In the **Attributes & Styles** area on the right, click ![en-us_image_0000001233048996](figures/en-us_image_0000001233048996.png)**General** and set **Height** to **100%** so that the component fills the entire screen. Click ![en-us_image_0000001233368860](figures/en-us_image_0000001233368860.png)**Feature** and set **AlignItems** to **center** so that the child components of the **Column** component are centered along the horizontal axis. Below is an illustration of the operations. + + ![en-us_image_0000001277488977](figures/en-us_image_0000001277488977.gif) + +3. Add a **Text** component. + Drag the **Text** component from the **UI Control** area to the canvas and then to the center area of the **Column** component. In the **Attributes & Styles** area, click ![en-us_image_0000001277608813](figures/en-us_image_0000001277608813.png)**Feature**, set **Content** of the **Text** component to **this.message** (that is, **Hello World**), set **FontSize** to **30fp**, and set **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations. + + ![en-us_image_0000001235731706](figures/en-us_image_0000001235731706.gif) + +4. Add a **Button** component. + Drag the **Button** component from the **UI Control** area to the canvas and then to a position under the **Text** component. In the **Attributes & Styles** area on the right, click ![en-us_image_0000001277728577](figures/en-us_image_0000001277728577.png)**General** and set **Height** of the **Button** component to **40vp**. Click ![en-us_image_0000001277809337](figures/en-us_image_0000001277809337.png)**Feature** and set **Label** to **Next** and **FontSize** to **25fp**. Below is an illustration of the operations. + + ![en-us_image_0000001235732402](figures/en-us_image_0000001235732402.gif) + +5. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. Below is how the first page looks in the Previewer. + ![en-us_image_0000001235892798](figures/en-us_image_0000001235892798.png) + + +## Building the Second Page + +1. Create the second page. + In the **Project** window, choose **entry** > **src** > **main** > **ets** > **MainAbility**, right-click the **pages** folder, choose **New** > **Visual**, name the page **second**, and click **Finish**. Below is the structure of the **pages** folder. + + ![en-us_image_0000001233368868](figures/en-us_image_0000001233368868.png) + +2. [Delete the existing template components from the canvas.](#delete_origin_content) + +3. [Add a **Column** component and set its styles and attributes.](#add_container) + +4. Add a **Text** component. + - In the **second.ets** file, set the message text content to **Hi there**. The sample code is as follows: + + ``` + @Entry + @Component + struct Second { + @State message: string = 'Hi there' + + /** + * In low-code mode, do not add anything to the build function, as it will be + * overwritten by the content generated by the .visual file in the build phase. + */ + build() { + + } + } + ``` + - Drag the **Text** component to the canvas and then to the center area of the **Column** component. In the **Attributes & Styles** area, click ![en-us_image_0000001277488985](figures/en-us_image_0000001277488985.png)**Feature**, set **Content** of the **Text** component to **this.message** (that is, **Hi there**), set **FontSize** to **30fp**, and set **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations. + ![en-us_image_0000001280255513](figures/en-us_image_0000001280255513.gif) + +5. Add a **Button** component. + Drag the **Button** component from the **UI Control** area to the canvas and then to a position under the **Text** component. In the **Attributes & Styles** area on the right, click ![en-us_image_0000001233528160](figures/en-us_image_0000001233528160.png)**General** and set **Height** of the **Button** component to **40vp**. Click ![en-us_image_0000001277728597](figures/en-us_image_0000001277728597.png)**Feature** and set **Value** to **Back** and **FontSize** to **25fp**. Below is an illustration of the operations. + + ![en-us_image_0000001280383937](figures/en-us_image_0000001280383937.gif) + + +## Implementing Page Redirection + +You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below: + +1. Implement redirection from the first page to the second page. + In the files of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. This operation needs to be completed in both .ets and .visual files. + - In the **index.ets** file: + + ``` + import router from '@system.router'; + + @Entry + @Component + struct Index { + @State message: string = 'Hello World' + + /** + * In low-code mode, do not add anything to the build function, as it will be + * overwritten by the content generated by the .visual file in the build phase. + */ + onclick() { + router.push({ + uri: 'pages/second', // Specify the page to be redirected to. + }) + } + + build() { + } + } + ``` + + - In the index.visual file, select the **Button** component on the canvas. In the **Attributes & Styles** area, click ![en-us_image_0000001233209020](figures/en-us_image_0000001233209020.png)**Events** and set **OnClick** to **this.onclick**. + ![en-us_image_0000001235745716](figures/en-us_image_0000001235745716.png) + +2. Implement redirection from the second page to the first page. + In the files of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. This operation needs to be completed in both .ets and .visual files. + + - In the **second.ets** file: + + ``` + import router from '@system.router'; + + @Entry + @Component + struct Second { + @State message: string = 'Hi there' + + /** + * In low-code mode, do not add anything to the build function, as it will be + * overwritten by the content generated by the .visual file in the build phase. + */ + back() { + router.back() + } + + build() { + + } + } + ``` + - In the second.visual file, select the **Button** component on the canvas. In the **Attributes & Styles** area, click ![en-us_image_0000001233368900](figures/en-us_image_0000001233368900.png)**Events** and set **OnClick** to **this.back**. + ![en-us_image_0000001280385809](figures/en-us_image_0000001280385809.png) + +3. Open the **index.visual** or **index.ets** file and click ![en-us_image_0000001277608849](figures/en-us_image_0000001277608849.png) in the Previewer to refresh the file. The figure below shows the effect. + ![en-us_image_0000001233528192](figures/en-us_image_0000001233528192.png) + + +## Running the Application on a Real Device + +1. Connect the development board running the OpenHarmony standard system to the computer. + +2. Choose **File** > **Project Structure** > **Project** > **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below. + ![en-us_image_0000001277728613](figures/en-us_image_0000001277728613.png) + +3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001277809373](figures/en-us_image_0000001277809373.png). The display effect is shown in the figure below. + ![en-us_image_0000001233209024](figures/en-us_image_0000001233209024.png) + +Congratulations! You have finished developing your OpenHarmony application in eTS in the low-code approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md). diff --git a/en/application-dev/quick-start/start-with-ets.md b/en/application-dev/quick-start/start-with-ets.md index 81510bef091d24e28c39acca75ab2f701151eaab..792fb818ba2ca78cd3fa9e6acb111b89bf18a90c 100644 --- a/en/application-dev/quick-start/start-with-ets.md +++ b/en/application-dev/quick-start/start-with-ets.md @@ -1,4 +1,4 @@ -# Getting Started with eTS +# Getting Started with eTS in the Traditional Coding Approach > ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** > To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later. @@ -247,4 +247,4 @@ You can implement page redirection through the page router, which finds the targ 3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001262206247](figures/en-us_image_0000001262206247.png). The display effect is shown in the figure below. ![en-us_image_0000001217526428](figures/en-us_image_0000001217526428.png) -Congratulations! You have finished developing your OpenHarmony application in eTS. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md) +Congratulations! You have finished developing your OpenHarmony application in eTS in the traditional coding approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md) diff --git a/en/application-dev/quick-start/start-with-js-low-code.md b/en/application-dev/quick-start/start-with-js-low-code.md index 572e49f734ae2f32a98695576229a0a058d468b0..b46990dc8ee7b7e8a08da0745d5b62e90bf3fe59 100644 --- a/en/application-dev/quick-start/start-with-js-low-code.md +++ b/en/application-dev/quick-start/start-with-js-low-code.md @@ -6,7 +6,7 @@ > For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development. -On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features complying with JS Development Specifications. +On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features. You can develop applications or services in the low-code approach using either of the following methods: diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md new file mode 100644 index 0000000000000000000000000000000000000000..de4c08ef0228af6b42328584fa8cd7bd5a0c106a --- /dev/null +++ b/en/application-dev/quick-start/syscap.md @@ -0,0 +1,178 @@ +# SysCap Usage Guidelines + +## Overview + +### System Capabilities and APIs + +SysCap is short for System Capability. It refers to each independent feature in the operating system, such as Bluetooth, Wi-Fi, NFC, and camera. Each system capability corresponds to multiple APIs. These APIs are bound together and their availability depends on the support on the target device. They can also be provided together with the IDE for association. + +![image-20220326064841782](figures/image-20220326064841782.png) + + + +### Supported Capability Set, Association Capability Set, and Required Capability Set + +The supported capability set, association capability set, and required capability set are collections of system capabilities. +The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. +The association capability set covers the system capabilities of APIs that can be associated by the IDE during application development. + +![image-20220326064913834](figures/image-20220326064913834.png) + + + +### Devices and Supported Capability Sets + +Each device provides a capability set according to its hardware capability. +The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors. + +![image-20220326064955505](figures/image-20220326064955505.png) + + + +### Mapping Between Devices and SDK Capabilities + +The SDK provides full APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input). + +![image-20220326065043006](figures/image-20220326065043006.png) + + + +## How to Develop + +### Importing the PCID + +DevEco Studio allows PCID imports for projects. After the imported PCID file is decoded, the output SysCap is written into the **syscap.json** file. + +Right-click the project directory and choose **Import Product Compatibility ID** from the shortcut menu to upload the PCID file and import it to the **syscap.json** file. + +![20220329-103626](figures/20220329-103626.gif) + + + +### Configuring the Association Capability Set and Required Capability Set + +The IDE automatically configures the association capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary. +For the association capability set, you can use more APIs in the IDE by adding more system capabilities. Note that these APIs may not be supported on the device. Therefore, you need to check whether these APIs are supported before using them. +Exercise caution when modifying the required capability set. Incorrect modifications may cause the application to unable to be distributed to the target device. + +``` +/* syscap.json */ +{ + devices: { + general: [ /* Each general device corresponds to a SysCap capability set. Multiple general devices can be configured.*/ + "car, + ... + ], + custom: [ /* Vendor-defined device*/ + { + "Custom device": [ + "SystemCapability.Communication.SoftBus.Core", + ... + ] + }, + ... + ] + }, + development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the association capability set.*/ + addedSysCaps: [ + "SystemCapability.Location.Location.Lite", + ... + ] + }, + production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices.*/ + addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set. + removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device. + } +} +``` + + + +### Single-Device Application Development + +By default, the association capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set. + +![image-20220326065124911](figures/image-20220326065124911.png) + + + +### Cross-Device Application Development + +By default, the association capability set of the application is the union of multiple devices' supported capability sets. The capability sets must be the intersection. + +![image-20220326065201867](figures/image-20220326065201867.png) + + + +### Checking Whether an API Is Available + +To check whether a project supports a specific SysCap, you can use **canIUse**. + +``` +if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) { + console.log("The application supports SystemCapability.ArkUI.ArkUI.Full."); +} else { + Console.log("The application does not support SystemCapability.ArkUI.ArkUI.Full".); +} +``` + +You can import a module. If the current device does not support the module, the import result is **undefined**. When using an API, you need to check whether the API is available. + +``` +import geolocation from '@ohos.geolocation'; + +if (geolocation) { + geolocation.getCurrentLocation((location) => { + console.log(location.latitude, location.longitude); + }); +} else { + Console.log('The device does not support location information.'); +} +``` + + + +### Checking the Differences Between Devices with the Same Capability + +The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. + +``` +import userAuth from '@ohos.userIAM.userAuth'; + +const authenticator = userAuth.getAuthenticator(); +const result = authenticator.checkAbility('FACE_ONLY', 'S1'); + +if (result == authenticator.CheckAvailabilityResult.AUTH_NOT_SUPPORT) { + Console.log('The device does not support facial recognition.'); +} +// If an unsupported API is forcibly called, an error message is returned, but no syntax error occurs. +authenticator.execute('FACE_ONLY', 'S1', (err, result) => { + if (err) { + console.log(err.message); + return; + } +}) +``` + + +### How Are the SysCap Differences Between Devices Generated + +The SysCap of devices varies according to the component combination assembled by the product solution vendor. The following figure shows the overall process. + +![image-20220326072448840](figures/image-20220326072448840.png) + +1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps. + +2. In a normalized released SDK, the mapping exists between APIs and SysCap. + +3. Product solution vendors can assemble components based on hardware capabilities and product requirements. + +4. The components configured for a product can be OpenHarmony components or private components developed by a third party. Because there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled. + +5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed on the SysCap differences of devices. + +6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications in the system to check whether a SysCap set is available. + +7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application is successfully installed. + +8. When an application is running, the **canIUse** API can be used to query the SysCap of a device to ensure compatibility on different devices. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 0887ba201b14be493ae22929539fa98aef908bc2..092d3f2373a88aa2789e14d1e81930d6e7beb386 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,122 +1,223 @@ # APIs - Ability Framework - - [FeatureAbility Module](js-apis-featureAbility.md) - - [ParticleAbility Module](js-apis-particleAbility.md) - - [DataAbilityHelper Module](js-apis-dataAbilityHelper.md) - - [DataUriUtils Module](js-apis-DataUriUtils.md) - - [Bundle Module](js-apis-Bundle.md) - - [Context Module](js-apis-Context.md) -- Event Notification - - [CommonEvent Module](js-apis-commonEvent.md) - - [Notification Module](js-apis-notification.md) - - [Reminder Agent](js-apis-reminderAgent.md) -- Resource Management - - [Resource Manager](js-apis-resource-manager.md) - - [Internationalization \(intl\) ](js-apis-intl.md) - - [Internationalization \(i18n\) ](js-apis-i18n.md) + + - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) + - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) + - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) + - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) + - [@ohos.application.appManager](js-apis-appmanager.md) + - [@ohos.application.Configuration](js-apis-configuration.md) + - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) + - [@ohos.ability.featureAbility](js-apis-featureAbility.md) + - [@ohos.application.formBindingData](js-apis-formbindingdata.md) + - [@ohos.application.formError](js-apis-formerror.md) + - [@ohos.application.formHost](js-apis-formhost.md) + - [@ohos.application.formInfo](js-apis-formInfo.md) + - [@ohos.application.missionManager](js-apis-missionManager.md) + - [@ohos.application.formProvider](js-apis-formprovider.md) + - [@ohos.ability.particleAbility](js-apis-particleAbility.md) + - [@ohos.application.Want](js-apis-application-Want.md) + - [@ohos.wantAgent](js-apis-wantAgent.md) + - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) + - app/[context](js-apis-Context.md) + - application/[abilityDelegator](js-apis-application-abilityDelegator.md) + - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) + - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) + - application/[ExtensionContext](js-apis-extension-context.md) + - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) + - application/[FormExtensionContext](js-apis-formextensioncontext.md) + - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) + - application/[ProcessRunningInfo](js-apis-processrunninginfo.md) + - application/[ServiceExtensionContext](js-apis-service-extension-context.md) + - application/[shellCmdResult](js-apis-application-shellCmdResult.md) + +- Common Event and Notification + + - [@ohos.commonEvent](js-apis-commonEvent.md) + - [@ohos.events.emitter](js-apis-emitter.md) + - [@ohos.notification](js-apis-notification.md) + - [@ohos.reminderAgent](js-apis-reminderAgent.md) +- Bundle Management + + - [@ohos.bundle](js-apis-Bundle.md) + - [@ohos.bundleState ](js-apis-deviceUsageStatistics.md) + - [@ohos.zlib](js-apis-zlib.md) + +- UI Page + + - [@ohos.animator](js-apis-animator.md) + - [@ohos.mediaquery](js-apis-mediaquery.md) + - [@ohos.prompt](js-apis-prompt.md) + - [@ohos.router](js-apis-router.md) + +- Graphics + + - [@ohos.display ](js-apis-display.md) + - [@ohos.screenshot](js-apis-screenshot.md) + - [@ohos.window](js-apis-window.md) + - [webgl](js-apis-webgl.md) + - [webgl2](js-apis-webgl2.md) + - Media - - [Audio Management](js-apis-audio.md) - - [Media](js-apis-media.md) - - [Image Processing](js-apis-image.md) - - [Camera](js-apis-camera.md) + + - [@ohos.multimedia.audio](js-apis-audio.md) + - [@ohos.multimedia.image](js-apis-image.md) + - [@ohos.multimedia.media](js-apis-media.md) + - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) + +- Resource Management + - [@ohos.i18n](js-apis-i18n.md) + - [@ohos.intl](js-apis-intl.md) + - [@ohos.resourceManager](js-apis-resource-manager.md) + +- Resource Scheduling + + - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) + +- Custom Management + + - [@ohos.configPolicy](js-apis-config-policy.md) + - Security - - [User Authentication](js-apis-useriam-userauth.md) - - [Access Control](js-apis-abilityAccessCtrl.md) + + - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) + - [@ohos.security.huks ](js-apis-huks.md) + - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) + - [@system.cipher](js-apis-system-cipher.md) + - Data Management - - [Lightweight Storage](js-apis-data-storage.md) - - [Distributed Data Management](js-apis-distributed-data.md) - - [Relational Database](js-apis-data-rdb.md) - - [Result Set](js-apis-data-resultset.md) - - [DataAbilityPredicates](js-apis-data-ability.md) - - [Settings](js-apis-settings.md) + + - [@ohos.data.dataAbility ](js-apis-data-ability.md) + - [@ohos.data.distributedData](js-apis-distributed-data.md) + - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) + - [@ohos.data.rdb](js-apis-data-rdb.md) + - [@ohos.settings](js-apis-settings.md) + - data/rdb/[resultSet](js-apis-data-resultset.md) + - File Management - - [File Management](js-apis-fileio.md) - - [Statfs](js-apis-statfs.md) - - [Environment](js-apis-environment.md) - - [Public File Access and Management](js-apis-filemanager.md) - - [App Storage Statistics](js-apis-storage-statistics.md) -- Account Management - - [OS Account Management](js-apis-osAccount.md) - - [Distributed Account Management](js-apis-distributed-account.md) - - [App Account Management](js-apis-appAccount.md) + + - [@ohos.environment](js-apis-environment.md) + - [@ohos.fileio](js-apis-fileio.md) + - [@ohos.fileManager](js-apis-filemanager.md) + - [@ohos.statfs](js-apis-statfs.md) + - [@ohos.storageStatistics](js-apis-storage-statistics.md) + - Telephony Service - - [Call](js-apis-call.md) - - [SMS](js-apis-sms.md) - - [SIM Management](js-apis-sim.md) - - [Radio](js-apis-radio.md) - - [Observer](js-apis-observer.md) - - [Cellular Data](js-apis-telephony-data.md) + + - [@ohos.contact](js-apis-contact.md) + - [@ohos.telephony.call](js-apis-call.md) + - [@ohos.telephony.observer](js-apis-observer.md) + - [@ohos.telephony.radio](js-apis-radio.md) + - [@ohos.telephony.sim](js-apis-sim.md) + - [@ohos.telephony.sms](js-apis-sms.md) + - [@ohos.telephony.data](js-apis-telephony-data.md) + - Network Management - - [Network Connection Management](js-apis-net-connection.md) - - [Socket Connection](js-apis-socket.md) - - [WebSocket Connection](js-apis-webSocket.md) - - [Data Request](js-apis-http.md) -- Network and Connectivity - - [WLAN](js-apis-wifi.md) - - [Bluetooth](js-apis-bluetooth.md) - - [RPC](js-apis-rpc.md) - - [Upload and Download](js-apis-request.md) -- Device Management - - [Sensor](js-apis-sensor.md) - - [Vibrator](js-apis-vibrator.md) - - [Brightness](js-apis-brightness.md) - - [Battery Info](js-apis-battery-info.md) - - [Power Management](js-apis-power.md) - - [Thermal Management](js-apis-thermal.md) - - [Running Lock](js-apis-runninglock.md) - - [Device Info](js-apis-device-info.md) - - [systemParameter](js-apis-system-parameter.md) - - [Device Management](js-apis-device-manager.md) - - [Window](js-apis-window.md) - - [Display](js-apis-display.md) - - [Update](js-apis-update.md) - - [USB](js-apis-usb.md) - - [Location](js-apis-geolocation.md) + - [@ohos.net.connection](js-apis-net-connection.md) + - [@ohos.net.http](js-apis-http.md) + - [@ohos.request](js-apis-request.md) + - [@ohos.net.socket](js-apis-socket.md) + - [@ohos.net.webSocket](js-apis-webSocket.md) + +- Connectivity + + - [@ohos.bluetooth](js-apis-bluetooth.md) + - [@ohos.connectedTag](js-apis-connectedTag.md) + - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.wifi](js-apis-wifi.md) + - [@ohos.wifiext](js-apis-wifiext.md) + - Basic Features - - [Application Context](js-apis-basic-features-app-context.md) - - [Console Logs](js-apis-basic-features-logs.md) - - [Page Routing](js-apis-basic-features-routes.md) - - [Timer](js-apis-basic-features-timer.md) - - [Screen Lock Management](js-apis-screen-lock.md) - - [Setting the System Time](js-apis-system-time.md) - - [Wallpaper](js-apis-wallpaper.md) - - [Pasteboard](js-apis-pasteboard.md) - - [Animation](js-apis-basic-features-animator.md) - - [WebGL](js-apis-webgl.md) - - [WebGL2](js-apis-webgl2.md) - - [Screenshot](js-apis-screenshot.md) - - [Accessibility](js-apis-accessibility.md) -- DFX - - [HiAppEvent](js-apis-hiappevent.md) - - [Performance Tracing](js-apis-hitracemeter.md) - - [Fault Logger](js-apis-faultLogger.md) - - [Distributed Call Chain Tracing](js-apis-hitracechain.md) - - [HiLog](js-apis-hilog.md) - - [HiChecker](js-apis-hichecker.md) - - [HiDebug](js-apis-hidebug.md) + + - [@ohos.accessibility](js-apis-accessibility.md) + - [@ohos.faultLogger](js-apis-faultLogger.md) + - [@ohos.hiAppEvent](js-apis-hiappevent.md) + - [@ohos.hichecker](js-apis-hichecker.md) + - [@ohos.hidebug](js-apis-hidebug.md) + - [@ohos.hilog](js-apis-hilog.md) + - [@ohos.hiTraceChain](js-apis-hitracechain.md) + - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) + - [@ohos.inputMethod](js-apis-inputmethod.md) + - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.pasteboard](js-apis-pasteboard.md) + - [@ohos.screenLock](js-apis-screen-lock.md) + - [@ohos.systemTime](js-apis-system-time.md) + - [@ohos.wallpaper](js-apis-wallpaper.md) + - [Timer](js-apis-timer.md) + +- Device Management + + - [@ohos.batteryInfo ](js-apis-battery-info.md) + - [@ohos.brightness](js-apis-brightness.md) + - [@ohos.deviceInfo](js-apis-device-info.md) + - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) + - [@ohos.geolocation](js-apis-geolocation.md) + - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) + - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) + - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) + - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) + - [@ohos.power](js-apis-power.md) + - [@ohos.runningLock](js-apis-runninglock.md) + - [@ohos.sensor](js-apis-sensor.md) + - [@ohos.systemParameter](js-apis-system-parameter.md) + - [@ohos.thermal](js-apis-thermal.md) + - [@ohos.update](js-apis-update.md) + - [@ohos.usb](js-apis-usb.md) + - [@ohos.vibrator](js-apis-vibrator.md) + +- Account Management + + - [@ohos.account.appAccount](js-apis-appAccount.md) + - [@ohos.account.distributedAccount](js-apis-distributed-account.md) + - [@ohos.account.osAccount](js-apis-osAccount.md) + - Language Base Class Library - - [Obtaining Process Information](js-apis-process.md) - - [URL String Parsing](js-apis-url.md) - - [URI String Parsing](js-apis-uri.md) - - [Util](js-apis-util.md) - - [XML Parsing and Generation](js-apis-xml.md) - - [XML-to-JavaScript Conversion](js-apis-convertxml.md) - - [Worker Startup](js-apis-worker.md) - - [Linear Container ArrayList](js-apis-arraylist.md) - - [Linear Container Deque](js-apis-deque.md) - - [Linear Container List](js-apis-list.md) - - [Linear Container LinkedList](js-apis-linkedlist.md) - - [Linear Container Queue](js-apis-queue.md) - - [Linear Container Stack](js-apis-stack.md) - - [Linear Container Vector](js-apis-vector.md) - - [Nonlinear Container HashSet](js-apis-hashset.md) - - [Nonlinear Container HashMap](js-apis-hashmap.md) - - [Nonlinear Container PlainArray](js-apis-plainarray.md) - - [Nonlinear Container TreeMap](js-apis-treemap.md) - - [Nonlinear Container TreeSet](js-apis-treeset.md) - - [Nonlinear Container LightWeightMap](js-apis-lightweightmap.md) - - [Nonlinear Container LightWeightSet](js-apis-lightweightset.md) -- Custom Management - - [Configuration Policy](js-apis-config-policy.md) + - [@ohos.convertxml](js-apis-convertxml.md) + - [@ohos.process](js-apis-process.md) + - [@ohos.uri](js-apis-uri.md) + - [@ohos.url](js-apis-url.md) + - [@ohos.util](js-apis-util.md) + - [@ohos.util.ArrayList](js-apis-arraylist.md) + - [@ohos.util.Deque](js-apis-deque.md) + - [@ohos.util.HashMap](js-apis-hashmap.md) + - [@ohos.util.HashSet](js-apis-hashset.md) + - [@ohos.util.LightWeightMap](js-apis-lightweightmap.md) + - [@ohos.util.LightWeightSet](js-apis-lightweightset.md) + - [@ohos.util.LinkedList](js-apis-linkedlist.md) + - [@ohos.util.List](js-apis-list.md) + - [@ohos.util.PlainArray](js-apis-plainarray.md) + - [@ohos.util.Queue](js-apis-queue.md) + - [@ohos.util.Stack](js-apis-stack.md) + - [@ohos.util.TreeMap](js-apis-treemap.md) + - [@ohos.util.TreeSet](js-apis-treeset.md) + - [@ohos.util.Vector](js-apis-vector.md) + - [@ohos.worker](js-apis-worker.md) + - [@ohos.xml](js-apis-xml.md) + +- Test + - [@ohos.application.testRunner](js-apis-testRunner.md) + - [@ohos.uitest](js-apis-uitest.md) + +- APIs No Longer Maintained + + - [@ohos.bytrace](js-apis-bytrace.md) + - [@system.app](js-apis-system-app.md) + - [@system.battery](js-apis-system-battery.md) + - [@system.brightness](js-apis-system-brightness.md) + - [@system.configuration](js-apis-system-configuration.md) + - [@system.device](js-apis-system-device.md) + - [@system.fetch](js-apis-system-fetch.md) + - [@system.file](js-apis-system-file.md) + - [@system.geolocation](js-apis-system-location.md) + - [@system.mediaquery](js-apis-system-mediaquery.md) + - [@system.network](js-apis-system-network.md) + - [@system.package](js-apis-system-package.md) + - [@system.prompt](js-apis-system-prompt.md) + - [@system.request](js-apis-system-request.md) + - [@system.router](js-apis-system-router.md) + - [@system.sensor](js-apis-system-sensor.md) + - [@system.storage](js-apis-system-storage.md) + - [@system.vibrator](js-apis-system-vibrate.md) + - [console](js-apis-logs.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png b/en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png new file mode 100644 index 0000000000000000000000000000000000000000..6eb89772d315b440636e8ceeda928e5db6b34e40 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001200913929.png differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 64459cb19ec7ffbe0ce7d66b1f4ccfa30a4c3ef5..e948637d03702446f46d18aeb4f5b4a1a8553dd8 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -15,17 +15,17 @@ SystemCapability.BundleManager.BundleFramework ## Required Permissions -| Required Permissions| Permission Level| Description| -|-------| --------- | ---- | -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about the current application.| +| Required Permissions | Permission Level | Description | +| ---------------------------------------- | ------------ | --------- | +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about the current application.| | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all applications.| -| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications.| +| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications. | ## bundle.getApplicationInfo getApplicationInfo(bundleName: string, bundleFlags: number, userId?: number): Promise\ -Obtains the application information based on a given bundle name. This method uses a promise to return the result. +Obtains the application information based on a given bundle name. This API uses a promise to return the result. **Required permissions** @@ -37,16 +37,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description| -| ----------- | -------- | +| Type | Description | +| ------------------------- | ------------------ | | Promise\ | Promise used to return the application information.| **Example** @@ -69,7 +69,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId) getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void -Obtains the application information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -81,12 +81,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\ | Yes | Callback used to return the application information. | **Example** @@ -108,7 +108,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, userId, (err, data) => { getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void -Obtains the application information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -120,11 +120,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of the application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\ | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | ------------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the application information. | **Example** @@ -145,7 +145,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of a specified user in the system. This method uses a promise to return the result. +Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result. **Required permissions** @@ -157,15 +157,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------- | ---- | ----------------------------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ---------- | ---------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| --------------------------- | ----------------------------------- | +| Type | Description | +| --------------------------- | -------------------------- | | Promise> | Promise used to return the information of all available bundles.| **Example** @@ -187,7 +187,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This method uses an asynchronous callback to return the result. +Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. **Required permissions** @@ -199,10 +199,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -222,7 +222,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This method uses an asynchronous callback to return the result. +Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. **Required permissions** @@ -234,11 +234,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------- | ---- | --------------------------------------- | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -260,7 +260,7 @@ bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Promise\ -Obtains the bundle information based on a given bundle name. This method uses a promise to return the result. +Obtains the bundle information based on a given bundle name. This API uses a promise to return the result. **Required permissions** @@ -272,16 +272,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | BundleOptions | No | Includes **userId**. | +| Name | Type | Mandatory | Description | +| ----------- | ------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| options | BundleOptions | No | Includes **userId**. | **Return value** -| Type | Description | -| -------------------- | ------------------------------------------ | +| Type | Description | +| -------------------- | ---------------------------- | | Promise\ | Promise used to return the bundle information.| **Example** @@ -306,7 +306,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options) getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void -Obtains the bundle information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -318,11 +318,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | **Example** @@ -343,7 +343,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, callback: AsyncCallback\): void -Obtains the bundle information based on a given bundle name. This method uses an asynchronous callback to return the result. +Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -355,12 +355,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | BundleOptions | Yes | Includes **userId**. | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------- | ---- | --------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| options | BundleOptions | Yes | Includes **userId**. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle information. | **Example** @@ -384,7 +384,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { getAllApplicationInfo(bundleFlags: number, userId?: number): Promise> -Obtains the information about all applications of the specified user. This method uses a promise to return the result. +Obtains the information about all applications of the specified user. This API uses a promise to return the result. **Required permissions** @@ -396,15 +396,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | +| Type | Description | +| -------------------------------- | ------------------------------- | | Promise> | Promise used to return the application information.| **Example** @@ -426,7 +426,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications of the specified user. This method uses an asynchronous callback to return the result. +Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -438,11 +438,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------------------- | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------------------- | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -461,9 +461,9 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { ## bundle.getAllApplicationInfo -function getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; +getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; -Obtains the information about all applications. This method uses an asynchronous callback to return the result. +Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -475,10 +475,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | -------------------------------------- | ---- | ------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory | Description | +| ----------- | -------------------------------------- | ---- | --------------------------------------- | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -497,7 +497,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { getAbilityInfo(bundleName: string, abilityName: string): Promise\ -Obtains the ability information based on a given want. This method uses a promise to return the result. +Obtains the ability information based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -509,15 +509,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| --------------------- | --------------------- | | Promise\ | Promise used to return the ability information.| **Example** @@ -535,10 +535,9 @@ bundle.getAbilityInfo(bundleName, abilityName) ## bundle.getAbilityInfo -getAbilityInfo(bundleName: string, abilityName: string): callback : -AsyncCallback\: void +getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -550,11 +549,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the ability information.| +| Name | Type | Mandatory | Description | +| ----------- | ------------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| +| callback | AsyncCallback\ | Yes | Callback used to return the ability information.| **Example** @@ -574,7 +573,7 @@ bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { getAbilityLabel(bundleName: string, abilityName: string): Promise\ -Obtains the application name based on a given want. This method uses a promise to return the result. +Obtains the application name based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -586,15 +585,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| ---------------- | ------------------ | | Promise\ | Promise used to return the application name.| **Example** @@ -614,7 +613,7 @@ bundle.getAbilityLabel(bundleName, abilityName) getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallback\): void -Obtains the application name based on a given want. This method uses an asynchronous callback to return the result. +Obtains the application name based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -626,11 +625,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| abilityName | string | Yes | Name of the ability.| -| callback | AsyncCallback\ | Yes| Callback used to return the application name.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------- | ---- | ---------------- | +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| +| callback | AsyncCallback\ | Yes | Callback used to return the application name. | **Example** @@ -650,7 +649,7 @@ bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { isAbilityEnabled(info: AbilityInfo): Promise\ -Checks whether an ability is enabled based on a given want. This method uses a promise to return the result. +Checks whether an ability is enabled based on a given want. This API uses a promise to return the result. **Required permissions** @@ -662,14 +661,14 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------ | -| info | AbilityInfo | Yes | Ability information. | +| Name | Type | Mandatory | Description | +| ---- | ----------- | ---- | ------------ | +| info | AbilityInfo | Yes | Ability information.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------| +| Type | Description | +| ----------------- | ------------------------- | | Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -691,7 +690,7 @@ bundle.isAbilityEnabled(Info) isAbilityEnabled(info : AbilityInfo, callback : AsyncCallback\): void -Checks whether an ability is enabled based on a given want. This method uses an asynchronous callback to return the result. +Checks whether an ability is enabled based on a given want. This API uses an asynchronous callback to return the result. **Required permissions** @@ -703,10 +702,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| info | AbilityInfo | Yes | Ability information. | -| callback | AsyncCallback\ | Yes| Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | --------------- | +| info | AbilityInfo | Yes | Ability information. | +| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -728,7 +727,7 @@ bundle.isAbilityEnabled(Info, (err, data) => { isApplicationEnabled(bundleName: string): Promise\ -Checks whether an application is enabled based on a given want. This method uses a promise to return the result. +Checks whether an application is enabled based on a given want. This API uses a promise to return the result. **Required permissions** @@ -740,15 +739,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | string | Yes | Bundle name of the application.| **Return value** -| Type | Description | -| ---------------------------- | ------------------------| -| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Type | Description | +| ----------------- | ------------------------- | +| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -766,7 +765,7 @@ bundle.isApplicationEnabled(bundleName) isApplicationEnabled(bundleName: string, callback : AsyncCallback\): void -Checks whether an application is enabled based on a given want. This method uses an asynchronous callback to return the result. +Checks whether an application is enabled based on a given want. This API uses an asynchronous callback to return the result. **Required permissions** @@ -778,15 +777,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | --------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of the application. | -| callback | AsyncCallback\ | Yes| Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | --------------- | +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js -let bundleName : "com.example.myapplication"; +let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -800,7 +799,7 @@ bundle.isApplicationEnabled(bundleName, (err, data) => { queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> -Obtains the ability information based on a given want. This method uses a promise to return the result. +Obtains the ability information based on a given want. This API uses a promise to return the result. **Required permissions** @@ -812,16 +811,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** -| Type | Description | -| ---------------------------- | ---------------------------- | +| Type | Description | +| ---------------------------- | --------------------- | | Promise\>| Promise used to return the ability information.| **Example** @@ -847,7 +846,7 @@ bundle.queryAbilityByWant(want, bundleFlags, userId) queryAbilityByWant(want: Want, bundleFlags: number, userId: number, callback: AsyncCallback\>): void -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. **System capability** @@ -855,12 +854,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------- | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -882,9 +881,9 @@ bundle.queryAbilityByWant(want, bundleFlags, userId, (err, data) => { ## bundle.queryAbilityByWant -queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void +queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback>): void; -Obtains the ability information based on a given want. This method uses an asynchronous callback to return the result. +Obtains the ability information based on a given want. This API uses an asynchronous callback to return the result. **System capability** @@ -892,11 +891,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------- | ---- | ------------------------------------- | +| want | Want | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -915,98 +914,13 @@ bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { }) ``` -## bundle.getBundleInstaller - -getBundleInstaller(): Promise\ - -Obtains the bundle installer. This method uses a promise to return the result. - -**Required permissions** - -ohos.permission.INSTALL_BUNDLE - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Return value** - -| Type | Description | -| ------------------------ | --------------------------------------------------- | -| Promise\ | Promise used to return the bundle installer.| - -**Example** - -```js -let bundleFilePaths = ['/data/test.hap']; -let param = { - userId : 100, - installFlag : 1, - isKeepData : false -}; -bundle.getBundleInstaller() -.then((installerObject) => { - console.info('Operation successful. '); - installerObject.install(bundleFilePaths, param) - .then((data) => { - console.info('Operation successful. Data:' + JSON.stringify(data)); - }).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); - }) -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - -## bundle.getBundleInstaller - -getBundleInstaller(callback: AsyncCallback\): void; - -Obtains the bundle installer. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.INSTALL_BUNDLE - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ------------------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle installer.| - -**Example** - -```js -let bundleFilePaths = ['/data/test.hap']; -let param = { - userId : 100, - installFlag : 1, - isKeepData : false -}; -bundle.getBundleInstaller((err, installerObject) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - } - console.info('Operation successful. Data:' + JSON.stringify(installerObject)); - installerObject.install(bundleFilePaths, param, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - } - console.info('Operation successful. Data:' + JSON.stringify(data)); - }) -}) -``` ## bundle.getLaunchWantForBundle getLaunchWantForBundle(bundleName: string): Promise\ -Obtains the **Want** object that launches the specified application. This method uses a promise to return the result. +Obtains the **Want** object that launches the specified application. This API uses a promise to return the result. **Required permissions** @@ -1018,13 +932,13 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name of the application.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | string | Yes | Bundle name of the application.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------------------------------ | +| Type | Description | +| -------------- | -------------------------------------- | | Promise\ | Promise used to return the **Want** object.| **Example** @@ -1043,7 +957,7 @@ bundle.getLaunchWantForBundle(bundleName) getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; -Obtains the **Want** object that launches the specified application. This method uses an asynchronous callback to return the result. +Obtains the **Want** object that launches the specified application. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1055,10 +969,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name of the application.| -| callback | AsyncCallback\ | Yes | Callback used to return the **Want** object.| +| Name | Type | Mandatory | Description | +| ---------- | -------------------- | ---- | ------------------------------ | +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the **Want** object.| **Example** @@ -1078,7 +992,7 @@ bundle.getLaunchWantForBundle(bundleName, (err, data) => { getNameForUid(uid: number): Promise\ -Obtains the bundle name based on a UID. This method uses a promise to return the result. +Obtains the bundle name based on a UID. This API uses a promise to return the result. **System capability** @@ -1086,13 +1000,13 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| uid | number | Yes | UID based on which the bundle name is to obtain.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------- | +| uid | number | Yes | UID based on which the bundle name is to obtain.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------------------------------ | +| Type | Description | +| ---------------- | --------------------------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -1109,9 +1023,9 @@ bundle.getNameForUid(uid) ## bundle.getNameForUid8+ -getNameForUid(uid: number, callback: AsyncCallback\): void; +getNameForUid(uid: number, callback: AsyncCallback\) : void -Obtains the bundle name based on a UID. This method uses an asynchronous callback to return the result. +Obtains the bundle name based on a UID. This API uses an asynchronous callback to return the result. **System capability** @@ -1119,10 +1033,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| uid | number | Yes | UID based on which the bundle name is to obtain.| -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------------- | +| uid | number | Yes | UID based on which the bundle name is to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -1140,9 +1054,9 @@ bundle.getNameForUid(uid, (err, data) => { ## bundle.getAbilityIcon8+ -getAbilityIcon(bundleName: string, abilityName: string): Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>; +getAbilityIcon(bundleName: string, abilityName: string): Promise\; -Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This method uses a promise to return the result. +Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This API uses a promise to return the result. **Required permissions** @@ -1154,15 +1068,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain.| -| abilityName | string | Yes | Ability name based on which the pixel map is to obtain.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | +| abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | **Return value** | Type | Description | | --------------------- | ------------------------------------------------------------ | -| Promise\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | Promise used to return the <[PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| +| Promise\ | Promise used to return the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| **Example** @@ -1179,9 +1093,9 @@ bundle.getAbilityIcon(bundleName, abilityName) ## bundle.getAbilityIcon8+ -getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)>): void; +getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void; -Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This method uses an asynchronous callback to return the result. +Obtains the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md) of the corresponding icon based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1193,11 +1107,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------- | -| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain.| -| abilityName | string | Yes | Ability name based on which the pixel map is to obtain.| -| callback | AsyncCallback\<[PixelMap](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-image.md)> | Yes | Callback used to return the <[PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | +| bundleName | string | Yes | Bundle name based on which the pixel map is to obtain. | +| abilityName | string | Yes | Ability name based on which the pixel map is to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the [PixelMap](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md)>.| **Example** @@ -1213,172 +1127,44 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { }) ``` - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId?: number): Promise> - -Obtains the extension ability information based on a given want. This method uses a promise to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | - -**Return value** - -| Type | Description | -| ---------------------------- | ---------------------------- | -| Promise> | Promise used to return the extension ability information.| - -**Example** - -```js -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId) -.then((data) => { - console.info('Operation successful. Data: ' + JSON.stringify(data)); -}).catch((error) => { - console.error('Operation failed. Cause: ' + JSON.stringify(error)); -}) -``` - - - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, userId: number, callback: AsyncCallback>): void - -Obtains the extension ability information based on a given want. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the extension ability information. | - -**Example** - -```js -let extensionFlags = 0; -let userId = 100; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, userId, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - -## bundle.queryExtensionAbilityInfosByWant9+ - -queryExtensionAbilityInfosByWant(want: Want, extensionFlags: number, callback: AsyncCallback>): void; - -Obtains the extension ability information based on a given want. This method uses an asynchronous callback to return the result. - -**Required permissions** - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED, ohos.permission.GET_BUNDLE_INFO - -**System capability** - -SystemCapability.BundleManager.BundleFramework - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want that contains the bundle name. | -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the extension ability information. | - -**Example** - -```js -let extensionFlags = 0; -let want = { - bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" -}; -bundle.queryExtensionAbilityInfosByWant(want, extensionFlags, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); -}) -``` - ## ElementName **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | ------ | ---- | ------------------------------------------------------------ | -| deviceId | Read-only | string | No | ID of the device that runs the ability. | -| bundleName | Read-only | string | Yes | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| -| abilityName | Read-only | string | Yes | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| -| uri | Read-only | string | No | Resource ID.| -| shortName | Read-only | string | No | Short name of the **ElementName**.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ---------------------------------------- | +| deviceId | Read-only | string | No | ID of the device that runs the ability. | +| bundleName | Read-only | string | Yes | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| +| abilityName | Read-only | string | Yes | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want**, the **Want** can directly match the specified ability.| +| uri | Read-only | string | No | Resource ID. | +| shortName | Read-only | string | No | Short name of the **ElementName**. | ## InstallErrorCode **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Default Value| Description | -| ------ | ------ | ------ | -| SUCCESS | 0 | Installation succeeded.| -| STATUS_INSTALL_FAILURE | 1 | Installation failed. (The application to be installed does not exist.)| -| STATUS_INSTALL_FAILURE_ABORTED | 2 | Installation aborted.| -| STATUS_INSTALL_FAILURE_INVALID | 3 | Invalid installation parameter.| -| STATUS_INSTALL_FAILURE_CONFLICT | 4 | Installation conflict. (The basic information about the application to upgrade is inconsistent with that of the existing application.)| -| STATUS_INSTALL_FAILURE_STORAGE | 5 | Failed to store the bundle information.| -| STATUS_INSTALL_FAILURE_INCOMPATIBLE | 6 | Installation incompatible. (A downgrade occurs or the signature information is incorrect.)| -| STATUS_UNINSTALL_FAILURE | 7 | Uninstallation failed. (The application to be uninstalled does not exist.)| -| STATUS_UNINSTALL_FAILURE_BLOCKED | 8 | Uninstallation aborted. (This error code is not in use.)| -| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.)| -| STATUS_UNINSTALL_FAILURE_CONFLICT | 10 | Uninstallation conflict. (Failed to uninstall a system application or end the application process.)| -| STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT | 0x0B | Installation failed. (Download timed out.)| -| STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED | 0x0C | Installation failed. (Download failed.)| -| STATUS_RECOVER_FAILURE_INVALID8+ | 0x0D | Failed to restore the pre-installed application.| -| STATUS_ABILITY_NOT_FOUND | 0x40 | Ability not found.| -| STATUS_BMS_SERVICE_ERROR | 0x41 | BMS service error.| -| STATUS_FAILED_NO_SPACE_LEFT8+ | 0x42 | Insufficient device space.| -| STATUS_GRANT_REQUEST_PERMISSIONS_FAILED8+ | 0x43 | Application authorization failed.| -| STATUS_INSTALL_PERMISSION_DENIED8+ | 0x44 | Installation permission denied.| -| STATUS_UNINSTALL_PERMISSION_DENIED8+ | 0x45 | Uninstallation permission denied.| +| Name | Default Value | Description | +| ---------------------------------------- | ---- | ------------------------- | +| SUCCESS | 0 | Installation succeeded. | +| STATUS_INSTALL_FAILURE | 1 | Installation failed. (The application to be installed does not exist.) | +| STATUS_INSTALL_FAILURE_ABORTED | 2 | Installation aborted. | +| STATUS_INSTALL_FAILURE_INVALID | 3 | Invalid installation parameter. | +| STATUS_INSTALL_FAILURE_CONFLICT | 4 | Installation conflict. (The basic information about the application to upgrade is inconsistent with that of the existing application.) | +| STATUS_INSTALL_FAILURE_STORAGE | 5 | Failed to store the bundle information. | +| STATUS_INSTALL_FAILURE_INCOMPATIBLE | 6 | Installation incompatible. (A downgrade occurs or the signature information is incorrect.) | +| STATUS_UNINSTALL_FAILURE | 7 | Uninstallation failed. (The application to be uninstalled does not exist.) | +| STATUS_UNINSTALL_FAILURE_BLOCKED | 8 | Uninstallation aborted. (This error code is not in use.) | +| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.) | +| STATUS_UNINSTALL_FAILURE_CONFLICT | 10 | Uninstallation conflict. (Failed to uninstall a system application or end the application process.)| +| STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT | 0x0B | Installation failed. (Download timed out.) | +| STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED | 0x0C | Installation failed. (Download failed.) | +| STATUS_RECOVER_FAILURE_INVALID8+ | 0x0D | Failed to restore the pre-installed application. | +| STATUS_ABILITY_NOT_FOUND | 0x40 | Ability not found. | +| STATUS_BMS_SERVICE_ERROR | 0x41 | BMS service error. | +| STATUS_FAILED_NO_SPACE_LEFT8+ | 0x42 | Insufficient device space. | +| STATUS_GRANT_REQUEST_PERMISSIONS_FAILED8+ | 0x43 | Application authorization failed. | +| STATUS_INSTALL_PERMISSION_DENIED8+ | 0x44 | Installation permission denied. | +| STATUS_UNINSTALL_PERMISSION_DENIED8+ | 0x45 | Uninstallation permission denied. | ## BundleFlag @@ -1386,21 +1172,20 @@ Enumerates bundle flags. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Default Value| Description | -| ------ | ------ | ------ | -| GET_BUNDLE_DEFAULT | 0x00000000 | Obtains the default application information.| -| GET_BUNDLE_WITH_ABILITIES | 0x00000001 | Obtains the bundle information with the ability information.| -| GET_ABILITY_INFO_WITH_PERMISSION | 0x00000002 | Obtains the ability information with the permission information.| -| GET_ABILITY_INFO_WITH_APPLICATION | 0x00000004 | Obtains the ability information with the application information.| -| GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | Obtains the application information with the permission information.| -| GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | Obtains the bundle information with the information about the required permissions.| -| GET_ABILITY_INFO_WITH_METADATA8+ | 0x00000020 | Obtains the ability metadata information.| -| GET_BUNDLE_WITH_EXTENSION_ABILITY9+ | 0x00000020 | Obtains the bundle information with the extension ability information.| -| GET_APPLICATION_INFO_WITH_METADATA8+ | 0x00000040 | Obtains the application metadata information.| +| Name | Default Value | Description | +| ---------------------------------------- | ---------- | ------------------- | +| GET_BUNDLE_DEFAULT | 0x00000000 | Obtains the default application information. | +| GET_BUNDLE_WITH_ABILITIES | 0x00000001 | Obtains the bundle information with the ability information. | +| GET_ABILITY_INFO_WITH_PERMISSION | 0x00000002 | Obtains the ability information with the permission information. | +| GET_ABILITY_INFO_WITH_APPLICATION | 0x00000004 | Obtains the ability information with the application information. | +| GET_APPLICATION_INFO_WITH_PERMISSION | 0x00000008 | Obtains the application information with the permission information. | +| GET_BUNDLE_WITH_REQUESTED_PERMISSION | 0x00000010 | Obtains the bundle information with the information about the required permissions. | +| GET_ABILITY_INFO_WITH_METADATA8+ | 0x00000020 | Obtains the ability metadata information. | +| GET_APPLICATION_INFO_WITH_METADATA8+ | 0x00000040 | Obtains the application metadata information. | | GET_ABILITY_INFO_SYSTEMAPP_ONLY8+ | 0x00000080 | Obtains the ability information with information about system applications.| -| GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | Obtains information about disabled abilities.| -| GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | Obtains information about disabled applications.| -| GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information.| +| GET_ABILITY_INFO_WITH_DISABLE8+ | 0x00000100 | Obtains information about disabled abilities. | +| GET_APPLICATION_INFO_WITH_DISABLE8+ | 0x00000200 | Obtains information about disabled applications. | +| GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | ## BundleOptions @@ -1408,9 +1193,9 @@ Describes the bundle options. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| userId | number | Yes| Yes| User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------- | +| userId | number | Yes | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| ## BundleInfo @@ -1418,32 +1203,31 @@ Describes the application bundle information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Bundle name. | -| type | string | Yes | No | Bundle type. | -| appId | string | Yes | No | ID of the application to which the bundle belongs. | -| uid | number | Yes | No | UID of the application to which the bundle belongs. | -| installTime | number | Yes | No | Time when the HAP file was installed. | -| updateTime | number | Yes | No | Time when the HAP file was updated. | -| appInfo | ApplicationInfo | Yes | No | Application configuration information. | -| abilityInfos | Array\ | Yes | No | Ability configuration information. | -| reqPermissions | Array\ | Yes | No | Array of the permissions to request from the system. | -| reqPermissionDetails | Array\ | Yes | No | Detailed information of the permissions to request from the system.| -| vendor | string | Yes | No | Vendor of the bundle. | -| versionCode | number | Yes | No | Version number of the bundle. | -| versionName | string | Yes | No | Version description of the bundle. | -| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | -| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | -| hapModuleInfos | Array\ | Yes | No | Module configuration information. | -| entryModuleName | string | Yes | No | Name of the entry module. | -| cpuAbi | string | Yes | No | cpuAbi information of the bundle. | -| isSilentInstallation | string | Yes | No | Whether to install the bundle in silent mode. | -| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes| No| Whether installation-free is supported for the entry.| -| reqPermissionStates8+ | Array\ | Yes| No| Permission grant state.| -| extensionAbilityInfo9+ | Array\ | Yes| No| Extended information of the ability.| +| Name | Type | Readable | Writable | Description | +| --------------------------------- | ---------------------------- | ---- | ---- | --------------------- | +| name | string | Yes | No | Bundle name. | +| type | string | Yes | No | Bundle type. | +| appId | string | Yes | No | ID of the application to which the bundle belongs. | +| uid | number | Yes | No | UID of the application to which the bundle belongs. | +| installTime | number | Yes | No | Time when the HAP file was installed. | +| updateTime | number | Yes | No | Time when the HAP file was updated. | +| appInfo | ApplicationInfo | Yes | No | Application configuration information. | +| abilityInfos | Array\ | Yes | No | Ability configuration information. | +| reqPermissions | Array\ | Yes | No | Array of the permissions to request from the system. | +| reqPermissionDetails | Array\ | Yes | No | Detailed information of the permissions to request from the system.| +| vendor | string | Yes | No | Vendor of the bundle. | +| versionCode | number | Yes | No | Version number of the bundle. | +| versionName | string | Yes | No | Version description of the bundle. | +| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | +| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | +| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| hapModuleInfos | Array\ | Yes | No | Module configuration information. | +| entryModuleName | string | Yes | No | Name of the entry module. | +| cpuAbi | string | Yes | No | cpuAbi information of the bundle. | +| isSilentInstallation | string | Yes | No | Whether to install the bundle in silent mode. | +| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. | ## ApplicationInfo @@ -1451,31 +1235,28 @@ Describes the application information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | -| icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used by default.| -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application. | -| moduleInfos | Array\ | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| customizeData | Map> | Yes | Yes | Custom data of the application. | -| codePath8+ | string | Yes| No| Installation directory of the application.| -| metaData8+ | Map> | Yes| No| Custom metadata of the application.| -| metaData9+ | Map> | Yes| No| Metadata of the application.| -| removable8+ | boolean | Yes| No| Whether the application is removable.| -| accessTokenId8+ | number | Yes| No| Access token ID of the application.| -| uid8+ | number | Yes| No| UID of the application.| -| entityType9+ | string | Yes| No| Entity type of the application.| +| Name | Type | Readable | Writable | Description | +| -------------------------- | ---------------------------------- | ---- | ---- | --------------------- | +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used by default.| +| supportedModes | number | Yes | No | Running modes supported by the application. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application. | +| moduleInfos | Array\ | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map> | Yes | No | Custom metadata of the application. | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | ## ModuleInfo @@ -1483,10 +1264,10 @@ Describes the module information of the application. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| moduleName | string | Yes | No | Module name.| -| moduleSourceDir | string | Yes | No | Installation directory.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------ | ---- | ---- | ---- | +| moduleName | string | Yes | No | Module name.| +| moduleSourceDir | string | Yes | No | Installation directory.| ## CustomizeData @@ -1494,11 +1275,11 @@ Describes the custom metadata. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | ---- | ---------------- | -| name | string | Yes | Yes | Custom metadata name.| -| value | string | Yes | Yes | Custom metadata value. | -| extra8+ | string | Yes | Yes | Custom resources. | +| Name | Type | Readable | Writable | Description | +| ------------------ | ------ | ---- | ---- | -------- | +| name | string | Yes | Yes | Custom metadata name.| +| value | string | Yes | Yes | Custom metadata value. | +| extra8+ | string | Yes | Yes | Custom resources. | ## HapModuleInfo @@ -1507,26 +1288,23 @@ Describes the HAP module information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | No | Module name. | -| description | string | Yes | No | Module description. | -| descriptionId | number | Yes | No | Module description ID. | -| icon | string | Yes | No | Module icon. | -| label | string | Yes | No | Module label. | -| labelId | number | Yes | No | Module label ID. | -| iconId | number | Yes | No | Module icon ID. | -| backgroundImg | string | Yes | No | Module background image. | -| supportedModes | number | Yes | No | Modes supported by the module. | -| reqCapabilities | Array\ | Yes | No | Capabilities required for module running.| -| deviceTypes | Array\ | Yes | No | An array of supported device types.| -| abilityInfo | Array\ | Yes | No | Ability information. | -| moduleName | string | Yes | No | Module name. | -| mainAbilityName | string | Yes | No | Name of the entry ability. | -| installationFree | boolean | Yes | No | Whether installation-free is supported. | -| mainElementName8+ | string | Yes| No| Information about the entry ability.| -| extensionAbilityInfo9+ | Array\ | Yes| No| Extension ability information.| -| metadata9+ | Array\ | Yes| No| Metadata of the ability.| +| Name | Type | Readable | Writable | Description | +| --------------------------------- | ---------------------------- | ---- | ---- | ------------------ | +| name | string | Yes | No | Module name. | +| description | string | Yes | No | Module description. | +| descriptionId | number | Yes | No | Module description ID. | +| icon | string | Yes | No | Module icon. | +| label | string | Yes | No | Module label. | +| labelId | number | Yes | No | Module label ID. | +| iconId | number | Yes | No | Module icon ID. | +| backgroundImg | string | Yes | No | Module background image. | +| supportedModes | number | Yes | No | Modes supported by the module. | +| reqCapabilities | Array\ | Yes | No | Capabilities required for module running. | +| deviceTypes | Array\ | Yes | No | An array of supported device types. | +| abilityInfo | Array\ | Yes | No | Ability information. | +| moduleName | string | Yes | No | Module name. | +| mainAbilityName | string | Yes | No | Name of the entry ability. | +| installationFree | boolean | Yes | No | Whether installation-free is supported. | ## ReqPermissionDetail @@ -1534,11 +1312,11 @@ Describes the detailed information of the permissions to request from the system **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| name | string | Yes | Yes | Name of the permission to request. | -| reason | string | Yes | Yes | Reason for requesting the permission. | -| usedScene | UsedScene | Yes| Yes| Application scenario and timing for using the permission.| +| Name | Type | Readable | Writable | Description | +| --------- | --------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Name of the permission to request. | +| reason | string | Yes | Yes | Reason for requesting the permission. | +| usedScene | UsedScene | Yes | Yes | Application scenario and timing for using the permission.| ## UsedScene @@ -1546,10 +1324,10 @@ Describes the application scenario and timing for using the permission. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| abilities | Array\ | Yes | Yes | Abilities that use the permission.| -| when | string | Yes | Yes | Time when the permission is used. | +| Name | Type | Readable | Writable | Description | +| --------- | -------------- | ---- | ---- | ---------------- | +| abilities | Array\ | Yes | Yes | Abilities that use the permission.| +| when | string | Yes | Yes | Time when the permission is used. | ## AbilityInfo @@ -1558,36 +1336,35 @@ Describes the ability information. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| bundleName | string | Yes | No | Application bundle name. | -| name | string | Yes | No | Ability name. | -| label | string | Yes | No | Ability name visible to users. | -| description | string | Yes | No | Ability description. | -| icon | string | Yes | No | Index of the ability icon resource file. | -| descriptionId | number | Yes | No | Ability description ID. | -| iconId | number | Yes | No | Ability icon ID. | -| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | -| process | string | Yes | No | Process in which this ability runs. If this parameter is not set, the bundle name is used by default.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to. | -| backgroundModes | number | Yes | No | Background service mode of the ability. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | -| type | AbilityType | Yes | No | Ability type. | -| orientation | DisplayOrientation | Yes | No | Ability display orientation. | -| launchMode | LaunchMode | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| -| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | -| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data. | -| writePermission | string | Yes | No | Permission required for writing data to the ability. | -| applicationInfo | ApplicationInfo | Yes | No | Application configuration information. | -| uri | string | Yes | No | URI of the ability. | -| labelId | number | Yes | No | Ability label ID. | -| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | -| metaData8+ | Array\ | Yes| No| Custom information of the ability.| -| metaData9+ | Array\ | Yes| No| Metadata of the ability.| -| enabled8+ | boolean | Yes| No| Whether the ability is enabled.| +| Name | Type | Readable | Writable | Description | +| --------------------- | --------------------- | ---- | ---- | ------------------------ | +| bundleName | string | Yes | No | Application bundle name. | +| name | string | Yes | No | Ability name. | +| label | string | Yes | No | Ability name visible to users. | +| description | string | Yes | No | Ability description. | +| icon | string | Yes | No | Index of the ability icon resource file. | +| descriptionId | number | Yes | No | Ability description ID. | +| iconId | number | Yes | No | Ability icon ID. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | +| process | string | Yes | No | Process in which this ability runs. If this parameter is not set, the bundle name is used by default.| +| targetAbility | string | Yes | No | Target ability that the ability alias points to. | +| backgroundModes | number | Yes | No | Background service mode of the ability. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | +| type | AbilityType | Yes | No | Ability type. | +| orientation | DisplayOrientation | Yes | No | Ability display orientation. | +| launchMode | LaunchMode | Yes | No | Ability launch mode. | +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| +| deviceTypes | Array\ | Yes | No | Device types supported by the ability. | +| deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data. | +| writePermission | string | Yes | No | Permission required for writing data to the ability. | +| applicationInfo | ApplicationInfo | Yes | No | Application configuration information. | +| uri | string | Yes | No | URI of the ability. | +| labelId | number | Yes | No | Ability label ID. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | +| metaData8+ | Array\ | Yes | No | Custom information of the ability. | +| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | ## AbilityType @@ -1595,12 +1372,12 @@ Enumerates ability types. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ------- | ---- | --------------------------- | -| UNKNOWN | None | Unknown ability type. | -| PAGE | None | Ability that has a UI. | -| SERVICE | None | Ability that does not have a UI. | -| DATA | None | Ability that is used to provide data access services.| +| Name | Type | Description | +| ------- | ---- | ----------------- | +| UNKNOWN | None | Unknown ability type. | +| PAGE | None | Ability that has a UI. | +| SERVICE | None | Ability that does not have a UI. | +| DATA | None | Ability that is used to provide data access services.| ## DisplayOrientation @@ -1608,12 +1385,12 @@ Enumerates display orientations. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ------------- | ---- | ------------------------ | -| UNSPECIFIED | None | The system automatically determines the display orientation. | -| LANDSCAPE | None | Landscape orientation. | -| PORTRAIT | None | Portrait orientation. | -| FOLLOW_RECENT | None | The page ability orientation is the same as that of the nearest ability in the stack.| +| Name | Type | Description | +| ------------- | ---- | ------------- | +| UNSPECIFIED | None | The system automatically determines the display orientation. | +| LANDSCAPE | None | Landscape orientation. | +| PORTRAIT | None | Portrait orientation. | +| FOLLOW_RECENT | None | The page ability orientation is the same as that of the nearest ability in the stack.| ## LaunchMode @@ -1621,10 +1398,10 @@ Enumerates launch modes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| SINGLETON | 0 | The ability has only one instance.| -| STANDARD | 1 | The ability can have multiple instances. | +| Name | Type | Description | +| --------- | ---- | ------------- | +| SINGLETON | 0 | The ability has only one instance.| +| STANDARD | 1 | The ability can have multiple instances. | ## AbilitySubType @@ -1632,56 +1409,23 @@ Enumerates ability subtypes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ----------------------------- | -| UNSPECIFIED | 0 | Undefined ability subtype. | +| Name | Type | Description | +| ----------- | ---- | -------------------- | +| UNSPECIFIED | 0 | Undefined ability subtype. | | CA | 1 | Ability that has a UI.| -## ExtensionAbilityType9+ - -Enumerates extension ability types. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type| Description | -| -------------------- | ---- | ----------------------------- | -| FORM9+ | 0 | Form included. | -| WORK_SCHEDULER9+ | 1 | Work scheduler included.| -| INPUT_METHOD9+ | 2 | Input method included. | -| SERVICE9+ | 3 | Service included. | -| ACCESSIBILITY9+ | 4 | Accessibility included. | -| DATA_SHARE9+ | 5 | Data sharing included.| -| FILE_SHARE9+ | 6 | File sharing included.| -| STATIC_SUBSCRIBER9+ | 7 | Subscribers included. | -| WALLPAPER9+ | 8 | Wallpaper included. | -| UNSPECIFIED9+ | 9 | Unspecified type. | - -## ExtensionFlag9+ - -Enumerates extension flags. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Default Value| Description | -| ------ | ------ | ------ | -| GET_EXTENSION_INFO_DEFAULT9+ | 0x00000000 | Obtains the default extension ability information.| -| GET_EXTENSION_INFO_WITH_PERMISSION9+ | 0x00000002 | Obtains the extension ability information that carries permission information.| -| GET_EXTENSION_INFO_WITH_APPLICATION9+ | 0x00000004 | Obtains the extension ability information that carries application information.| -| GET_EXTENSION_INFO_WITH_METADATA9+ | 0x00000020 | Obtains the extension ability information that carries metadata information.| - - ## ColorMode Enumerates color modes. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| AUTO_MODE | -1 | Automatic mode.| -| DARK_MODE | 0 | Dark mode. | -| LIGHT_MODE | 1 | Light mode. | +| Name | Type | Description | +| ---------- | ---- | ---- | +| AUTO_MODE | -1 | Automatic mode.| +| DARK_MODE | 0 | Dark mode.| +| LIGHT_MODE | 1 | Light mode.| ## GrantStatus @@ -1690,44 +1434,7 @@ Enumerates permission grant statuses. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type| Description | -| ----------- | ---- | ------------------- | -| PERMISSION_DENIED | -1 | Permission denied.| -| PERMISSION_GRANTED | 0 | Permission granted. | - - -## ExtensionAbilityInfo9+ - -Describes the extension ability information. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type| Readable| Writable| Description| -| ------ | ------ | ------ | ------ | ------ | -| bundleName9+ | string | Yes | No | Application bundle name. | -| moduleName9+ | string | Yes | No | Name of the HAP file to which the extension ability belongs. | -| name9+ | string | Yes | No | Name of the extension ability. | -| labelId9+ | number | Yes | No | Label ID of the extension ability. | -| descriptionId9+ | number | Yes | No | Description ID of the extension ability. | -| iconId9+ | number | Yes | No | Icon ID of the extension ability. | -| isVisible9+ | boolean | Yes | No | Whether the extension ability can be called by other applications. | -| extensionAbilityType9+ | bundle.ExtensionAbilityType | Yes | No | Type of the extension ability. | -| permissions9+ | Array\ | Yes | No | Permissions required for other applications to call the extension ability.| -| applicationInfo9+ | ApplicationInfo | Yes | No | Application configuration information. | -| metaData9+ | Array\ | Yes| No| Metadata of the extension ability.| -| enabled9+ | boolean | Yes| No| Whether the extension ability is enabled.| -| readPermission9+ | string | Yes | No | Permission required for reading the extension ability data. | -| writePermission9+ | string | Yes | No | Permission required for writing data to the extension ability. | - - -## Metadata9+ - -Describes the metadata information. - - **System capability**: SystemCapability.BundleManager.BundleFramework - -| Name | Type | Readable| Writable| Description | -| ----- | ------ | ---- | ---- | ---------------- | -| name9+ | string | Yes | Yes | Metadata name.| -| value9+ | string | Yes | Yes | Metadata value. | -| resource9+ | string | Yes | Yes | Metadata resource. | +| Name | Type | Description | +| ------------------ | ---- | ---- | +| PERMISSION_DENIED | -1 | Permission denied.| +| PERMISSION_GRANTED | 0 | Permission granted. | diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index 4b2526ce8336f5ae3391f0652cbf17dacb7c6f54..7beee10809e0b7252c65ed514180413bc92f10bb 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -880,9 +880,9 @@ Obtains the context of the application. **Return value** -| Parameters | Type | Description | -| --------------- | ------------------------- |------ | -| Context | Context |Application context.| +| Type | Description | +| --------- |------ | +| Context |Application context.| **Example** @@ -908,7 +908,7 @@ var context = featureAbility.getContext().getApplicationContext(); | ----------- | -------- | -------------- | ---- | ------------------ | | requestCode | Read-only | number | Yes | Request code passed.| | permissions | Read-only | Array\ | Yes | Permissions requested. | -| authResults | Read-only | Array\ | Yes | Permission request result. | +| authResults | Read-only | Array\ | Yes | Permission request result. | ## HapModuleInfo diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md deleted file mode 100644 index 6e5f9e4b36e1df88f85f2b9a91434b700f508673..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ /dev/null @@ -1,495 +0,0 @@ -# AbilityContext - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements the ability context. This module is inherited from **Context**. - - -## Usage - - -Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. - - - -```js -import Ability from '@ohos.application.Ability' -class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - let context = this.context; - } -} -``` - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityContext.startAbility - -startAbility(want: Want, callback: AsyncCallback<void>): void - -Starts an ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - this.context.startAbility(want, (error) => { - console.log("error.code = " + error.code) - }) - ``` - - -## AbilityContext.startAbility - -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void - -Starts an ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want) | Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) - }) - ``` - - -## AbilityContext.startAbility - -startAbility(want: Want, options?: StartOptions): Promise<void>; - -Starts an ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "com.extreme.test.MainAbility" - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options) - .then((data) => { - console.log('Operation successful.') - }).catch((error) => { - console.log('Operation failed.'); - }) - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| - - -**Example** - - ```js - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; - -Starts an ability. This API uses a callback to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | Yes| Parameters used for starting the ability.| - | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| - - -**Example** - - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult( - {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options, - (error, result) => { - console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) - console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) - } - ); - ``` - - -## AbilityContext.startAbilityForResult - -startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; - -Starts an ability. This API uses a promise to return the execution result when the ability is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| - | options | StartOptions | No| Parameters used for starting the ability.| - - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| - -**Example** - - ```js - var options = { - windowMode: 0, - }; - this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, options).then((result) => { - console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) - }, (error) => { - console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) - }) - ``` - - -## AbilityContext.terminateSelf - -terminateSelf(callback: AsyncCallback<void>): void; - -Terminates this ability. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringfy(err)); - }); - ``` - - -## AbilityContext.terminateSelf - -terminateSelf(): Promise<void>; - -Terminates this ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.terminateSelf(want).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; - -Terminates this ability. This API uses a callback to return the information to the caller of **startAbilityForResult**. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }, (error) => { - console.log("terminateSelfWithResult is called = " + error.code) - } - ); - ``` - - -## AbilityContext.terminateSelfWithResult - -terminateSelfWithResult(parameter: AbilityResult): Promise<void>; - -Terminates this ability. This API uses a promise to return information to the caller of **startAbilityForResult**. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }).then((result) => { - console.log("terminateSelfWithResult") - } - ) - ``` - - -## AbilityContext.startAbilityByCall - -startAbilityByCall(want: Want): Promise<Caller>; - -Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<Caller> | Promise used to return the caller object to communicate with.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - console.log('Caller GetCaller Get ' + call); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a pop-up window. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| - | callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ``` - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); - }); - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a pop-up window. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ``` - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` - - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string, callback:AsyncCallback<void>): void; - -Sets the label of the ability displayed in the task. This API uses a callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringfy(result)); - }); - ``` - - -## AbilityContext.setMissionLabel - -setMissionLabel(label: string): Promise<void> - -Sets the label of the ability displayed in the task. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | label | string | Yes| Label of the ability to set.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| - -**Example** - - ```js - this.context.setMissionLabel("test").then((data) => { - console.log('success:' + JSON.stringfy(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringfy(error)); - }); - ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md new file mode 100644 index 0000000000000000000000000000000000000000..e81e9d60f6bcf0d1b5f0376057f577c2b467f45d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -0,0 +1,25 @@ +# ErrorCode + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + + +## Modules to Import + +``` +import errorCode from '@ohos.ability.errorCode' +``` + +## ErrorCode + +Defines the error code used when the ability is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| NO_ERROR | 0 | No error occurs. | +| INVALID_PARAMETER | -1 | Invalid parameter.| +| ABILITY_NOT_FOUND | -2 | The ability is not found.| +| PERMISSION_DENY | -3 | Permission denied. | diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..ef6e3e60018a4124ef5d917217599b520d550fe1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -0,0 +1,88 @@ +# wantConstant + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + + +## Modules to Import + +``` +import wantConstant from '@ohos.ability.wantConstant' +``` + + +## wantConstant.Action + +**System capability**: SystemCapability.Ability.AbilityBase + +Lists the permissions. + +| Common Event Macro | Common Event Name | Subscriber Permission | +| ------------ | ------------------ | ---------------------- | +| ACTION_HOME | ohos.want.action.home | None | +| ACTION_DIAL | ohos.want.action.dial | None | +| ACTION_SEARCH | ohos.want.action.search | None | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | None | +| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | None | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | +| ACTION_SET_ALARM | ohos.want.action.setAlarm | None | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | None | +| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | None | +| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | None | +| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | None | +| ACTION_SEND_SMS | ohos.want.action.sendSms | None | +| ACTION_CHOOSE | ohos.want.action.choose | None | +| ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | None | +| ACTION_VIDEO_CAPTUR8+ | ohos.want.action.videoCapture | None | +| ACTION_SELECT | ohos.want.action.select | None | +| ACTION_SEND_DATA | ohos.want.action.sendData | None | +| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | None | +| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | None | +| ACTION_VIEW_DATA | ohos.want.action.viewData | None | +| ACTION_EDIT_DATA | ohos.want.action.editData | None | +| INTENT_PARAMS_INTENT | ability.want.params.INTENT | None | +| INTENT_PARAMS_TITLE | ability.want.params.TITLE | None | +| ACTION_FILE_SELECT7+ | ohos.action.fileSelect | None | +| PARAMS_STREAM7+ | ability.params.stream | None | +| ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | None | + + +## wantConstant.Entity + +**System capability**: SystemCapability.Ability.AbilityBase + +Lists the permissions. + +| Common Event Macro | Common Event Name | Subscriber Permission | +| ------------ | ------------------ | ---------------------- | +| ENTITY_DEFAULT | entity.system.default | None | +| ENTITY_HOME | entity.system.homel | None | +| ENTITY_VOICE | ENTITY_VOICE | None | +| ENTITY_BROWSABLE | entity.system.browsable | None | +| ENTITY_VIDEO | entity.system.video | None | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | None | + + +## flags + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 0d008c7f831661dcc9d49bb8a8cf3273ede1a361..9f81d3aab860d8f6123d09d7f4aae8893ca19aa4 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -204,6 +204,8 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS + **System capability**: SystemCapability.Security.AccessToken **Parameters** @@ -234,7 +236,7 @@ promise.then(data => { Enumerates the permission grant states. -**System capability:** SystemCapability.Security.AccessToken +**System capability**: SystemCapability.Security.AccessToken | Name | Default Value | Description | | ----------------------------- | ---------------------- | ----------------------- | diff --git a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md new file mode 100644 index 0000000000000000000000000000000000000000..5f772d8706f2872fbea97c59e42f7dfd878575df --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @@ -0,0 +1,76 @@ +# AbilityDelegatorRegistry + +> **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 + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityLifecycleState + +Enumerates the ability lifecycle states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | ---- | --------------------------- | +| UNINITIALIZED | 0 | The ability is in an invalid state. | +| CREATE | 1 | The ability is created.| +| FOREGROUND | 2 | The ability is running in the foreground. | +| BACKGROUND | 3 | The ability is running in the background. | +| DESTROY | 4 | The ability is destroyed.| + + + +## AbilityDelegatorRegistry.getAbilityDelegator + +getAbilityDelegator(): AbilityDelegator + +Obtains the **AbilityDelegator** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| + +**Example** + +```js +var abilityDelegator; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +``` + + + +## AbilityDelegatorRegistry.getArguments + +getArguments(): AbilityDelegatorArgs + +Obtains the **AbilityDelegatorArgs** object of the application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| + +**Example** + +```js +var args = AbilityDelegatorRegistry.getArguments(); +console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments testCaseNames:" + args.testCaseNames); +console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md index 0ed9eb40d2cfe73bcc98bfb394d894809f6700dc..b4f137e8d3f3da19beb7a1b5a8bbbc8a4ab74ee3 100644 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md @@ -22,6 +22,7 @@ abilitymanager.getAbilityRunningInfos((err,data) => { ``` ## Attributes + **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Readable| Writable| Description| @@ -31,10 +32,11 @@ abilitymanager.getAbilityRunningInfos((err,data) => { | uid | number | Yes| No| User ID. | | processName | string | Yes| No| Process name. | | startTime | number | Yes| No| Ability start time. | -| abilityState | [abilityManager.AbilityState](#abilitymanager-abilitystate) | Yes| No| Ability state. | +| abilityState | [abilityManager.AbilityState](#abilitymanagerabilitystate) | Yes| No| Ability state. | ## abilityManager.AbilityState + Enumerates the ability states. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md b/en/application-dev/reference/apis/js-apis-abilitystagecontext.md deleted file mode 100644 index 91e8a7513e8c68f06105d14d4a96fc0cec9e2fac..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md +++ /dev/null @@ -1,33 +0,0 @@ -# AbilityStageContext - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md). - - -## Usage - - -The ability stage context is obtained through an **AbilityStage** instance. - - - -```js -import AbilityStage from '@ohos.application.AbilityStage'; -class MyAbilityStage extends AbilityStage { - onCreate() { - let abilityStageContext = this.context; - } -} -``` - - -## Attributes -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index f8414adaa9aa458914b66d9aaf503183c299095c..7041eaef2788d011c6e953e7657d2d4b38a2100e 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -20,8 +20,8 @@ Creates an **AppAccountManager** instance. **System capability**: SystemCapability.Account.AppAccount **Return Value** -| Type | Description | -| ----------------- | ------------------------ | +| Type | Description | +| ----------------- | ------------ | | AppAccountManager | **AppAccountManager** instance created.| **Example** @@ -43,10 +43,10 @@ Adds an app account to the account management service. This method uses an async **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------------------- | +| name | string | Yes | Name of the app account to add. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| **Example** @@ -67,11 +67,11 @@ Adds an app account and its additional information to the account management ser **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information (for example, token) of the app account to add. The additional information cannot contain sensitive information about the app account.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account and its additional information are added. | +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| name | string | Yes | Name of the app account to add. | +| extraInfo | string | Yes | Additional information (for example, token) of the app account to add. The additional information cannot contain sensitive information about the app account.| +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account and its additional information are added. | **Example** @@ -94,15 +94,15 @@ Adds an app account and its additional information to the account management ser **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information of the app account to add. The additional information cannot contain sensitive information about the app account.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------------------------------- | +| name | string | Yes | Name of the app account to add. | +| extraInfo | string | Yes | Additional information of the app account to add. The additional information cannot contain sensitive information about the app account.| **Return Value** -| Type | Description | -| ------------------- | ---------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -126,12 +126,12 @@ Implicitly adds an app account based on the specified account owner, authenticat **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------ | -| owner | string | Yes | Bundle name of the app account to add.| -| authType | string | Yes | Authentication type of the app account to add. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| owner | string | Yes | Bundle name of the app account to add.| +| authType | string | Yes | Authentication type of the app account to add. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** @@ -167,10 +167,10 @@ Deletes an app account from the account management service. This method uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------- | -| name | string | Yes | Name of the app account to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the app account to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| **Example** @@ -191,14 +191,14 @@ Deletes an app account from the account management service. This method uses a p **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------ | -| name | string | Yes | Name of the app account to delete.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| name | string | Yes | Name of the app account to delete.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -222,11 +222,11 @@ Disables an app account from accessing an application with the given bundle name **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is disabled from accessing the application with the given bundle name.| **Example** @@ -247,15 +247,15 @@ Disables an app account from accessing an application with the given bundle name **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ---------------------------------- | -| name | string | Yes | App account name.| -| bundleName | string | Yes | Bundle name of an app. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ----------------- | +| name | string | Yes | App account name.| +| bundleName | string | Yes | Bundle name of an app. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -279,11 +279,11 @@ Enables an app account to access an application with the given bundle name. This **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------------------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is enabled to access the application with the given bundle name.| **Example** @@ -304,15 +304,15 @@ Enables an app account to access an application with the given bundle name. This **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------ | -| name | string | Yes | App account name. | -| bundleName | string | Yes | Bundle name of an app.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | App account name. | +| bundleName | string | Yes | Bundle name of an app.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -337,10 +337,10 @@ Checks whether an app account allows application data synchronization. This meth **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | -------------------------------------------- | -| name | string | Yes | App account name. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the app account allows application data synchronization.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ---------------------- | +| name | string | Yes | App account name. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return whether the app account allows application data synchronization.| **Example** @@ -364,14 +364,14 @@ Checks whether an app account allows application data synchronization. This meth **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | string | Yes | App account name.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | App account name.| **Return Value** -| Type | Description | -| :--------------------- | :---------------------------------- | +| Type | Description | +| :--------------------- | :-------------------- | | Promise<boolean> | Promise used to return the result.| **Example** @@ -387,7 +387,7 @@ Checks whether an app account allows application data synchronization. This meth ### setAccountCredential -setAccountCredential(name: string, credentialType: string, credential: string callback: AsyncCallback<void>): void +setAccountCredential(name: string, credentialType: string, credential: string, callback: AsyncCallback<void>): void Sets a credential for an app account. This method uses an asynchronous callback to return the result. @@ -395,12 +395,12 @@ Sets a credential for an app account. This method uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | ---------------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to set. | -| credential | string | Yes | Credential to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when a credential is set for the specified app account.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ---- | -------------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to set. | +| credential | string | Yes | Credential to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when a credential is set for the specified app account.| **Example** @@ -421,16 +421,16 @@ Sets a credential for an app account. This method uses a promise to return the r **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to set.| -| credential | string | Yes | Credential to set. | +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to set.| +| credential | string | Yes | Credential to set. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -454,11 +454,11 @@ Sets additional information for an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | -------------------------------- | -| name | string | Yes | App account name. | -| extraInfo | string | Yes | Additional information to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when additional information is set for the specified app account.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------- | +| name | string | Yes | App account name. | +| extraInfo | string | Yes | Additional information to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when additional information is set for the specified app account.| **Example** @@ -479,15 +479,15 @@ Sets additional information for an app account. This method uses a promise to re **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------------ | -| name | string | Yes | App account name. | -| extraInfo | string | Yes | Additional information to set.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | --------- | +| name | string | Yes | App account name. | +| extraInfo | string | Yes | Additional information to set.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -513,11 +513,11 @@ Sets whether to enable application data synchronization for an app account. This **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------------------------------------- | -| name | string | Yes | App account name. | -| isEnable | boolean | Yes | Whether to enable app data synchronization. | -| callback | AsyncCallback<void> | Yes | Callback invoked when application data synchronization is enabled or disabled for the app account.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | App account name. | +| isEnable | boolean | Yes | Whether to enable app data synchronization. | +| callback | AsyncCallback<void> | Yes | Callback invoked when application data synchronization is enabled or disabled for the app account.| **Example** @@ -540,15 +540,15 @@ Sets whether to enable application data synchronization for an app account. This **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| isEnable | boolean | Yes | Whether to enable app data synchronization.| +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | App account name. | +| isEnable | boolean | Yes | Whether to enable app data synchronization.| **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -572,12 +572,12 @@ Sets data to be associated with an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to set. The private key can be customized.| +| value | string | Yes | Value of the data to be set. | +| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| **Example** @@ -597,16 +597,16 @@ Sets data to be associated with an app account. This method uses a promise to re **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to set. The private key can be customized.| +| value | string | Yes | Value of the data to be set. | **Return Value** -| Type | Description | -| :------------------ | :---------------------------------- | +| Type | Description | +| :------------------ | :-------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -630,11 +630,11 @@ Obtains the credential of an app account. This method uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | --------------------------- | ---- | ---------------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential of the specified app account.| +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential of the specified app account.| **Example** @@ -656,15 +656,15 @@ Obtains the credential of an app account. This method uses a promise to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------- | -| name | string | Yes | App account name. | -| credentialType | string | Yes | Type of the credential to obtain.| +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | App account name. | +| credentialType | string | Yes | Type of the credential to obtain.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -688,10 +688,10 @@ Obtains additional information of an app account. This method uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------------------- | -| name | string | Yes | App account name. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ---------------- | +| name | string | Yes | App account name. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| **Example** @@ -713,14 +713,14 @@ Obtains additional information of an app account. This method uses a promise to **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | string | Yes | App account name.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | App account name.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -744,11 +744,11 @@ Obtains data associated with an app account. This method uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| **Example** @@ -770,15 +770,15 @@ Obtains data associated with an app account. This method uses a promise to retur **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------- | -| name | string | Yes | App account name. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| key | string | Yes | Key of the data to obtain.| **Return Value** -| Type | Description | -| :-------------------- | :---------------------------------- | +| Type | Description | +| :-------------------- | :-------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -798,15 +798,15 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>& Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------- | -| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------- | +| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| **Example** @@ -824,14 +824,14 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> Obtains information about all accessible app accounts. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<AppAccountInfo>> | Promise used to return the result.| **Example** @@ -851,16 +851,16 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------- | -| owner | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------- | +| owner | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<Array<AppAccountInfo>> | Yes | Callback invoked to return information about all accessible app accounts.| **Example** @@ -879,20 +879,20 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> Obtains information about all app accounts of the specified app. This method uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.GET_ACCOUNTS_PRIVILEGED (available only to system applications) +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------- | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<AppAccountInfo>> | Promise used to return the result.| **Example** @@ -917,11 +917,11 @@ Subscribes to the account change event of the specified account owners. This met **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | 'change' | Yes | Type of the event to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| -| owners | Array<string> | Yes | Owners of the accounts. | -| callback | Callback<Array<AppAccountInfo>> | Yes | Callback invoked to return the account change. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'change' | Yes | Type of the event to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| +| owners | Array<string> | Yes | Owners of the accounts. | +| callback | Callback<Array<AppAccountInfo>> | Yes | Callback invoked to return the account change. | **Example** @@ -948,10 +948,10 @@ Unsubscribes from the account change event. This method uses an asynchronous cal **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | ------------------------ | -| type | 'change' | Yes | Account change event to unsubscribe from. | -| callback | Callback> | No | Callback used to report the account change.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'change' | Yes | Account change event to unsubscribe from. | +| callback | Callback> | No | Callback used to report the account change.| **Example** @@ -981,13 +981,13 @@ Authenticates an app account to obtain the Open Authorization (OAuth) access tok **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------ | -| name | string | Yes | Name of the app account to authenticate. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the app account to authenticate. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** @@ -1023,12 +1023,12 @@ Obtains the OAuth access token of an app account based on the specified authenti **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | **Example** @@ -1050,16 +1050,16 @@ Obtains the OAuth access token of an app account based on the specified authenti **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| authType | string | Yes | Authentication type. | **Parameters** -| Type | Description | -| --------------------- | ----------------------------------- | +| Type | Description | +| --------------------- | --------------------- | | Promise<string> | Promise used to return the result.| **Example** @@ -1083,12 +1083,12 @@ Sets an OAuth access token for an app account. This method uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | App account name.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------- | +| name | string | Yes | App account name.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -1109,16 +1109,16 @@ Sets an OAuth access token for an app account. This method uses a promise to ret **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------- | -| name | string | Yes | App account name.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to set. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| name | string | Yes | App account name.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to set.| **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -1142,13 +1142,13 @@ Deletes the specified OAuth access token for an app account. This method uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to delete.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -1169,17 +1169,17 @@ Deletes the specified OAuth access token for an app account. This method uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth access token to delete. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | OAuth access token to delete.| **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -1203,13 +1203,13 @@ Sets the visibility of an OAuth access token to the specified app. This method u **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------ | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -1230,24 +1230,23 @@ Sets the visibility of an OAuth access token to the specified app. This method u **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- | ------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ------------ | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the OAuth access token is visible to the app. | **Parameters** -| Type | Description | -| ------------------- | ----------------------------------- | +| Type | Description | +| ------------------- | --------------------- | | Promise<void> | Promise used to return the result.| **Example** ``` const appAccountManager = account_appAccount.createAppAccountManager(); - const appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { @@ -1265,12 +1264,12 @@ Checks whether an OAuth token is visible to the specified app. This method uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------- | ---- | -------------------------- | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------- | ---- | ------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1292,16 +1291,16 @@ Checks whether an OAuth token is visible to the specified app. This method uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ---------------------- | ----------------------------------- | +| Type | Description | +| ---------------------- | --------------------- | | Promise<boolean> | Promise used to return the result.| **Example** @@ -1325,11 +1324,11 @@ Obtains information about all OAuth access tokens of an app account visible to t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<Array<OAuthTokenInfo>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<Array<OAuthTokenInfo>> | Yes | Callback invoked to return the result. | **Example** @@ -1351,15 +1350,15 @@ Obtains information about all OAuth access tokens of an app account visible to t **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ------------------------------------------ | ----------------------------------- | +| Type | Description | +| ---------------------------------------- | --------------------- | | Promise<Array<OAuthTokenInfo>> | Promise used to return the result.| **Example** @@ -1383,11 +1382,11 @@ Obtains the authorization list of OAuth access tokens of an app account. This me **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | **Example** @@ -1409,15 +1408,15 @@ Obtains the authorization list of OAuth access tokens of an app account. This me **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| name | string | Yes | App account name. | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | App account name. | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| ---------------------------------- | ----------------------------------- | +| Type | Description | +| ---------------------------------- | --------------------- | | Promise<Array<string>> | Promise used to return the result.| **Example** @@ -1441,10 +1440,10 @@ Obtains the authenticator callback for a session. This method uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------ | ---- | ---------------- | -| sessionId | string | Yes | ID of the session to authenticate.| -| callback | AsyncCallback<AuthenticatorCallback> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the session to authenticate.| +| callback | AsyncCallback<AuthenticatorCallback> | Yes | Callback invoked to return the result.| **Example** @@ -1476,14 +1475,14 @@ Obtains the authenticator callback for a session. This method uses a promise to **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------------- | -| sessionId | string | Yes | ID of the session to authenticate.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the session to authenticate.| **Parameters** -| Type | Description | -| ------------------------------------ | ----------------------------------- | +| Type | Description | +| ------------------------------------ | --------------------- | | Promise<AuthenticatorCallback> | Promise used to return the result.| **Example** @@ -1516,10 +1515,10 @@ Obtains authenticator information of an app account. This method uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<AuthenticatorInfo> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<AuthenticatorInfo> | Yes | Callback invoked to return the result. | **Example** @@ -1541,14 +1540,14 @@ Obtains authenticator information of an app account. This method uses a promise **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| **Parameters** -| Type | Description | -| -------------------------------- | ----------------------------------- | +| Type | Description | +| -------------------------------- | --------------------- | | Promise<AuthenticatorInfo> | Promise used to return the result.| **Example** @@ -1568,10 +1567,10 @@ Defines app account information. **System capability**: SystemCapability.Account.AppAccount -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| owner | string | Yes | Bundle name of the app.| -| name | string | Yes | App account name. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| name | string | Yes | App account name. | ## OAuthTokenInfo8+ @@ -1579,10 +1578,10 @@ Defines OAuth access token information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------- | -| authType | string | Yes | Authentication type.| -| token | string | Yes | Value of the access token. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| authType | string | Yes | Authentication type.| +| token | string | Yes | Value of the access token. | ## AuthenticatorInfo8+ @@ -1590,11 +1589,11 @@ Defines OAuth authenticator information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------- | -| owner | string | Yes | Bundle name of the authenticator owner.| -| iconId | string | Yes | ID of the authenticator icon. | -| labelId | string | Yes | ID of the authenticator label. | +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| owner | string | Yes | Bundle name of the authenticator owner.| +| iconId | string | Yes | ID of the authenticator icon. | +| labelId | string | Yes | ID of the authenticator label. | ## Constants8+ @@ -1602,19 +1601,19 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ------------------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation for implicitly adding an account. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | +| Name | Default Value | Description | +| ----------------------------- | ---------------------- | ------------- | +| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation for implicitly adding an account. | +| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | +| KEY_NAME | "name" | App account name. | | KEY_OWNER | "owner" | App account owner.| -| KEY_TOKEN | "token" | OAuth access token. | -| KEY_ACTION | "action" | Action. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | Caller process ID (PID). | -| KEY_CALLER_UID | "callerUid" | Caller user ID (UID). | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Caller bundle name. | +| KEY_TOKEN | "token" | OAuth access token. | +| KEY_ACTION | "action" | Action. | +| KEY_AUTH_TYPE | "authType" | Authentication type. | +| KEY_SESSION_ID | "sessionId" | Session ID. | +| KEY_CALLER_PID | "callerPid" | Caller process ID (PID). | +| KEY_CALLER_UID | "callerUid" | Caller user ID (UID). | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Caller bundle name. | ## ResultCode8+ @@ -1622,27 +1621,27 @@ Enumerates the result codes. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value| Description | -| ----------------------------------- | ------ | ------------------------ | -| SUCCESS | 0 | The operation is successful. | -| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | -| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | -| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | -| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | -| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | -| ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. | -| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. | -| ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. | -| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. | -| ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. | -| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | -| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | -| ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | -| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth access token does not exist.| -| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth access tokens reaches the limit. | -| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | -| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | -| ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | +| Name | Default Value | Description | +| ----------------------------------- | ----- | ------------ | +| SUCCESS | 0 | The operation is successful. | +| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | +| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | +| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | +| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | +| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | +| ERROR_NETWORK_EXCEPTION | 10006 | The network is abnormal. | +| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | The authenticator does not exist. | +| ERROR_OAUTH_CANCELED | 10008 | The authentication is canceled. | +| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | The size of the OAuth list exceeds the limit. | +| ERROR_OAUTH_SERVICE_BUSY | 10010 | The OAuth service is busy. | +| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | +| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | +| ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | +| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth access token does not exist.| +| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth access tokens reaches the limit. | +| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | +| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | +| ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | ## AuthenticatorCallback8+ @@ -1657,10 +1656,10 @@ Called back to send the authentication result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------------------- | ---- | ------------ | -| code | number | Yes | Authentication result code.| -| result | {[key: string]: any} | Yes | Authentication result. | +| Name | Type | Mandatory | Description | +| ------ | -------------------- | ---- | ------ | +| code | number | Yes | Authentication result code.| +| result | {[key: string]: any} | Yes | Authentication result. | **Example** @@ -1687,9 +1686,9 @@ Called back to redirect an authentication request. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type| Mandatory| Description | -| ------- | ---- | ---- | -------------------- | -| request | Want | Yes | Request to be redirected.| +| Name | Type | Mandatory | Description | +| ------- | ---- | ---- | ---------- | +| request | Want | Yes | Request to be redirected.| **Example** @@ -1724,12 +1723,12 @@ Implicitly adds an app account based on the specified authentication type and op **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------- | ---- | ------------------------------ | -| authType | string | Yes | Authentication type. | -| callerBundleName | string | Yes | Bundle name of the authentication requester. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Bundle name of the authentication requester. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| ### authenticate8+ @@ -1740,13 +1739,13 @@ Authenticates an app account to obtain the OAuth access token. This method uses **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | --------------------- | ---- | ------------------------------ | -| name | string | Yes | App account name. | -| authType | string | Yes | Authentication type. | -| callerBundleName | string | Yes | Bundle name of the authentication requester. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| name | string | Yes | App account name. | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Bundle name of the authentication requester. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | AuthenticatorCallback | Yes | Authenticator callback invoked to return the authentication result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md index fffd17605b6e72d0e3cc612c12bdd9e8bdcd5ab0..21cff7a9c850cc316aac00520824a8446cb8980e 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -1,8 +1,8 @@ # MissionSnapshot -> **NOTE** -> The initial APIs of this module are supported since API 8. +> ![icon-note.gif](public_sys-resources/icon-note.gif)**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. Provides snapshot of a mission. @@ -10,8 +10,6 @@ Provides snapshot of a mission. ## Modules to Import -Import ElementName and image before use. - ``` import { ElementName } from '../bundle/elementName'; diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md new file mode 100644 index 0000000000000000000000000000000000000000..3731cf8c99930e4bdf470946c5ad00067c142c21 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -0,0 +1,30 @@ +# Want + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + +**Want** is the basic communication component of the system. + + +## Modules to Import + + +``` +import Want from '@ohos.application.Want'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read only | string | No | ID of the device running the ability. | +| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | +| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| +| action | Read only | string | No | Action option. | +| parameters | Read only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read only | Array\ | No | List of entities. | | diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md deleted file mode 100644 index e775138da3d761cc425df00d59e58e2f6fbbc3bc..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ /dev/null @@ -1,587 +0,0 @@ -# Ability - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The 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. - - -Manages the ability lifecycle and context. - - -## Modules to Import - - -``` -import Ability from '@ohos.application.Ability'; -``` - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| -| launchWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters for starting the ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| -| lastRequestWant | [Want](js-apis-featureAbility.md#Want)| Yes| No| Parameters used when the ability was started last time.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore| - - -## Ability.onCreate - -onCreate(want: Want, param: AbilityConstant.LaunchParam): void; - -Called to initialize the service logic when an ability is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| 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) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## Ability.onWindowStageCreate - -onWindowStageCreate(windowStage: window.WindowStage): void - -Called when a **WindowStage** is created for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageCreate(windowStage) { - console.log('onWindowStageCreate'); - } - } - ``` - - -## Ability.onWindowStageDestroy - -onWindowStageDestroy(): void - -Called when the **WindowStage** is destroyed for this ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageDestroy() { - console.log('onWindowStageDestroy'); - } - } - ``` - - -## Ability.onWindowStageRestore - -onWindowStageRestore(windowStage: window.WindowStage): void - -Called when the **WindowStage** is restored during the migration of this ability, which is a multi-instance ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| - -**Example** - - ```js - class myAbility extends Ability { - onWindowStageRestore(windowStage) { - console.log('onWindowStageRestore'); - } - } - ``` - - -## Ability.onDestroy - -onDestroy(): void; - -Called when this ability is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## Ability.onForeground - -onForeground(): void; - -Called when this ability is running in the foreground. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onForeground() { - console.log('onForeground'); - } - } - ``` - - -## Ability.onBackground - -onBackground(): void; - -Callback when this ability is switched to the background. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - class myAbility extends Ability { - onBackground() { - console.log('onBackground'); - } - } - ``` - - -## Ability.onContinue - -onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; - -Called to save data during the ability migration preparation process. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | wantParam | {[key: string]: any} | Yes| **want** parameter.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | AbilityConstant.OnContinueResult | Continuation result.| - -**Example** - - ```js - class myAbility extends Ability { - onContinue(wantParams) { - console.log('onContinue'); - wantParams["myData"] = "my1234567"; - return true; - } - } - ``` - - -## Ability.onNewWant - -onNewWant(want: Want): void; - -Called when the ability startup mode is set to singleton. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Want parameters, such as the ability name and bundle name.| - -**Example** - - ```js - class myAbility extends Ability { - onNewWant(want) { - console.log('onNewWant, want:' + want.abilityName); - } - } - ``` - - -## Ability.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](#section188911144124715) | Yes| New configuration.| - -**Example** - - ```js - class myAbility extends Ability { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - - -## Caller - -Implements sending of sequenceable data to the target ability when an ability (caller) invokes the target ability (callee). - - -## Caller.call - -call(method: string, data: rpc.Sequenceable): Promise<void>; - -Sends sequenceable data to the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**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.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return a response.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ // Custom sequenceable data structure - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; // Notification message string negotiated by the two abilities - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); // See the definition of Sequenceable. - caller.call(method, msg) - .then(() => { - console.log('Caller call() called'); - }).catch((e) => { - console.log('Caller call() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - - } - ``` - - -## Caller.callWithResult - -callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; - -Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**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.| - -**Return value** - - | 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{ - constructor(name, str) { - this.name = name; - this.str = str; - } - constructor() {} - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - let msg = new MyMessageAble(1, "world"); - caller.callWithResult(method, msg) - .then((data) => { - console.log('Caller callWithResult() called'); - let retmsg = new MyMessageAble(0, ""); - data.readSequenceable(retmsg); - }).catch((e) => { - console.log('Caller callWithResult() catch error ' + e); - }); - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Caller.release - -release(): void; - -Releases the caller interface of the target ability. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.release(); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Caller.onRelease - -onRelease(callback: OnReleaseCallBack): void; - -Registers a callback that is invoked when the Stub on the target ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var caller; - export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - this.context.startAbilityByCall({ - bundleName: "com.example.myservice", - abilityName: "com.example.myservice.MainAbility", - deviceId: "" - }).then((obj) => { - caller = obj; - try { - caller.onRelease((str) => { - console.log(' Caller OnRelease CallBack is called ' + str); - }); - } catch (e) { - console.log('Caller Release error ' + e); - } - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); - } - } - ``` - - -## Callee - -Implements callbacks for caller notification registration and unregistration. - - -## Callee.on - -on(method: string, callback: CaleeCallBack): void; - -Registers a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Notification message string negotiated between the two abilities.| - | callback | CaleeCallBack | 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** - - ```js - import Ability from '@ohos.application.Ability'; - class MyMessageAble{ - constructor(name, str) { - this.name = name; - this.str = str; - } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); - console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); - console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); - return true; - } - }; - var method = 'call_Function'; - function funcCallBack(pdata) { - console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble(0, ""); - pdata.readSequenceable(msg); - return new MyMessageAble(10, "Callee test"); - } - export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.on(method, funcCallBack); - } - } - ``` - - -## Callee.off - -off(method: string): void; - -Unregisters a caller notification callback, which is invoked when the target ability registers a function. - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | method | string | Yes| Registered notification message string.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - var method = 'call_Function'; - export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log('Callee onCreate is called'); - this.callee.off(method); - } - } - ``` - -## OnReleaseCallBack - -(msg: string): void; - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (msg: string) | function | Yes| No| Prototype of the listener function interface registered by the caller.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | - - - ## CaleeCallBack - -(indata: rpc.MessageParcel): rpc.Sequenceable; - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the message listener function interface registered by the callee.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore | diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md deleted file mode 100644 index 4e00922ba0efccb12fe03fb7fc0c46a607b2f4d3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ /dev/null @@ -1,56 +0,0 @@ -# AbilityConstant - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 9. - - -Provides parameters related to ability launch. - - -## Modules to Import - - -```js -import AbilityConstant from '@ohos.application.AbilityConstant'; -``` - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - -## AbilityConstant.LaunchReason - -Enumerates ability launch reasons. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| START_ABILITY | 1 | Ability startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| CALL | 2 | Call.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| CONTINUATION | 3 | Ability continuation.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityConstant.LaunchReason - -Enumerates reasons for the last exit. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| UNKNOWN | 0 | Unknown reason.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| NORMAL | 2 | Normal status.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## AbilityConstant.OnContinueResult - -Enumerates ability continuation results. - -| Name | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| AGREE | 0 | Continuation agreed.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| REJECT | 1 | Continuation denied.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| -| MISMATCH | 2 | Mismatch.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md new file mode 100644 index 0000000000000000000000000000000000000000..0c8f62fcfb300c152b632fa434cd28e603a2c835 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md @@ -0,0 +1,239 @@ +# AbilityDelegator + +> **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 + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityDelegator + +### startAbility + +startAbility(want: Want, callback: AsyncCallback\): void + +Starts an ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------ | +| want | [Want](js-apis-featureAbility.md#Want) | Yes | **Want** parameter for starting the ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +var abilityDelegator; +var want = { + bundleName: "bundleName", + abilityName: "abilityName" +}; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.startAbility(want, (err, data) => { + console.info("startAbility callback"); +}); +``` + + + +### startAbility + +startAbility(want: Want): Promise\ + +Starts an ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | --------------- | +| want | [Want](js-apis-featureAbility.md#Want) | Yes | **Want** parameter for starting the ability.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; +var want = { + bundleName: "bundleName", + abilityName: "abilityName" +}; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.startAbility(want).then((data: any) => { + console.info("startAbility promise"); +}); +``` + +### print + +print(msg: string, callback: AsyncCallback\): void + +Prints log information to the unit test console. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------ | +| msg | string | Yes | Log string. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +var abilityDelegator; +var msg = "msg"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.print(msg, (err) => { + console.info("print callback"); +}); +``` + + + +### print + +print(msg: string): Promise\ + +Prints log information to the unit test console. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| msg | string | Yes | Log string.| + +**Return value** + +| Type | Description | +| -------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var abilityDelegator; +var msg = "msg"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.print(msg).then(() => { + console.info("print promise"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, callback: AsyncCallback\): void + +Executes a shell command. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| cmd | string | Yes | Shell command string. | +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, (err, data) => { + console.info("executeShellCommand callback"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void + +Executes a shell command with the timeout period specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ----------------------------- | +| cmd | string | Yes | Shell command string. | +| timeoutSecs | number | Yes | Command timeout period, in seconds.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object. | + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; +var timeout = 100; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, timeout, (err, data) => { + console.info("executeShellCommand callback"); +}); +``` + + + +### executeShellCommand + +executeShellCommand(cmd: string, timeoutSecs: number): Promise\ + +Executes a shell command with the timeout period specified. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------------- | +| cmd | string | Yes | Shell command string. | +| timeoutSecs | number | No | Command timeout period, in seconds.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| Promise\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| + +**Example** + +```js +var abilityDelegator; +var cmd = "cmd"; +var timeout = 100; + +abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { + console.info("executeShellCommand promise"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md new file mode 100644 index 0000000000000000000000000000000000000000..36a133137f300949b710e0f1e9d246528f0c25d3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md @@ -0,0 +1,24 @@ +# AbilityDelegatorArgs + +> **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 + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## AbilityDelegatorArgs + +Describes the test parameters. + +| Name | Type | Readable| Writable| Description | +| ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Yes | Bundle name of the application to test.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| testCaseNames | string | Yes | Yes | Test case names.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| testRunnerClassName | string | Yes | Yes | Names of the test executors that execute the test cases.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilitystage.md deleted file mode 100644 index 4f04fa0a109852d619697b1d4cab23382d086477..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ /dev/null @@ -1,99 +0,0 @@ -# AbilityStage - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Runtime class for HAP files. It provides APIs to notify you when a HAP file starts loading. You can then initialize the HAP file, for example, pre-load resources and create threads. - - -## Modules to Import - - -```js -import AbilityStage from '@ohos.application.AbilityStage'; -``` - -## AbilityStage.onCreate - -onCreate(): void - -Called when the application is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage.onCreate is called") - } - } - ``` - - -## AbilityStage.onAcceptWant - -onAcceptWant(want: Want): string; - -Called when a specified ability is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onAcceptWant(want) { - console.log("MyAbilityStage.onAcceptWant called"); - return "com.example.test"; - } - } - ``` - - -## AbilityStage.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the global configuration is updated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| - -**Example** - - ```js - class MyAbilityStage extends AbilityStage { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, language:' + config.language); - } - } - ``` -## AbilityStage.context - -Describes the configuration information about the context. - -| Name | Type | Description | -| ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-featureAbility.md) | Called when initialization is performed during ability startup.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md deleted file mode 100644 index eaf0b4ceca53a65a4f8bb70ff4d181284271ea76..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ /dev/null @@ -1,80 +0,0 @@ -# Context - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Provides the context for running code, including **applicationInfo** and **resourceManager**. - - -## Usage - - -You must extend **AbilityContext** to implement this module. - - -## Attributes -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| resourceManager | ResourceManager | Yes| No| **ResourceManager** object.| -| applicationInfo | ApplicationInfo | Yes| No| Information about the application.| -| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.| -| tempDir | string | Yes| No| Temporary file directory of the application.| -| filesDir | string | Yes| No| File directory of the application on the internal storage.| -| databaseDir | string | Yes| No| Storage directory of local data.| -| storageDir | string | Yes| No| Storage directory of lightweight data.| -| bundleCodeDir | string | Yes| No| Application installation path.| -| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| -| eventHub | [EventHub](js-apis-eventhub.md) | Yes| No| Event hub information.| - - -## Context.createBundleContext - -createBundleContext(bundleName: string): Context; - -Creates an application context. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context of the application created.| - -**Example** - - ```js - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - ``` - - -## Context.getApplicationContext - -getApplicationContext(): Context; - -Obtains the context of this application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context obtained.| - -**Example** - - ```js - // This part is mandatory. - let context = this.context.getApplicationContext(); - ``` diff --git a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md new file mode 100644 index 0000000000000000000000000000000000000000..6a956dad3ed19cbaa506302cb19227a441af5d0c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md @@ -0,0 +1,22 @@ +# ShellCmdResult + +> **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 + +```js +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' +``` + + + +## ShellCmdResult + +Describes the shell command execution result. + +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| stdResult | string | Yes | Yes | Standard output content.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| +| exitCode | number | Yes | Yes | Result code.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index a803daded9f58c1e1e53d4e464807d478a76bcc5..04e994eb648946046319cdd55b25a908362c7b0d 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -1,7 +1,7 @@ # appManager > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. Implements application management. @@ -9,7 +9,7 @@ Implements application management. ## Modules to Import - + ```js import app from '@ohos.application.appManager'; ``` @@ -77,18 +77,16 @@ Checks whether this application is running in a RAM constrained device. This API | Type| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return whether the the application is running in a RAM constrained device. If the the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | Promise<boolean> | Promise used to return whether the application is running in a RAM constrained device. If the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js - IsRamConstrainedDevicePromise(){ app.isRamConstrainedDevicePromise().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); - } ``` ## appManager.isRamConstrainedDevice @@ -103,17 +101,15 @@ Checks whether this application is running in a RAM constrained device. This API | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the the application is running in a RAM constrained device. If the the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running in a RAM constrained device. If the application is running in a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** ```js - IsRamConstrainedDeviceCallBack(){ app.isRamConstrainedDevicePromise((err, data) => { console.log('startAbility result failed:' + JSON.stringify(err)); console.log('startAbility result success:' + JSON.stringify(data)); }) - } ``` ## appManager.getAppMemorySize @@ -133,13 +129,11 @@ Obtains the memory size of this application. This API uses a promise to return t **Example** ```js - GetAppMemorySize(){ app.getAppMemorySize().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); - } ``` ## appManager.getAppMemorySize @@ -159,10 +153,65 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Example** ```js - GetAppMemorySizeCallBack(){ app.getAppMemorySize((err, data) => { console.log('startAbility result failed :' + JSON.stringify(err)); console.log('startAbility result success:' + JSON.stringify(data)); }) - } ``` +## appManager.getProcessRunningInfos8+ + +getProcessRunningInfos(): Promise>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise> | Promise used to return the process information.| + +**Example** + + ```js + app.GetProcessRunningInfos().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInfos8+ + +getProcessRunningInfos(callback: AsyncCallback>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback> | No| Callback used to return the process information.| + +**Example** + + ```js + app.GetProcessRunningInfos((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + +## ProcessRunningInfo + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| 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 process.| diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index e3ba42ce0955682922d7d36766a8a4544d111b83..691dea9eaed2f4ec4cfbafc22ffb8b547c48cfbc 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -264,6 +264,7 @@ arrayList.removeByRange(2, 6); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void @@ -301,6 +302,7 @@ arrayList.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void @@ -335,6 +337,7 @@ arrayList.forEach((value, index) => { ``` ### sort + sort(comparator?: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -366,6 +369,7 @@ arrayList.sort(); ``` ### subArrayList + subArrayList(fromIndex: number, toIndex: number): ArrayList<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **ArrayList** instance. @@ -397,6 +401,7 @@ let result3 = arrayList.subArrayList(2, 6); ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -413,6 +418,7 @@ arrayList.clear(); ``` ### clone + clone(): ArrayList<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. @@ -436,6 +442,7 @@ let result = arrayList.clone(); ``` ### getCapacity + getCapacity(): number Obtains the capacity of this container. @@ -458,6 +465,7 @@ let result = arrayList.getCapacity(); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -480,6 +488,7 @@ let result = arrayList.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -502,6 +511,7 @@ let result = arrayList.isEmpty(); ``` ### increaseCapacityTo + increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. @@ -525,6 +535,7 @@ arrayList.increaseCapacityTo(8); ``` ### trimToCurrentLength + trimToCurrentLength(): void Trims the capacity of this container to its current length. diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 7787a551160a0afdb84af786ef1efd133a078bf6..da5d93ba2a83e3b760fcffe02c8bc2e555243258 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -22,15 +22,15 @@ The default duration of delayed suspension is 180000 when the battery level is h **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ---------------------------------------- | -| reason | string | Yes | Reason for delayed transition to the suspended state. | -| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | ------------------------------ | +| reason | string | Yes | Reason for delayed transition to the suspended state. | +| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| **Return value** -| Type | Description | -| ------------------------------------- | --------------------------------------- | -| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay. | +| Type | Description | +| ------------------------------------- | --------- | +| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| **Example** ```js @@ -50,10 +50,10 @@ Obtains the remaining duration before the application is suspended. This API use **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | --------------------------- | --------- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds. | +| Name | Type | Mandatory | Description | +| --------- | --------------------------- | ---- | ---------------------------------------- | +| requestId | number | Yes | ID of the suspension delay request. | +| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.| **Example** @@ -78,14 +78,14 @@ Obtains the remaining duration before the application is suspended. This API use **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ----------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| requestId | number | Yes | ID of the suspension delay request.| **Return value** -| Type | Description | +| Type | Description | | --------------------- | ---------------------------------------- | -| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds. | +| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| **Example** ```js @@ -107,9 +107,9 @@ Cancels the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | --------- | ----------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------- | +| requestId | number | Yes | ID of the suspension delay request.| **Example** ```js @@ -128,12 +128,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | --------- | ---------------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ------------------------ | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -180,15 +180,15 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | --------- | ---------------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page when a continuous task notification is clicked. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** -| Type | Description | -| -------------- | ---------------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result. | **Example** @@ -229,10 +229,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------- | --------- | ----------------------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -260,13 +260,13 @@ Requests to cancel a continuous task. This API uses a promise to return the resu **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------- | --------- | -------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | +| Name | Type | Mandatory | Description | +| ------- | ----------------------------- | ---- | --------- | +| context | [Context](js-apis-Context.md) | Yes | Application context. | **Return value** -| Type | Description | -| -------------- | ---------------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result. | **Example** @@ -288,24 +288,24 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask -| Name | Type | Mandatory | Description | -| --------------- | ------ | --------- | ---------------------------------------- | -| requestId | number | Yes | ID of the suspension delay request. | -| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level. | +| Name | Type | Mandatory | Description | +| --------------- | ------ | ---- | ---------------------------------------- | +| requestId | number | Yes | ID of the suspension delay request. | +| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| ## BackgroundMode8+ **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Value | Description | -| ----------------------- | ----- | -------------------------------- | -| DATA_TRANSFER | 1 | Data transfer. | -| AUDIO_PLAYBACK | 2 | Audio playback. | -| AUDIO_RECORDING | 3 | Audio recording. | -| LOCATION | 4 | Positioning and navigation. | -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related (reserved). | -| VOIP | 8 | Voice and video call (reserved). | -| TASK_KEEPING | 9 | Computing task. | +| Name | Value| Description | +| ----------------------- | ------ | ---------------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related (reserved). | +| VOIP | 8 | Voice and video call (reserved). | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices).| diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index f74e565b2d2dda5aa0421d5a7629e5fbee4dbdd5..947a2723837dc43af7a7b4473538931c1b17e009 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. +> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. ## Modules to Import @@ -216,9 +216,9 @@ Obtains the connection status of a profile. **Return value** -| Type | Description | -| ---------------------------------------- | ------------- | -| [ProfileConnectionState](#ProfileConnectionState) | Profile connection state obtained.| +| Type | Description | +| ------------------------------------------------- | ------------------- | +| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained.| **Example** @@ -1235,14 +1235,14 @@ Obtains the connection status of the profile. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ------- | -| device | string | Yes | Address of the remote device.| +| device | string | Yes | Address of the target device.| | **Return value** -| | | -| ---------------------------------------- | --------------- | -| Type | Description | +| | | +| ------------------------------------------------- | ----------------------- | +| Type | Description | | [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. | @@ -1904,7 +1904,7 @@ Subscribes to the characteristic write request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------------------------- | | type | string | Yes | Event type. The value **characteristicWrite** indicates a characteristic write request event.| -| callback | Callback<[DescriptorWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | +| callback | Callback<[CharacteristicWriteReq](#descriptorwritereq)> | Yes | Callback invoked to return a characteristic write request from the GATT client. | **Return value** @@ -1984,7 +1984,7 @@ Subscribes to the descriptor read request events. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------- | | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| -| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request event from the GATT client. | +| callback | Callback<[DescriptorReadReq](#descriptorreadreq)> | Yes | Callback invoked to return a descriptor read request from the GATT client. | **Return value** @@ -3116,10 +3116,10 @@ Defines the parameters of **BLEConnectChangedState**. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Type | Readable | Writable | Description | -| -------- | ---------------------------------------- | ---- | ---- | -------------------------------- | -| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| -| state | [ProfileConnectionState](#profileconnectionState) | Yes | Yes | BLE connection state. | +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | --------------------------------------------- | +| deviceId | string | Yes | No | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | Yes | BLE connection state. | ## ProfileConnectionState @@ -3285,10 +3285,10 @@ Defines the profile state change parameters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Type | Readable | Writable | Description | -| -------- | ---------------------------------------- | ---- | ---- | ------------------- | -| deviceId | string | Yes | No | Address of a Bluetooth device. | -| state | [ProfileConnectionState](#ProfileConnectionState) | Yes | No | Profile connection state of the device.| +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------------------- | ---- | ---- | ------------------------------- | +| deviceId | string | Yes | No | Address of a Bluetooth device. | +| state | [ProfileConnectionState](#profileconnectionstate) | Yes | No | Profile connection state of the device.| ## DeviceClass8+ diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index a87d894778f20df2e419dc14c4ce0e88460681bc..8f93a1e5d0e78f0cc31ccd1758114950a6852662 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,6 +1,6 @@ # CommonEvent -> **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -9,62 +9,63 @@ | ------------ | ------------------ | ---------------------- | | COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | | COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | N/A | -| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | N/A | -| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | N/A | -| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | N/A | -| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | N/A | -| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | N/A | -| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | N/A | -| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | N/A | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | N/A | -| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | N/A | -| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | N/A | -| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | N/A | -| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | N/A | -| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | N/A | -| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | N/A | -| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | N/A | -| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | N/A | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | N/A | -| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | N/A | -| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | N/A | -| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | N/A | -| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | N/A | -| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | N/A | -| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | N/A | -| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | N/A | -| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | N/A | -| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | N/A | -| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | N/A | -| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | N/A | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | N/A | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | N/A | -| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | N/A | -| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | N/A | -| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | N/A | -| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | N/A | -| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | N/A | -| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | N/A | -| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | N/A | -| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | N/A | -| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | N/A | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | | COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | N/A | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | | COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | N/A | -| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | N/A | -| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | N/A | -| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | N/A | -| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | N/A | -| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | N/A | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | +| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | +| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | +| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | +| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | | COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | | COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | N/A | -| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | N/A | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | | COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | | COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO | | COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | @@ -82,26 +83,26 @@ | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | N/A | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | N/A | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | N/A | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | N/A | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | | COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | N/A | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | | COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | @@ -111,34 +112,34 @@ | COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | | COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | N/A | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | | COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | | COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | -| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | N/A | -| COMMON_EVENT_CHARGING | usual.event.CHARGING | N/A | -| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | N/A | -| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | N/A | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | | COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | | COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | | COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | | COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | -| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | N/A | -| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | N/A | -| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | N/A | -| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | N/A | -| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | N/A | -| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | N/A | -| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | N/A | -| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | N/A | -| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | N/A | -| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | N/A | -| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | N/A | -| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | N/A | -| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | N/A | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | N/A | -| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | N/A | -| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | N/A | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | | COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| | COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| | COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| @@ -153,7 +154,7 @@ | COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | N/A | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | | COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | ## Modules to Import @@ -174,8 +175,8 @@ Publishes a common event. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | -------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result.| +| event | Read only | string | Yes | Name of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -207,9 +208,9 @@ Publishes a common event with given attributes. This API uses a callback to retu | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| options | Read-only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -249,9 +250,9 @@ Publishes a common event to a specific user. This API uses a callback to return | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | -------------------- | ---- | ---------------------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| userId | Read-only | number | Yes | User ID.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| userId | Read only | number | Yes | User ID.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -286,10 +287,10 @@ Publishes a common event with given attributes to a specific user. This API uses | Name | Readable/Writable| Type | Mandatory| Description | | -------- | -------- | ---------------------- | ---- | ---------------------- | -| event | Read-only | string | Yes | Name of the common event to publish. | -| userId | Read-only| number | Yes| User ID.| -| options | Read-only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result. | +| event | Read only | string | Yes | Name of the common event to publish. | +| userId | Read only| number | Yes| User ID.| +| options | Read only | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | Read only | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -331,8 +332,8 @@ Creates a subscriber. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ------------- | -------- | ------------------------------------------------------------ | ---- | -------------------------- | -| subscribeInfo | Read-only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | -| callback | Read-only | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| +| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | Read only | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| **Example** @@ -340,12 +341,12 @@ Creates a subscriber. This API uses a callback to return the result. ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); @@ -373,7 +374,7 @@ Creates a subscriber. This API uses a promise to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ------------- | -------- | ----------------------------------------------------- | ---- | -------------- | -| subscribeInfo | Read-only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| +| subscribeInfo | Read only | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| **Return value** | Type | Description | @@ -385,7 +386,7 @@ Creates a subscriber. This API uses a promise to return the result. ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; @@ -413,20 +414,20 @@ Subscribes to common events. This API uses a callback to return the result. | Name | Readable/Writable| Type | Mandatory| Description | | ---------- | -------- | --------------------------------------------------- | ---- | -------------------------------- | -| subscriber | Read-only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | -| callback | Read-only | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| +| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | Read only | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| **Example** ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for common event subscription +// Callback for common event subscription. function SubscribeCallBack(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); @@ -435,7 +436,7 @@ function SubscribeCallBack(err, data) { } } -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); @@ -451,7 +452,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); ``` - + ## CommonEvent.unsubscribe @@ -463,22 +464,22 @@ Unsubscribes from common events. This API uses a callback to return the result. **Parameters** -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | --------------------- | ---- | ------------------------ | -| subscriber | Read-only | CommonEventSubscriber | Yes | Subscriber object. | -| callback | Read-only | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Readable/Writable| Type | Mandatory| Description | +| ---------- | -------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | Read only | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | Read only | AsyncCallback\ | No | Callback used to return the result.| **Example** ```js var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. -// Subscriber information +// Subscriber information. var subscribeInfo = { events: ["event"] }; -// Callback for common event subscription +// Callback for common event subscription. function SubscribeCallBack(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); @@ -487,7 +488,7 @@ function SubscribeCallBack(err, data) { } } -// Callback for subscriber creation +// Callback for subscriber creation. function CreateSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); @@ -499,7 +500,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { } } -// Callback for common event unsubscription +// Callback for common event unsubscription. function UnsubscribeCallBack(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); @@ -515,43 +516,6 @@ CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); ``` -## CommonEventPublishData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| --------------------- | -------- | -------------------- | ---- | ---------------------------- | -| bundleName | Read-only | string | No | Bundle name. | -| code | Read-only | number | No | Result code of the common event. | -| data | Read-only | string | No | Custom result data of the common event.| -| subscriberPermissions | Read-only | Array\ | No | Permissions required for subscribers to receive the common event. | -| isOrdered | Read-only | boolean | No | Whether the common event is an ordered one. | -| parameters | Read-only | {[key: string]: any} | No | Additional information about the common event. | - -## CommonEventSubscribeInfo - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | -| events | Read-only | Array\ | Yes | Common events to subscribe to. | -| publisherPermission | Read-only | string | No | Permission required for the publisher. | -| publisherDeviceId | Read-only | string | No | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Read-only | number | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Read-only | number | No | Subscriber priority. The value ranges from -100 to 1000. | - -## CommonEventData - -**System capability**: SystemCapability.Notification.CommonEvent - -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------- | -| event | Read-only | string | Yes | Name of the common event to subscribe to. | -| bundleName | Read-only | string | No | Bundle name. | -| code | Read-only | number | No | Result code of the common event, which is used to transfer data of the int type. | -| data | Read-only | string | No | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Read-only | {[key: string]: any} | No | Additional information about the common event. | - ## CommonEventSubscriber ### getCode @@ -573,8 +537,7 @@ Obtains the result code of this common event. This API uses a callback to return ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event -getCode() { +// Callback for result code obtaining of an ordered common event. function getCodeCallback(err, Code) { if (err.code) { console.error("getCode failed " + JSON.stringify(err)); @@ -631,7 +594,7 @@ Sets the result code for this common event. This API uses a callback to return t ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result code setting of an ordered common event. function setCodeCallback(err) { if (err.code) { console.error("setCode failed " + JSON.stringify(err)); @@ -654,7 +617,13 @@ Sets the result code for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | Yes | Callback used to return the result code.| +| code | number | Yes | Result code of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result code.| **Example** @@ -680,14 +649,14 @@ Obtains the result data of this common event. This API uses a callback to return | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result data.| +| callback | AsyncCallback\ | Yes | Result data of the common event.| **Example** ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result data obtaining of an ordered common event. function getDataCallback(err, Data) { if (err.code) { console.error("getData failed " + JSON.stringify(err)); @@ -710,7 +679,7 @@ Obtains the result data of this common event. This API uses a promise to return | Type | Description | | ---------------- | ------------------ | -| Promise\ | Promise used to return the result data.| +| Promise\ | Result data of the common event.| **Example** @@ -767,7 +736,13 @@ Sets the result data for this common event. This API uses a promise to return th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| data | string | Yes | Callback used to return the result data.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result data.| **Example** @@ -802,7 +777,7 @@ Sets the result code and result data for this common event. This API uses a call ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for result code and result data setting of an ordered common event. function setCodeDataCallback(err) { if (err.code) { console.error("setCodeAndData failed " + JSON.stringify(err)); @@ -826,7 +801,13 @@ Sets the result code and result data for this common event. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | code | number | Yes | Result code of the common event.| -| data | string | Yes | Callback used to return the result data.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -859,7 +840,7 @@ Checks whether this common event is an ordered one. This API uses a callback to ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for checking whether the current common event is an ordered one. function isOrderedCallback(err, isOrdered) { if (err.code) { console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); @@ -896,6 +877,62 @@ subscriber.isOrderedCommonEvent().then((isOrdered) => { }); ``` +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is a sticky one. This API uses a callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```js +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +Checks whether this common event is a sticky one. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Returns **true** if the common event is a sticky one; returns **false** otherwise.| + +**Example** + +```js +var subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + ### abortCommonEvent abortCommonEvent(callback: AsyncCallback\): void @@ -915,7 +952,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for common event aborting. function abortCallback(err) { if (err.code) { console.error("abortCommonEvent failed " + JSON.stringify(err)); @@ -934,6 +971,12 @@ Aborts this common event. After the abort, the common event is not sent to the n **System capability**: SystemCapability.Notification.CommonEvent +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js @@ -965,7 +1008,7 @@ Clears the aborted state of this common event. This API takes effect only for or ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for clearing the aborted state of the current common event. function clearAbortCallback(err) { if (err.code) { console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); @@ -984,6 +1027,12 @@ Clears the aborted state of this common event. This API takes effect only for or **System capability**: SystemCapability.Notification.CommonEvent +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js @@ -1015,7 +1064,7 @@ Checks whether this common event is in the aborted state. This API takes effect ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for checking whether the current common event is in the aborted state. function getAbortCallback(err, AbortCommonEvent) { if (err.code) { console.error("getAbortCommonEvent failed " + JSON.stringify(err)); @@ -1028,7 +1077,7 @@ subscriber.getAbortCommonEvent(getAbortCallback); ### getAbortCommonEvent -getAbortCommonEvent(): Promise\ +getAbortCommonEvent(): Promise\ Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. @@ -1064,14 +1113,14 @@ Obtains the subscriber information. This API uses a callback to return the resul | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Promise used to return the subscriber information.| **Example** ```js var subscriber; // Subscriber object successfully created. -// Callback for result data setting of an ordered common event +// Callback for subscriber information obtaining. function getSubscribeInfoCallback(err, SubscribeInfo) { if (err.code) { console.error("getSubscribeInfo failed " + JSON.stringify(err)); @@ -1107,3 +1156,42 @@ subscriber.getSubscribeInfo().then((SubscribeInfo) => { console.error("getSubscribeInfo failed " + JSON.stringify(err)); }); ``` + +## CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------- | +| event | Read only | string | Yes | Name of the common event that is being received. | +| bundleName | Read only | string | No | Bundle name. | +| code | Read only | number | No | Result code of the common event, which is used to transfer data of the int type. | +| data | Read only | string | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | + + +## CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| --------------------- | -------- | -------------------- | ---- | ---------------------------- | +| bundleName | Read only | string | No | Bundle name. | +| code | Read only | number | No | Result code of the common event. | +| data | Read only | string | No | Custom result data of the common event.| +| subscriberPermissions | Read only | Array\ | No | Permissions required for subscribers to receive the common event. | +| isOrdered | Read only | boolean | No | Whether the common event is an ordered one. | +| isSticky | Read only | boolean | No | Whether the common event is a sticky one. | +| parameters | Read only | {[key: string]: any} | No | Additional information about the common event. | + +## CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Readable/Writable| Type | Mandatory| Description | +| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | +| events | Read only | Array\ | Yes | Name of the common event to publish. | +| publisherPermission | Read only | string | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | Read only | string | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | Read only | number | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | Read only | number | No | Subscriber priority. The value ranges from -100 to 1000. | diff --git a/en/application-dev/reference/apis/js-apis-configuration.md b/en/application-dev/reference/apis/js-apis-configuration.md index 50803fb4587f9e8ec8e31f447a90eeccdd44780c..be8b93df49a6e3530d0e4d0afce852eade8033d2 100644 --- a/en/application-dev/reference/apis/js-apis-configuration.md +++ b/en/application-dev/reference/apis/js-apis-configuration.md @@ -9,7 +9,7 @@ Provides the configuration for the environment where the ability is running. ## Modules to Import - + ```js import Configuration from '@ohos.application.Configuration'; ``` @@ -19,10 +19,7 @@ import Configuration from '@ohos.application.Configuration'; **System capability**: SystemCapability.Ability.AbilityBase - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| Yes| Language of the application.| -| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| -| direction9+ | Direction | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| -| screenDensity9+ | ScreenDensity | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| -| displayId9+ | number | Yes| No| ID of the display where the application is located.| +| language | string | Yes| Yes| Language of the application.| +| colorMode | [ColorMode](js-apis-configurationconstant.md) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| diff --git a/en/application-dev/reference/apis/js-apis-configurationconstant.md b/en/application-dev/reference/apis/js-apis-configurationconstant.md index 55f42b926d4bfcbb4b07a48185611b22a92cbc32..541b665c730503ffbf072cf437c7f8e8cb2dfd79 100644 --- a/en/application-dev/reference/apis/js-apis-configurationconstant.md +++ b/en/application-dev/reference/apis/js-apis-configurationconstant.md @@ -9,7 +9,7 @@ Defines enumerated values of the configuration for the environment where the abi ## Modules to Import - + ```js import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; ``` @@ -27,50 +27,8 @@ ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT **System capability**: SystemCapability.Ability.AbilityBase -| Name| Value| Description| -| -------- | -------- | -------- | -| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| -| COLOR_MODE_DARK | 0 | Dark mode.| -| COLOR_MODE_LIGHT | 1 | Light mode.| - - -## ConfigurationConstant.Direction - -The value is obtained through the **ConfigurationConstant.Direction** API. - -**Example** - -``` -ConfigurationConstant.Direction.DIRECTION_VERTICAL -``` - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| -| -------- | -------- | -------- | -| DIRECTION_NOT_SET9+ | -1 | Unspecified direction.| -| DIRECTION_VERTICAL9+ | 0 | Vertical direction.| -| DIRECTION_HORIZONTAL9+ | 1 | Horizontal direction.| - - -## ConfigurationConstant.ScreenDensity - -The value is obtained through the **ConfigurationConstant.ScreenDensity** API. - -**Example** - -``` -ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_NOT_SET -``` - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name| Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| SCREEN_DENSITY_NOT_SET9+ | 0 | Unspecified screen resolution.| -| SCREEN_DENSITY_SDPI9+ | 120 | The screen resolution is sdpi.| -| SCREEN_DENSITY_MDPI9+ | 160 | The screen resolution is mdpi.| -| SCREEN_DENSITY_LDPI9+ | 240 | The screen resolution is ldpi.| -| SCREEN_DENSITY_XLDPI9+ | 320 | The screen resolution is xldpi.| -| SCREEN_DENSITY_XXLDPI9+ | 480 | The screen resolution is xxldpi.| -| SCREEN_DENSITY_XXXLDPI9+ | 640 | The screen resolution is xxxldpi.| +| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| +| COLOR_MODE_DARK | 0 | Dark mode.| +| COLOR_MODE_LIGHT | 1 | Light mode.| diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md new file mode 100644 index 0000000000000000000000000000000000000000..5e76a594771be99634ac1cfd7e3b7089b8a58ba3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -0,0 +1,223 @@ +# Active Tag + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**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 + +``` +import connectedTag from '@ohos.connectedTag'; +``` + + +## connectedTag.init + +init(): boolean + +Initializes the active tag chip. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| + + +## connectedTag.uninit + +uninit(): boolean + +Uninitializes the active tag resources. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## connectedTag.readNdefTag + +readNdefTag(): Promise<string> + +Reads the content of this active tag. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<string> | Promise used to return the content of the active tag.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.readNdefTag().then(result => { + console.log("promise recv ndef response: " + result); + }); + ``` + +## connectedTag.readNdefTag + +readNdefTag(callback: AsyncCallback<string>): void + +Reads the content of this active tag. This method uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.readNdefTag(result => { + console.log("callback recv ndef response: " + result); + }); + ``` + +## connectedTag.writeNdefTag + +writeNdefTag(data: string): Promise<void> + +Writes data to this active tag. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +- Return value + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result. This method returns no value.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + writeNdefTag.write("010203") + .then((value) => { + // Data is written to the tag. + console.log(`success to write event: ${value}`); + }).catch((err) => { + // Failed to write data to the tag. + console.error(`failed to write event because ${err.code}`); + }); + ``` + +## connectedTag.writeNdefTag + +writeNdefTag(data: string, callback: AsyncCallback<string>): void + +Writes data to this active tag. This method uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | data | string | Yes| Data to write. The maximum length is 1024 bytes.| + | callback | AsyncCallback<string> | Yes| Callback invoked to return the operation result.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + connectedTag.writeNdefTag("010203", (err, value) => { + if (err) { + // Failed to write data to the tag. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Data is written to the tag. + console.log(`success to write event: ${value}`); + }); + ``` + +## connectedTag.on('notify') + +on(type: "notify", callback: Callback<number>): void + +Registers the NFC field strength state events. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **notify**.| + | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| + +- Enumerates the field strength states. + | **Value**| **Description**| + | -------- | -------- | + | 0 | Field off. | + | 1 | Field on. | + + +## connectedTag.off('notify') + +off(type: "notify", callback?: Callback<number>): void + +Unregisters the NFC field strength state events. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.ConnectedTag + +- Parameters + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **notify**.| + | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +- Example + ``` + import connectedTag from '@ohos.connectedTag'; + + var NFC_RF_NOTIFY = "notify"; + + var recvNfcRfNotifyFunc = result => { + console.info("nfc rf receive state: " + result); + } + + // Register event + connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); + + // Unregister event + connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); + ``` + +## NfcRfType + +Enumerates the NFC states. + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| NFC_RF_LEAVE | 0 | Field off. | +| NFC_RF_ENTER | 1 | Field on. | diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 4045752d3f6cd83bcb09f939fc1670bd1f766a05..2f4b695a6c88c635d4a92cd1b58c617e47d2b5c2 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,1697 +1,813 @@ -# DataAbilityPredicates +# DataAbilityPredicates ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import + +## Modules to Import ``` import dataAbility from '@ohos.data.dataAbility' ``` -## System Capabilities -SystemCapability.DistributedDataManager.DataShare.Core - - -## dataAbility.createRdbPredicates - -createRdbPredicates\(name: string, dataAbilityPredicates: DataAbilityPredicates\): rdb.RdbPredicates - -Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

name

-

string

-

Yes

-

Table name in the RDB store.

-

dataAbilityPredicates

-

DataAbilityPredicates

-

Yes

-

DataAbilityPredicates object.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

rdb.RdbPredicates

-

RdbPredicates object created.

-
- -- Example - - ``` - let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() - dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) - let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) - ``` - - -## DataAbilityPredicates + + +## dataAbility.createRdbPredicates + + +createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates + + +Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Table name in the RDB store.| + | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object.| + +- Return value + | Type| Description| + | -------- | -------- | + | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| + +- Example: + ``` + let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() + dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) + let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) + ``` + + +## DataAbilityPredicates Provides predicates for implementing diverse query methods. -### equalTo - -equalTo\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value equal to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") - ``` - - -### notEqualTo - -notEqualTo\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value not equal to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notEqualTo("NAME", "lisi") - ``` - - -### beginWrap - -beginWrap\(\): DataAbilityPredicates - -Adds a left parenthesis to this **DataAbilityPredicates**. - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with a left parenthesis.

-
- -- Example - - ``` - let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") - .beginWrap() - .equalTo("AGE", 18) - .or() - .equalTo("SALARY", 200.5) - .endWrap() - ``` - - -### endWrap - -endWrap\(\): DataAbilityPredicates - -Adds a right parenthesis to this **DataAbilityPredicates**. - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with a right parenthesis.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "lisi") - .beginWrap() - .equalTo("AGE", 18) - .or() - .equalTo("SALARY", 200.5) - .endWrap() - ``` - - -### or - -or\(\): DataAbilityPredicates - -Adds the OR condition to this **DataAbilityPredicates**. - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object with the OR condition.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") - .or() - .equalTo("NAME", "Rose") - ``` - - -### and - -and\(\): DataAbilityPredicates - -Adds the AND condition to this **DataAbilityPredicates**. - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates with the AND condition.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") - .and() - .equalTo("SALARY", 200.5) - ``` - - -### contains - -contains\(field: string, value: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match a string containing the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.contains("NAME", "os") - ``` - - -### beginsWith - -beginsWith\(field: string, value: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match a string that starts with the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.beginsWith("NAME", "os") - ``` - - -### endsWith - -endsWith\(field: string, value: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match a string that ends with the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.endsWith("NAME", "se") - ``` - - -### isNull - -isNull\(field: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field whose value is **null**. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNull("NAME") - ``` - - -### isNotNull - -isNotNull\(field: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field whose value is not **null**. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.isNotNull("NAME") - ``` - - -### like - -like\(field: string, value: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match a string that is similar to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.like("NAME", "%os%") - ``` - - -### glob - -glob\(field: string, value: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the specified string. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

string

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.glob("NAME", "?h*g") - ``` - - -### between - -between\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value within the specified range. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

low

-

ValueType

-

Yes

-

Minimum value to match the DataAbilityPredicates.

-

high

-

ValueType

-

Yes

-

Maximum value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.between("AGE", 10, 50) - ``` - - -### notBetween - -notBetween\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value out of the specified range. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

low

-

ValueType

-

Yes

-

Minimum value to match the DataAbilityPredicates.

-

high

-

ValueType

-

Yes

-

Maximum value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notBetween("AGE", 10, 50) - ``` - - -### greaterThan - -greaterThan\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThan("AGE", 18) - ``` - - -### lessThan - -lessThan\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThan("AGE", 20) - ``` - - -### greaterThanOrEqualTo - -greaterThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.greaterThanOrEqualTo("AGE", 18) - ``` - - -### lessThanOrEqualTo - -lessThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

ValueType

-

Yes

-

Value to match the DataAbilityPredicates.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.lessThanOrEqualTo("AGE", 20) - ``` - - -### orderByAsc - -orderByAsc\(field: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the column with values sorted in ascending order. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the column sorted in the specified order.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByAsc("NAME") - ``` - - -### orderByDesc - -orderByDesc\(field: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the column with values sorted in descending order. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the column sorted in the specified order.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.orderByDesc("AGE") - ``` - - -### distinct - -distinct\(\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to filter out duplicate records. - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that can filter out duplicate records.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").distinct("NAME") - rdbStore.query(predicates, ["NAME"]) - ``` - - -### limitAs - -limitAs\(value: number\): DataAbilityPredicates - -Set the **DataAbilityPredicates** that specify the maximum number of records. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

value

-

number

-

Yes

-

Maximum number of records in a column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates that can be used to set the maximum number of records.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").limitAs(3) - ``` - - -### offsetAs - -offsetAs\(rowOffset: number\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to specify the start position of the returned result. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

rowOffset

-

number

-

Yes

-

Number of rows to offset from the beginning. The value is a positive integer.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that specifies the start position of the returned result.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Rose").offsetAs(3) - ``` - - -### groupBy - -groupBy\(fields: Array\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to group rows that have the same value into summary rows. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

fields

-

Array<string>

-

Yes

-

Names of columns grouped for querying data.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that groups rows that have the same value.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.groupBy(["AGE", "NAME"]) - ``` - - -### indexedBy - -indexedBy\(indexName: string\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to specify the index column. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

indexName

-

string

-

Yes

-

Name of the index column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityRdbPredicates object that specifies the index column.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.indexedBy("SALARY_INDEX") - ``` - - -### in - -in\(field: string, value: Array\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **Array** and value within the specified range. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

Array<ValueType>

-

Yes

-

Array of ValueType to match.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.in("AGE", [18, 20]) - ``` - - -### notIn - -notIn\(field: string, value: Array\): DataAbilityPredicates - -Sets the **DataAbilityPredicates** to match the field with data type **Array** and value out of the specified range. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

field

-

string

-

Yes

-

Column name in the database table.

-

value

-

Array<ValueType>

-

Yes

-

Array of ValueType to match.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

DataAbilityPredicates

-

DataAbilityPredicates object that matches the specified field.

-
- -- Example - - ``` - let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") - predicates.notIn("NAME", ["Lisa", "Rose"]) - ``` +### equalTo + + +equalTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + + +notEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + + +beginWrap(): DataAbilityPredicates + + +Adds a left parenthesis to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| + +- Example: + ``` + let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + + +endWrap(): DataAbilityPredicates + + +Adds a right parenthesis to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + + +or(): DataAbilityPredicates + + +Adds the OR condition to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + + +and(): DataAbilityPredicates + + +Adds the AND condition to this **DataAbilityPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + + +contains(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + + +beginsWith(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + + +endsWith(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + + +isNull(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + + +isNotNull(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + + +like(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + + +glob(field: string, value: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | string | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + + +between(field: string, low: ValueType, high: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + + +notBetween(field: string, low: ValueType, high: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | low | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| + | high | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + + +greaterThan(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + + +lessThan(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + + +greaterThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + + +lessThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | [ValueType](js-apis-data-rdb.md#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + + +orderByAsc(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + + +orderByDesc(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + + +distinct(): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let promiseDistinct = rdbStore.query(predicates, ["NAME"]) + promiseDistinct.then((resultSet) => { + console.log("distinct") + }).catch((err) => { + expect(null).assertFail(); + }) + ``` + + +### limitAs + + +limitAs(value: number): DataAbilityPredicates + + +Set a **DataAbilityPredicates** object to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | value | number | Yes| Maximum number of records.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + + +offsetAs(rowOffset: number): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + + +groupBy(fields: Array<string>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | fields | Array<string> | Yes| Names of columns to group.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + +### indexedBy + + +indexedBy(field: string): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to specify the index column. + + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | indexName | string | Yes| Name of the index column.| + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + + +in(field: string, value: Array<ValueType>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type Array and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](js-apis-data-rdb.md#valuetype)> | Yes| Array of **ValueType**s to match.| + + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + + +notIn(field: string, value: Array<ValueType>): DataAbilityPredicates + + +Sets a **DataAbilityPredicates** object to match the field with data type Array and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | field | string | Yes| Column name in the table.| + | value | Array<[ValueType](js-apis-data-rdb.md#valuetype)> | Yes| Array of **ValueType**s to match.| + + +- Return value + | Type| Description| + | -------- | -------- | + | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| + +- Example: + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index f30b388e0f16691c0f9d754abfa9c198975c2f15..ed0829f6f6789c2aac7180df3ba5bc0e1d6c275e 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,4 +1,4 @@ -# Distributed Object +# Distributed Data Object > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. @@ -17,16 +17,21 @@ import distributedObject from '@ohos.data.distributedDataObject' createDistributedObject(source: object): DistributedObject -Creates a **distributedObject** instance. You can specify the attribute of the instance in **source**. This method returns the **distributedObject** instance created. +Creates a distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | object | source | Yes| Attribute of the **distributedObject** instance to create.| + | source | object | Yes| Attribute of the distributed data object to create.| -- Example +**Return Value** + | Type| Description| + | -------- | -------- | + | [DistributedObject](#distributedobject) | Distributed data object created.| + +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' // Create a distributedObject instance. The attribute type of the object can be string, number, boolean, or Object. @@ -39,16 +44,16 @@ Creates a **distributedObject** instance. You can specify the attribute of the i genSessionId(): string -Creates a session ID randomly. +Creates a random session ID. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- Return value +**Return Value** | Type| Description| | -------- | -------- | | string | Session ID created.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var sessionId = distributedObject.genSessionId(); @@ -58,20 +63,29 @@ Creates a session ID randomly. ## DistributedObject Represents a **distributedObject** instance. + ### setSessionId setSessionId(sessionId?: string): boolean -Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. To remove a device from the distributed network, set this parameter to "" or leave it unspecified. If **true** is returned, the session ID is set successfully. +Sets a session ID for synchronization. Automatic synchronization is performed for multiple devices with the same session ID on a trusted network. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** -- **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed object on a trusted network.| + | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| + +**Return Value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | -- Example +**Example** + ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -87,17 +101,17 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void -Subscribes to the data changes of this distributed object. +Subscribes to the data changes of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data change events.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the data changes of the distributed object. In the callback, **sessionId** indicates the session ID of the distributed object, and **fields** indicates the attributes of the object.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the attributes of the distributed data object changed.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -116,18 +130,18 @@ Subscribes to the data changes of this distributed object. off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void -Unsubscribes from the data changes of this distributed object. +Unsubscribes from the data changes of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data change events.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback used to return changes of the distributed object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| + | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data change events.| + | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the attributes of the distributed data object changed.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -135,7 +149,7 @@ Unsubscribes from the data changes of this distributed object. g_object.on("change", function (sessionId, changeData) { console.info("change" + sessionId); }); - // Unsubscribe from the data change callback for the specified distributed object. + // Unsubscribe from the data change callback for the specified distributed data object. g_object.off("change", function (sessionId, changeData) { console.info("change" + sessionId); }); @@ -147,17 +161,19 @@ Unsubscribes from the data changes of this distributed object. on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' | 'offline' }>): void -Subscribes to the status changes (online or offline) of this distributed object. +Subscribes to the status changes (online or offline) of this distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is "status", which indicates the status (online or offline) change events.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status changes of the distributed object. In the callback, **sessionId** indicates the session ID of the distributed object, and **status** indicates the online or offline status of the distributed object.| + | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the online or offline status.
**sessionId** indicates the session ID of the distributed data object.
**networkId** indicates the network ID of the device.
**status** indicates the status, which can be online or offline.| + + -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, @@ -172,24 +188,24 @@ Subscribes to the status changes (online or offline) of this distributed object. off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' | 'offline' }>): void -Unsubscribes from the status (online or offline) changes of the distributed object. +Unsubscribes from the status (online or offline) changes of the distributed data object. -** System Capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject -- **Parameters** +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is "status", which indicates the status (online or offline) change events.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status changes. If this parameter is not specified, all the status change callbacks will be unregistered.| + | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status changes. If this parameter is not specified, all the status change callbacks will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| -- Example +**Example** ```js import distributedObject from '@ohos.data.distributedDataObject' g_object.on("status", function (sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; }); - // Unsubscribe from the status change callback for the specified distributed object. + // Unsubscribe from the status change callback for the specified distributed data object. g_object.off("status", function (sessionId, networkId, status) { this.response += "status changed " + sessionId + " " + status + " " + networkId; }); diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 6d92a418fadd6d56ca0520fbc3b32026a82c037c..dbc00546fef265fea63133cbf905bf862b866de4 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,7 +1,6 @@ # Relational Database -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,71 +11,75 @@ import data_rdb from '@ohos.data.rdb' ``` -## System Capabilities -SystemCapability.DistributedDataManager.RelationalStore.Core - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void -Obtains a relational database (RDB) store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result. +Obtains a relational database (RDB) store. This method uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| - | version | number | Yes| RDB store version.| - | callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example - ``` - import Ability from '@ohos.application.Ability' - import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - const STORE_CONFIG = { name: "RdbTest.db"} - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { - rdbStore.executeSql(SQL_CREATE_TABLE) - console.info(TAG + 'create table done.') - }) - } - ``` +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| +| version | number | Yes| RDB store version.| +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| + +**Example** + +``` +import data_rdb from '@ohos.data.rdb' +const STORE_CONFIG = { name: "RdbTest.db"} +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info('create table done.') +}) +``` ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> -Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result. +Obtains an RDB store. This method uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| - | version | number | Yes| RDB store version.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| +**Parameters** -- Example - ``` - import Ability from '@ohos.application.Ability' - import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - const STORE_CONFIG = { name: "RdbTest.db" } - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); - promise.then(async (rdbStore) => { - await rdbStore.executeSql(SQL_CREATE_TABLE, null) - }).catch((err) => { - expect(null).assertFail(); - }) - } - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| +| version | number | Yes| RDB store version.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| + +**Example** + +``` +import data_rdb from '@ohos.data.rdb' +const STORE_CONFIG = { name: "RdbTest.db" } +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promisegetRdb = data_rdb.getRdbStore(STORE_CONFIG, 1); +promisegetRdb.then(async (rdbStore) => { + let promiseExecSql = rdbStore.executeSql(SQL_CREATE_TABLE, null) + promiseExecSql.then(() => { + console.info('executeSql creat done.') + }).catch((err) => { + console.log("executeSql creat err.") + }) +}).catch((err) => { + console.log("getRdbStore err.") +}) +``` ## data_rdb.deleteRdbStore @@ -84,21 +87,21 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g Deletes an RDB store. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | name | string | Yes| Name of the RDB store to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| name | string | Yes| Name of the RDB store to delete.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` - import Ability from '@ohos.application.Ability' import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { - console.info(TAG + 'delete store done.')}) - } + data_rdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { + console.info('delete store done.') + }) ``` ## data_rdb.deleteRdbStore @@ -107,27 +110,28 @@ deleteRdbStore(context: Context, name: string): Promise<void> Deletes an RDB store. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | Context | Yes| Context of the app or functionality.| - | name | string | Yes| Name of the RDB store to delete.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result. If the RDB store is deleted, **true** will be returned. Otherwise, **false** will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context8+ | Context | Yes| Context of the app or functionality.| +| name | string | Yes| Name of the RDB store to delete.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - import Ability from '@ohos.application.Ability' import data_rdb from '@ohos.data.rdb' - export default class MainAbility extends Ability { - let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") - promise.then(()=>{ - console.info(TAG + 'delete store done.') - }) - } + let promisedeleteRdb = data_rdb.deleteRdbStore("RdbTest.db") + promisedeleteRdb.then(()=>{ + console.info('delete store done.') + }).catch((err) => { + console.log("deleteRdbStore err.") + }) ``` ## RdbPredicates @@ -142,55 +146,58 @@ constructor(name: string) A constructor used to create an **RdbPredicates** object. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Database table name.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database table name.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ``` -### inDevices +### inDevices8+ -inDevices(devices: Array): RdbPredicates; +inDevices(devices: Array<string>): RdbPredicates Specifies a remote device on the network during distributed database synchronization. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | devices | Array | Yes| ID of the remote device to specify.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| devices | Array<string> | Yes| ID of the remote device to specify.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicate.inDevices(['12345678abcde']) ``` -### inAllDevices +### inAllDevices8+ -inAllDevices(): RdbPredicates; +inAllDevices(): RdbPredicates Connects to all remote devices on the network during distributed database synchronization. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inAllDevices() @@ -203,19 +210,20 @@ equalTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -229,19 +237,20 @@ notEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notEqualTo("NAME", "lisi") @@ -255,13 +264,14 @@ beginWrap(): RdbPredicates Adds a left parenthesis to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -280,13 +290,14 @@ endWrap(): RdbPredicates Adds a right parenthesis to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -305,13 +316,14 @@ or(): RdbPredicates Adds the OR condition to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -327,13 +339,14 @@ and(): RdbPredicates Adds the AND condition to the **RdbPredicates**. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -344,24 +357,24 @@ Adds the AND condition to the **RdbPredicates**. ### contains -contains(field: string, value: string): RdbPredicat - +contains(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string containing the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.contains("NAME", "os") @@ -375,19 +388,20 @@ beginsWith(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that starts with the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.beginsWith("NAME", "os") @@ -401,19 +415,20 @@ endsWith(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that ends with the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.endsWith("NAME", "se") @@ -427,16 +442,17 @@ isNull(field: string): RdbPredicates Sets the **RdbPredicates** to match the field whose value is null. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| - Example ``` @@ -452,18 +468,19 @@ isNotNull(field: string): RdbPredicates Sets the **RdbPredicates** to match the field whose value is not null. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNotNull("NAME") @@ -477,19 +494,20 @@ like(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match a string that is similar to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.like("NAME", "%os%") @@ -503,19 +521,20 @@ glob(field: string, value: string): RdbPredicates Sets the **RdbPredicates** to match the specified string. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | string | Yes| Value to match the **RdbPredicates**.
Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. ***** indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.glob("NAME", "?h*g") @@ -529,20 +548,21 @@ between(field: string, low: ValueType, high: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.between("AGE", 10, 50) @@ -556,20 +576,21 @@ notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **RdbPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notBetween("AGE", 10, 50) @@ -578,24 +599,24 @@ Sets the **RdbPredicates** to match the field with data type **ValueType** and v ### greaterThan -greaterThan(field: string, value: ValueType): RdbPredicatesgr - +greaterThan(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThan("AGE", 18) @@ -609,19 +630,20 @@ lessThan(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThan("AGE", 20) @@ -636,19 +658,20 @@ greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThanOrEqualTo("AGE", 18) @@ -663,19 +686,20 @@ lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThanOrEqualTo("AGE", 20) @@ -690,18 +714,19 @@ orderByAsc(field: string): RdbPredicates Sets the **RdbPredicates** to match the column with values sorted in ascending order. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByAsc("NAME") @@ -716,18 +741,19 @@ orderByDesc(field: string): RdbPredicates Sets the **RdbPredicates** to match the column with values sorted in descending order. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByDesc("AGE") @@ -741,17 +767,24 @@ distinct(): RdbPredicates Sets the **RdbPredicates** to filter out duplicate records. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct("NAME") - rdbStore.query(predicates, ["NAME"]) + let promisequery = rdbStore.query(predicates, ["NAME"]) + promisequery.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("query err.") + }) ``` @@ -762,18 +795,19 @@ limitAs(value: number): RdbPredicates Sets the **RdbPredicates** to specify the maximum number of records. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").limitAs(3) @@ -787,18 +821,19 @@ offsetAs(rowOffset: number): RdbPredicates Sets the **RdbPredicates** to specify the start position of the returned result. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").offsetAs(3) @@ -812,18 +847,19 @@ groupBy(fields: Array<string>): RdbPredicates Sets the **RdbPredicates** to group rows that have the same value into summary rows. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.groupBy(["AGE", "NAME"]) @@ -832,23 +868,24 @@ Sets the **RdbPredicates** to group rows that have the same value into summary r ### indexedBy -indexedBy(indexName: string): RdbPredicates - +indexedBy(field: string): RdbPredicates Sets the **RdbPredicates** object to specify the index column. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Name of the index column.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| +**Return value** -- Example +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.indexedBy("SALARY_INDEX") @@ -862,20 +899,21 @@ in(field: string, value: Array<ValueType>): RdbPredicates Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.in("AGE", [18, 20]) @@ -889,20 +927,21 @@ notIn(field: string, value: Array<ValueType>): RdbPredicates Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the database table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| -- Return value - | Type| Description| - | -------- | -------- | - | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +**Return value** +| Type| Description| +| -------- | -------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notIn("NAME", ["Lisa", "Rose"]) @@ -920,14 +959,16 @@ insert(name: string, values: ValuesBucket, callback: AsyncCallback<number> Inserts a row of data into a table. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the target table.| - | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** ``` const valueBucket = { "NAME": "Lisa", @@ -936,8 +977,8 @@ Inserts a row of data into a table. This method uses a callback to return the re "CODES": new Uint8Array([1, 2, 3, 4, 5]), } rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { - expect(1).assertEqual(ret) - console.log(TAG + "insert first done: " + ret)}) + console.log("insert first done: " + ret) + }) ``` @@ -947,18 +988,20 @@ insert(name: string, values: ValuesBucket):Promise<number> Inserts a row of data into a table. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the target table.| - | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** ``` const valueBucket = { "NAME": "Lisa", @@ -966,10 +1009,12 @@ Inserts a row of data into a table. This method uses a promise to return the res "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } - let promise = rdbStore.insert("EMPLOYEE", valueBucket) - promise.then(async (ret) => { - await console.log(TAG + "insert first done: " + ret) - }).catch((err) => {}) + let promiseinsert = rdbStore.insert("EMPLOYEE", valueBucket) + promiseinsert.then(async (ret) => { + console.log("insert first done: " + ret) + }).catch((err) => { + console.log("insert err.") + }) ``` @@ -979,14 +1024,16 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallba Updates data in the database based on the specified RdbPredicates object. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback used to return the number of rows updated.| + +**Example** ``` const valueBucket = { "NAME": "Rose", @@ -997,7 +1044,7 @@ Updates data in the database based on the specified RdbPredicates object. This m let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.update(valueBucket, predicates, function (err, ret) { - console.log(TAG + "updated row count: " + changedRows)}) + console.log("updated row count: " + changedRows)}) ``` @@ -1007,18 +1054,20 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> Updates data in the database based on the specified RdbPredicates object. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.| +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Row of data to insert.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of rows updated.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| -- Example +**Example** ``` const valueBucket = { "NAME": "Rose", @@ -1028,10 +1077,12 @@ Updates data in the database based on the specified RdbPredicates object. This m } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") - let promise = rdbStore.update(valueBucket, predicates) - promise.then(async (ret) => { - await console.log(TAG + "updated row count: " + changedRows) - }).catch((err) => {}) + let promiseupdate = rdbStore.update(valueBucket, predicates) + promiseupdate.then(async (ret) => { + console.log("updated row count: " + changedRows) + }).catch((err) => { + console.log("update err.") + }) ``` @@ -1042,19 +1093,21 @@ delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void Deletes data from the database based on the specified RdbPredicates object. This method uses a callback to return the result. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows deleted.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.delete(predicates, function (err, rows) { - console.log(TAG + "delete rows: " + rows)}) + console.log("delete rows: " + rows) + }) ``` @@ -1064,24 +1117,28 @@ delete(rdbPredicates: RdbPredicates):Promise<number> Deletes data from the database based on the specified RdbPredicates object. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified for deleting data.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of rows deleted.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the number of rows updated.| -- Example +**Example** ``` - let predicates = new data_rdb.RdbPredicates("EMPLOYEE") - predicates.equalTo("NAME", "Lisa") - let promise = rdbStore.delete(predicates) - promise.then((rows) => { - console.log(TAG + "delete rows: " + rows) - }).catch((err) => {}) + let predicatesdelete = new data_rdb.RdbPredicates("EMPLOYEE") + predicatesdelete.equalTo("NAME", "Lisa") + let promisedelete = rdbStore.delete(predicates) + promisedelete.then((rows) => { + console.log("delete rows: " + rows) + }).catch((err) => { + console.log("delete err.") + }) ``` @@ -1091,20 +1148,23 @@ query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: Asyn Queries data in the database based on specified conditions. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| - | columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| - | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }) ``` @@ -1114,25 +1174,30 @@ query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<Re Queries data in the database based on specified conditions. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| - | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rdbPredicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| -- Example +**Example** ``` let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") - let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - promise.then((resultSet) => { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + let promisequery = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequery.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("query err.") + }) ``` @@ -1142,18 +1207,21 @@ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback& Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| - | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }) ``` @@ -1163,23 +1231,28 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** ``` - let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) - promise.then((resultSet) => { - console.log(TAG + "resultSet column names:" + resultSet.columnNames) - console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + let promisequerySql = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) + promisequerySql.then((resultSet) => { + console.log("resultSet column names:" + resultSet.columnNames) + console.log("resultSet column count:" + resultSet.columnCount) + }).catch((err) => { + console.log("querySql err.") + }) ``` @@ -1189,17 +1262,20 @@ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallbac Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a callback to return the execution result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` rdbStore.executeSql("DELETE FROM EMPLOYEE", null, function () { - console.info(TAG + 'delete done.')}) + console.info('delete done.') + }) ``` @@ -1209,37 +1285,122 @@ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a promise to return the execution result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sql | string | Yes| SQL statement to run.| - | bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - let promise = rdbStore.executeSql("DELETE FROM EMPLOYEE") - promise.then(() => { - console.info(TAG + 'delete done.')}) + let promiseexecuteSql = rdbStore.executeSql("DELETE FROM EMPLOYEE") + promiseexecuteSql.then(() => { + console.info('delete done.') + }).catch((err) => { + console.log("executeSql err.") + }) ``` -### setDistributedTables +### beginTransaction8+ + +beginTransaction():void + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() +``` + + +### commit8+ + +commit():void -setDistributedTables(tables: Array, callback: AsyncCallback): void; +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() +``` + + +### rollBack8+ + +rollBack():void; + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** +``` + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + rdbStore.insert("test", valueBucket, function (err, ret) { + console.log("insert done: " + ret) + }) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +``` + + +### setDistributedTables8+ + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void Sets a list of distributed tables. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | tables | Array | Yes| Names of the distributed tables to be set.| - | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| tables | Array<string> | Yes| Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| + +**Example** ``` rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { @@ -1251,46 +1412,50 @@ Sets a list of distributed tables. This method uses a callback to return the res ``` -### setDistributedTables +### setDistributedTables8+ - setDistributedTables(tables: Array): Promise; + setDistributedTables(tables: Array<string>): Promise<void> Sets a list of distributed tables. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | tables | Array | Yes| Names of the distributed tables to be set.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| tables | Array<string> | Yes| Names of the distributed tables to set.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** ``` - let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) - promise.then(() => { + let promiseset = rdbStore.setDistributedTables(["EMPLOYEE"]) + promiseset.then(() => { console.info("setDistributedTables success.") }).catch((err) => { - console.info("setDistributedTables failed."") + console.info("setDistributedTables failed.") }) ``` -### obtainDistributedTableName +### obtainDistributedTableName8+ -obtainDistributedTableName(device: string, table: string, callback: AsyncCallback): void; +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | device | string | Yes| Remote device.| - | table | string | Yes| Local table name.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Remote device.| +| table | string | Yes| Local table name.| +| callback | AsyncCallback<string> | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** ``` rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", function (err, tableName) { if (err) { @@ -1302,47 +1467,51 @@ Obtains the distributed table name for a remote device based on the local table ``` -### obtainDistributedTableName +### obtainDistributedTableName8+ - obtainDistributedTableName(device: string, table: string): Promise; + obtainDistributedTableName(device: string, table: string): Promise<string> Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | device | string | Yes| Remote device.| - | table | string | Yes| Local table name.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Return value - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Remote device.| +| table | string | Yes| Local table name.| -- Example +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** ``` - let promise = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") - promise.then((tableName) => { + let promiseDistr = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE") + promiseDistr.then((tableName) => { console.info('obtainDistributedTableName success, tableName=' + tableName) }).catch((err) => { console.info('obtainDistributedTableName failed.') }) ``` -### sync +### sync8+ -sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback>): void; +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void Synchronizes data between devices. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mode | SyncMode | Yes| Data synchronization mode, which can be **push** or **pull**.| - | predicates | RdbPredicates | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| - | callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| +| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** ``` let predicate = new rdb.RdbPredicates('EMPLOYEE') predicate.inDevices(['12345678abcde']) @@ -1359,77 +1528,89 @@ Synchronizes data between devices. This method uses a callback to return the res ``` -### sync +### sync8+ - sync(mode: SyncMode, predicates: RdbPredicates): Promise>; + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> Synchronizes data between devices. This method uses a promise to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mode | SyncMode | Yes| Data synchronization mode, which can be **push** or **pull**.| - | predicates | RdbPredicates | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +**Return value** -- Example +| Type| Description| +| -------- | -------- | +| Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** ``` - let predicate = new rdb.RdbPredicates('EMPLOYEE') - predicate.inDevices(['12345678abcde']) - let promise = rdbStore.sync(rdb.SyncMode.SYNC_MODE_PUSH, predicate) - promise.then(result) { + let predicatesync = new data_rdb.RdbPredicates('EMPLOYEE') + predicatesync.inDevices(['12345678abcde']) + let promisesync = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesync) + promisesync.then((result) =>{ console.log('sync done.') for (let i = 0; i < result.length; i++) { console.log('device=' + result[i][0] + ' status=' + result[i][1]) } - }).catch((err) => { - console.log('sync failed') - }) + }).catch((err) => { + console.log('sync failed') + }) ``` -### on +### on('dataChange')8+ -on(event: 'dataChange', type: SubscribeType, observer: Callback>): void; +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | SubscribeType | Yes| Type defined in **SubscribeType**.| - | observer | Callback> | Yes| Observer that listens for the data changes in the RDB store.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -- Example +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| The value is'dataChange', which indicates a data change event.| +| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| + +**Example** ``` function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { console.log('device=' + device[i] + ' data changed') - } - } - try { - rdbStore.on('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) - } catch (err) { - console.log('register observer failed') - } + } + } + try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + } catch (err) { + console.log('register observer failed') + } ``` -### off +### off('dataChange')8+ -off(event:'dataChange', type: SubscribeType, observer: Callback>): void; +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void Deletes the specified observer of the RDB store. This method uses a callback to return the result. -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | SubscribeType | Yes| Type defined in **SubscribeType**.| - | observer | Callback> | Yes| Data change observer registered.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| The value is'dataChange', which indicates a data change event.| +| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| observer | Callback<Array<string>> | Yes| Data change observer registered.| + +**Example** -- Example ``` function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { @@ -1437,7 +1618,7 @@ Deletes the specified observer of the RDB store. This method uses a callback to } } try { - rdbStore.off('dataChange', rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('unregister observer failed') } @@ -1448,6 +1629,8 @@ Deletes the specified observer of the RDB store. This method uses a callback to Manages the configuration of an RDB store. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | name | string | Yes| Database file name.| @@ -1457,6 +1640,8 @@ Manages the configuration of an RDB store. Defines the data types allowed. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + | Name| Description| | -------- | -------- | | number | Number.| @@ -1468,25 +1653,30 @@ Defines the data types allowed. Defines a bucket to store key-value pairs. +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes| Defines a bucket to store key-value pairs.| -## SyncMode +## SyncMode8+ Defines the database synchronization mode. -| Name| Description| -| -------- | -------- | -| SYNC_MODE_PUSH | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | Data is loaded from a remote device to a local device.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Default Value| Description| +| -------- | ----- |----- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| -## SubscribeType +## SubscribeType8+ Defines the subscription type. -| Name| Description| -| -------- | -------- | -| SUBSCRIBE_TYPE_REMOTE | Subscribe to remote data changes.| +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Default Value| Description| +| -------- | ----- |---- | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 654cff58ad2c45b1d809251a7db2059c82b8928b..e383a530352cebdfac0124957f16957c88200223 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,15 +1,12 @@ -# Result Set +# Result Set ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## System Capabilities -SystemCapability.DistributedDataManager.RelationalStore.Core -## Usage +## Usage -The **resultSet** object is obtained by using [**RdbStore.query\(\)**](js-apis-data-rdb.md#query). +You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain the **resultSet** object. ``` import dataRdb from '@ohos.data.rdb'; @@ -17,779 +14,392 @@ let predicates = new dataRdb.RdbPredicates("EMPLOYEE") predicates.equalTo("AGE", 18) let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { - console.log("resultSet columnNames:" + resultSet.columnNames); - console.log("resultSet columnCount:" + resultSet.columnCount); + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) ``` -## ResultSet - -Provides methods to access the result set, which is obtained by querying the relational database \(RDB\) store. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnNames

-

Array<string>

-

Yes

-

Names of all columns in the result set.

-

columnCount

-

number

-

Yes

-

Number of columns in the result set.

-

rowCount

-

number

-

Yes

-

Number of rows in the result set.

-

rowIndex

-

number

-

Yes

-

Index of the current row in the result set.

-

isAtFirstRow

-

boolean

-

Yes

-

Specifies whether the cursor is in the first row of the result set.

-

isAtLastRow

-

boolean

-

Yes

-

Whether the cursor is in the last row of the result set.

-

isEnded

-

boolean

-

Yes

-

Whether the cursor is after the last row of the result set.

-

isStarted

-

boolean

-

Yes

-

Whether the cursor has been moved.

-

isClosed

-

boolean

-

Yes

-

Whether the result set is closed.

-
- -### getColumnIndex - -getColumnIndex\(columnName: string\): number - -Obtains the column index based on the specified column name. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnName

-

string

-

Yes

-

Name of the column.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Index of the column.

-
- -- Example - - ``` - resultSet.goToFirstRow() - const id = resultSet.getLong(resultSet.getColumnIndex("ID")) - const name = resultSet.getString(resultSet.getColumnIndex("NAME")) - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) - ``` - - -### getColumnName - -getColumnName\(columnIndex: number\): string - -Obtains the column name based on the specified column index. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the column.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Name of the column.

-
- -- Example - - ``` - const id = resultSet.getColumnName(0) - const name = resultSet.getColumnName(1) - const age = resultSet.getColumnName(2) - ``` - - -### goTo - -goTo\(offset:number\): boolean + + + +## ResultSet + +Provides methods to access the result set, which is obtained by querying the relational database (RDB) store. + + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| columnNames | Array<string> | Yes| Names of all columns in the result set.| +| columnCount | number | Yes| Number of columns in the result set.| +| rowCount | number | Yes| Number of rows in the result set.| +| rowIndex | number | Yes| Index of the current row in the result set.| +| isAtFirstRow | boolean | Yes| Whether the cursor is in the first row of the result set.| +| isAtLastRow | boolean | Yes| Whether the cursor is in the last row of the result set.| +| isEnded | boolean | Yes| Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes| Whether the cursor has been moved.| +| isClosed | boolean | Yes| Whether the result set is closed.| + + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| + +- Example + ``` + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("ID")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### getColumnName + +getColumnName(columnIndex: number): string + +Obtains the column name based on the column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| + +- Return value + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| + +- Example + ``` + const id = resultSet.getColumnName(0) + const name = resultSet.getColumnName(1) + const age = resultSet.getColumnName(2) + ``` + + +### goTo + +goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

offset

-

number

-

Yes

-

Offset relative to the current position.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goTo(1); - resultSet.close(); - resultSet = null; - }) - ``` - - -### goToRow - -goToRow\(position: number\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoto.then((resultSet) { + resultSet.goTo(1) + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` + + +### goToRow + +goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

position

-

number

-

Yes

-

Position to which the cursor is to be moved.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToRow(1); - resultSet.close(); - resultSet = null - }) - ``` - - -### goToFirstRow - -goToFirstRow\(\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -Moves the cursor to the first row of the result set. +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Return values +- Example + ``` + let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygotorow.then((resultSet) { + resultSet.goToRow(5) + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
-- Example +### goToFirstRow - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToFirstRow(); - resultSet.close(); - resultSet = null; - }) - ``` +goToFirstRow(): boolean -### goToLastRow +Moves the cursor to the first row of the result set. -goToLastRow\(\): boolean +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -Moves the cursor to the last row of the result set. +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Return values +- Example + ``` + let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoFirst.then((resultSet) { + resultSet.goToFirstRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
-- Example +### goToLastRow - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToLastRow(); - resultSet.close(); - resultSet = null; - }) - ``` +goToLastRow(): boolean +Moves the cursor to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoLast.then((resultSet) { + resultSet.goToLastRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` -### goToNextRow -goToNextRow\(\): boolean +### goToNextRow + +goToNextRow(): boolean Moves the cursor to the next row in the result set. -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
- -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +- Example + ``` + let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoNext.then((resultSet) { resultSet.goToNextRow() resultSet.close() - resultSet = null; - }) - ``` + }).catch((err) => { + console.log('query failed') + }) + ``` -### goToPreviousRow +### goToPreviousRow -goToPreviousRow\(\): boolean +goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -- Return values +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the operation is successful; returns false otherwise.

-
+- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.goToPreviousRow(); - resultSet.close(); - resultSet = null - }) - ``` +- Example + ``` + let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE") + let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoPrev.then((resultSet) { + resultSet.goToPreviousRow() + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` -### getBlob +### getBlob -getBlob\(columnIndex: number\): Uint8Array +getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- - -- Return values - - - - - - - - - - -

Type

-

Description

-

Uint8Array

-

Value in the specified column as a byte array.

-
- -- Example - - ``` - const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) - ``` - - -### getString - -getString\(columnIndex: number\): string +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| + +- Example + ``` + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + ``` + + +### getString + +getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Value in the specified column as a string.

-
- -- Example - - ``` - const name = resultSet.getString(resultSet.getColumnIndex("NAME")) - ``` - - -### getLong - -getLong\(columnIndex: number\): number - -Obtains the value in the specified column in the current row as a **Long**. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Value in the specified column as a Long.

-
- -- Example - - ``` - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) - ``` - - -### getDouble - -getDouble\(columnIndex: number\): number - -Obtains the value in the specified column in the current row as a **double**. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Value in the specified column as a double.

-
- -- Example - - ``` - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) - ``` - - -### isColumnNull - -isColumnNull\(columnIndex: number\): boolean - -Checks whether the value in the specified column in the current row is **null**. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

columnIndex

-

number

-

Yes

-

Index of the specified column, starting from 0.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

boolean

-

Returns true if the value is null; returns false otherwise.

-
- -- Example - - ``` - const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) - ``` - - -### close - -close\(\): void - -Closes the result set. - -- Example - - ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { - resultSet.close(); - resultSet = null - }) - ``` +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| + +- Example + ``` + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + ``` + + +### getLong + +getLong(columnIndex: number): number + +Obtains the value in the specified column in the current row as a Long. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| + +- Example + ``` + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + ``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value in the specified column in the current row as a double. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| + +- Example + ``` + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column of the current row is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| + +- Return value + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| + +- Example + ``` + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + ``` + + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +- Example + ``` + let predicatesclose = new dataRdb.RdbPredicates("EMPLOYEE") + let predicatesclose = rdbStore.query(predicatesclose, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promisequerygoPrev.then((resultSet) { + resultSet.close() + }).catch((err) => { + console.log('query failed') + }) + ``` 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 1f77fa17150dfa3b26394418a7b4411cde17a986..18cc1ce8d935c35b8a1035c5dd9a41f439db77d8 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -4,7 +4,8 @@ Lightweight storage provides applications with data processing capability and al > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. ## Modules to Import @@ -47,10 +48,16 @@ Reads a file and loads the data to the **Storage** instance in synchronous mode. import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - let storage = dataStorage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() + context.getFilesDir((err, path) => { + if (err) { + console.error('getFilesDir failed. err: ' + JSON.stringify(err)); + return; + } + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + let storage = dataStorage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() + }); ``` @@ -74,15 +81,21 @@ Reads a file and loads the data to the **Storage** instance. This method uses an import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - dataStorage.getStorage(path + '/mystore', function (err, storage) { + context.getFilesDir((err, path) => { if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') + console.error('getFilesDir failed. err: ' + JSON.stringify(err)); return; } - storage.putSync('startup', 'auto') - storage.flushSync() - }) + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + dataStorage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + storage.putSync('startup', 'auto') + storage.flushSync() + }) + }); ``` @@ -110,14 +123,20 @@ Reads a file and loads the data to the **Storage** instance. This method uses a import featureAbility from '@ohos.ability.featureAbility' var context = featureAbility.getContext() - var path = await context.getFilesDir() - let promisegetSt = dataStorage.getStorage(path + '/mystore') - promisegetSt.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) + context.getFilesDir((err, path) => { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + console.info('getFilesDir successful. path:' + JSON.stringify(path)); + let promisegetSt = dataStorage.getStorage(path + '/mystore') + promisegetSt.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Get the storage failed, path: " + path + '/mystore') + }) + }); ``` @@ -250,7 +269,7 @@ removeStorageFromCache(path: string): Promise<void> Removes the singleton **Storage** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -426,7 +445,7 @@ put(key: string, value: ValueType): Promise<void> Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush()** or **flushSync()**. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -522,7 +541,7 @@ has(key: string): Promise<boolean> Checks whether the storage object contains data with a given key. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -678,7 +697,7 @@ flush(): Promise<void> Saves the modification of this object to the **Storage** instance and synchronizes the modification to the file. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -747,7 +766,7 @@ clear(): Promise<void> Clears this **Storage** object. -This method uses a promise to return the result. +This method uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index fb34371c004c08cfc346a81cc13b8d3387f3ca94..10d36843925949c185a431ddb60dd33c1493d7b8 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -1,5 +1,8 @@ # DataAbilityHelper Module (JavaScript SDK APIs) +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import ``` diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index a8931d24e49bee0459923e96b9d4cea7fce31777..128dc378de40cc7cca9cc4b8b3732b833cc678b9 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -49,7 +49,7 @@ Inserts an entry at the front of this container. **Example** ``` -let deque = new Deque; +let deque = new Deque(); deque.insertFront("a"); deque.insertFront(1); let b = [1, 2, 3]; @@ -73,7 +73,7 @@ Inserts an entry at the end of this container. **Example** ``` -let deque = new Deque; +let deque = new Deque(); deque.insertEnd("a"); deque.insertEnd(1); let b = [1, 2, 3]; @@ -158,6 +158,7 @@ let result = deque.popLast(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void @@ -193,7 +194,7 @@ deque.forEach((value, index) => { ### getFirst -getFirst(): T; +getFirst(): T Obtains the first entry of this container. diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 43e248fb82075971c2e32b7fa77003d9ddff5bf3..93ab553ef10e531fea0b2d0871b65183d22bf6fa 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,456 +1,213 @@ -# Device Management +# Device Management ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs of this module are system APIs and cannot be called by third-party applications. -## Modules to Import + +## Modules to import: ``` import deviceManager from '@ohos.distributedHardware.deviceManager'; ``` -## deviceManager.createDeviceManager - -createDeviceManager\(bundleName: string, callback: AsyncCallback\): void - -Creates a **DeviceManager** instance. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Bundle name of the application.

-

callback

-

AsyncCallback<DeviceManager>

-

Yes

-

Callback invoked to return the DeviceManager instance created.

-
- -- Example - - ``` - deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { - if (err) { - console.info("createDeviceManager err:" + JSON.stringify(err)); - return; - } - console.info("createDeviceManager success"); - this.dmInstance = data; - }); - ``` - - -## DeviceStateChangeAction + +## deviceManager.createDeviceManager + +createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager>): void + +Creates a **DeviceManager** instance. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name of the application.| + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes| Callback invoked to return the **DeviceManager** instance created.| + +- Example + ``` + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.info("createDeviceManager err:" + JSON.stringify(err)); + return; + } + console.info("createDeviceManager success"); + this.dmInstance = data; + }); + ``` + + +## DeviceStateChangeAction Enumerates the device states. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

ONLINE

-

0

-

The device is online.

-

READY

-

1

-

The device is ready, and the device information has been synchronized.

-

OFFLINE

-

2

-

The device is offline.

-

CHANGE

-

3

-

The device information is changed.

-
- -## DeviceType - -Enumerates device types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SPEAKER

-

0x0A

-

Smart speaker.

-

PHONE

-

0x0E

-

Phone.

-

TABLET

-

0x11

-

Tablet.

-

WEARABLE

-

0x6D

-

Wearable.

-

TV

-

0x9C

-

Smart TV.

-
- -## DeviceInfo +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| ONLINE | 0 | The device is online.| +| READY | 1 | The device is ready, and the device information has been synchronized.| +| OFFLINE | 2 | The device is offline.| +| CHANGE | 3 | The device information is changed.| + + +## DeviceType + +Enumerates the device types. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| SPEAKER | 0x0A | Smart speaker.| +| PHONE | 0x0E | Phone.| +| TABLET | 0x11 | Tablet.| +| WEARABLE | 0x6D | Wearable.| +| TV | 0x9C | Smart TV.| +| CAR | 0x83 | Car.| +| UNKNOWN_TYPE | 0 | Unknown device type.| + + +## DeviceInfo Defines device information. - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

deviceId

-

number

-

Yes

-

Unique device identifier.

-

deviceName

-

string

-

Yes

-

Device name.

-

deviceType

-

number

-

Yes

-

Device type.

-
- -## DeviceManager - -Creates a **DeviceManager** instance to obtain information about trusted devices and local devices. Before calling any method in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. - -### release - -release\(\): void - -Releases the **DeviceManager** instance that is no longer used. - -- Example - - ``` - dmInstance.release(); - ``` - - -### getTrustedDeviceListSync - -getTrustedDeviceListSync\(\): Array +**System capability**: SystemCapability.DistributedHardware.DeviceManager -Obtains all trusted devices synchronously. +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | number | Yes| Unique device identifier.| +| deviceName | string | Yes| Device name.| +| deviceType | number | Yes| Device type.| + + +## DeviceManager -- Return values +Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. - - - - - - - - - -

Name

-

Description

-

Array<DeviceInfo>

-

List of trusted devices obtained.

-
-- Example +### release - ``` - var deviceInfoList = dmInstance.getTrustedDeviceListSync(); - ``` +release(): void +Releases the **DeviceManager** instance that is no longer used. -### on\('deviceStateChange'\) +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Example + ``` + dmInstance.release(); + ``` + + +### getTrustedDeviceListSync + +getTrustedDeviceListSync(): Array<DeviceInfo> + +Obtains all trusted devices synchronously. -on\(type: 'deviceStateChange', callback: Callback<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- Return value + | Name| Description| + | -------- | -------- | + | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| + +- Example + ``` + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + ``` + + +### on('deviceStateChange') + +on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void Subscribes to changes in the device state. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value is deviceStateChange, which indicates a device state change event.

-

callback

-

Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>

-

Yes

-

Callback invoked to return the device information and state.

-
- - -- Example - - ``` - dmInstance.on('deviceStateChange', (data) => { - console.info("deviceStateChange on:" + JSON.stringify(data)); - } - ); - ``` - - -### off\('deviceStateChange'\) - -off\(type: 'deviceStateChange', callback?: Call back<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void +**System capability**: SystemCapability.DistributedHardware.DeviceManager -Unsubscribes from changes in the device state. +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **deviceStateChange**, which indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes| Callback invoked to return the device information and state.| -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value deviceStateChange indicates an event of device state change.

-

callback

-

Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>

-

Yes

-

Callback used to return the device state changes.

-
- - -- Example - - ``` - dmInstance.off('deviceStateChange', (data) => { - console.info('deviceStateChange' + JSON.stringify(data)); - } - ); - ``` - - -### on\('serviceDie'\) - -on\(type: 'serviceDie', callback: \(\) =\> void\): void - -Subscribes to dead events of the **DeviceManager** service. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

-

callback

-

() => void

-

Yes

-

Callback invoked when a dead event of the DeviceManager service occurs.

-
- - -- Example - - ``` - dmInstance.on("serviceDie", () => { - console.info("serviceDie on"); - } - ); - ``` - - -### off\('serviceDie'\) - -off\(type: 'serviceDie', callback?: \(\) =\> void\): void - -Unsubscribes from dead events of the **DeviceManager** service. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

-

callback

-

() => void

-

No

-

Callback used to return the dead event of the DeviceManager service.

-
- - -- Example - - ``` - dmInstance.off("serviceDie", () => { - console.info("serviceDie off"); +- Example + ``` + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); } - ); - ``` + ); + ``` + + +### off('deviceStateChange') + +off(type: 'deviceStateChange', callback?: Call back<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void + +Unsubscribes from changes in the device state. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **deviceStateChange** indicates an event of device state change.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes| Callback invoked to return the device information and state.| + +- Example + ``` + dmInstance.off('deviceStateChange', (data) => { + console.info('deviceStateChange' + JSON.stringify(data)); + } + ); + ``` + + +### on('serviceDie') + +on(type: 'serviceDie', callback: () => void): void + +Subscribes to dead events of the **DeviceManager** service. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | Yes| Callback invoked when a dead event of the **DeviceManager** service occurs.| + +- Example + ``` + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + } + ); + ``` + + +### off('serviceDie') + +off(type: 'serviceDie', callback?: () => void): void + +Unsubscribes from dead events of the **DeviceManager** service. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **serviceDie** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | No| Callback used to return the dead event of the **DeviceManager** service.| +- Example + ``` + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + } + ); + ``` diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index fa0eac3fef8845b3e16cbac42a7894523fd69e1f..934bcc66d070f4f2a484944d7427d38039332f33 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -29,10 +29,10 @@ Checks whether the application specified by **bundleName** is in the idle state. ``` bundleState.isIdleState("com.ohos.camera", (err, res) => { - if(err.code === 0) { - console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); - } else { + if (err) { console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); } }); ``` @@ -85,10 +85,10 @@ Queries the priority group of the current invoker application. This API uses an ``` bundleState.queryAppUsagePriorityGroup((err, res) => { - if(err.code === 0) { - console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); - } else { + if (err) { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); + } else { + console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); } }); ``` @@ -139,7 +139,9 @@ Queries the application usage duration statistics based on the specified start t ``` bundleState.queryBundleStateInfos(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleStateInfos callback success.'); let i = 1; for(let key in res){ @@ -147,8 +149,6 @@ Queries the application usage duration statistics based on the specified start t console.log('BUNDLE_ACTIVE queryBundleStateInfos callback result ' + JSON.stringify(res[key])); i++; } - } else { - console.log('BUNDLE_ACTIVE queryBundleStateInfos callback failed, because: ' + err.code); } }); ``` @@ -215,14 +215,14 @@ Queries the application usage duration statistics in the specified time frame at ``` bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback result ' + JSON.stringify(res[i])); } - } else { - console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); } }); ``` @@ -287,14 +287,14 @@ Queries events of all applications based on the specified start time and end tim ``` bundleState.queryBundleActiveStates(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryBundleActiveStates callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates callback result ' + JSON.stringify(res[i])); } - } else { - console.log('BUNDLE_ACTIVE queryBundleActiveStates callback failed, because: ' + err.code); } }); ``` @@ -356,14 +356,14 @@ Queries events of this application based on the specified start time and end tim ``` bundleState.queryCurrentBundleActiveStates(0, 20000000000000, (err, res) => { - if(err.code == 0) { + if (err) { + console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code); + } else { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback result ' + JSON.stringify(res[i])); - } - } else { - console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates callback failed, because: ' + err.code); + } } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 8a787a420d2f2ec87d298c42f5f0b9533d5953e6..faaf19c4db1c1f74f530642e5d51f29b4dcd7694 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -67,7 +67,7 @@ Obtains the default display object. ``` var displayClass = null; display.getDefaultDisplay((err, data) => { - if (err) { + if (err.code) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); return; } @@ -119,7 +119,7 @@ Obtains all the display objects. ``` display.getAllDisplay((err, data) => { - if (err) { + if (err.code) { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); return; } diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index ee8b2f2a0aa057e168de6286e9624924d20d4f77..ddf747f7566d06b48c2d13f99f187b21f997b467 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,306 +1,149 @@ -# Distributed Account Management +# Distributed Account Management ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## Modules to Import + +## Modules to Import ``` import account_distributedAccount from '@ohos.account.distributedAccount'; ``` -## System Capabilities +## System Capability SystemCapability.Account.OsAccount -## account\_distributedAccount.getDistributedAccountAbility +## account_distributedAccount.getDistributedAccountAbility + +getDistributedAccountAbility(): DistributedAccountAbility -getDistributedAccountAbility\(\): DistributedAccountAbility +Obtains a **DistributedAccountAbility** instance. -Obtains a **DistributedAccountAbility** instance. +- Return value + | Type| Description| + | -------- | -------- | + | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| -- Return values +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + ``` - - - - - - - - - -

Type

-

Description

-

DistributedAccountAbility

-

Instance that provides methods for querying and updating the login state of a distributed account.

-
+## DistributedAccountAbility -- Example +Provides methods for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - ``` +### queryOsAccountDistributedInfo +queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void -## DistributedAccountAbility +Obtains distributed account information. This method uses an asynchronous callback to return the result. -Provides methods for querying and updating the login state of a distributed account. \(You must obtain a **DistributedAccountAbility** instance first.\) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) -### queryOsAccountDistributedInfo +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the distributed account information obtained.| -queryOsAccountDistributedInfo\(callback: AsyncCallback\): void +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo((err, data) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + ``` -Obtains distributed account information. This method uses an asynchronous callback to return the result. +### queryOsAccountDistributedInfo -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS or ohos.permission.DISTRIBUTED\_DATASYNC** permission is required. This permission is intended for system applications only. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<DistributedInfo>

-

Yes

-

Callback invoked to return the distributed account information.

-
- -- Example - - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo((err, data) => { - console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); - }); - ``` - - -### queryOsAccountDistributedInfo - -queryOsAccountDistributedInfo\(\): Promise +queryOsAccountDistributedInfo(): Promise<DistributedInfo> Obtains distributed account information. This method uses a promise to return the result asynchronously. -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS or ohos.permission.DISTRIBUTED\_DATASYNC** permission is required. This permission is intended for system applications only. +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) -- Return values +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| - - - - - - - - - -

Type

-

Description

-

Promise<DistributedInfo>

-

Promise used to return the result.

-
+- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); + }); + ``` -- Example +### updateOsAccountDistributedInfo - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo().then((data) => { - console.log('Query account info name: ' + data.name); - console.log('Query account info id: ' + data.id); - }).catch((err) => { - console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); - }); - ``` +updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void +Updates distributed account information. This method uses an asynchronous callback to return the result. -### updateOsAccountDistributedInfo +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) -updateOsAccountDistributedInfo\(accountInfo: DistributedInfo, callback: AsyncCallback\): void +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the distributed account information is updated.| -Updates distributed account information. This method uses an asynchronous callback to return the result. +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + +### updateOsAccountDistributedInfo -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

accountInfo

-

DistributedInfo

-

Yes

-

Distributed account information.

-

callback

-

AsyncCallback<void>

-

Yes

-

Callback invoked when the distributed account information is updated.

-
- -- Example - - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { - console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); - }); - ``` - - -### updateOsAccountDistributedInfo - -updateOsAccountDistributedInfo\(accountInfo: DistributedInfo\): Promise +updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> Updates distributed account information. This method uses a promise to return the result asynchronously. -The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. - -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

accountInfo

-

DistributedInfo

-

Yes

-

Distributed account information.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Promise used to return the result.

-
- -- Example - - ``` - const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { - console.log('updateOsAccountDistributedInfo Success'); - }).catch((err) => { - console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); - }); - ``` - - -## DistributedInfo +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS (available only to system applications) + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { + console.log('updateOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +## DistributedInfo Defines distributed OS account information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

name

-

string

-

Yes

-

Name of a distributed account. It must be a non-null string.

-

id

-

string

-

Yes

-

UID of a distributed account. It must be a non-null string.

-

event

-

string

-

Yes

-

Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:

-
  • Ohos.account.event.LOGIN
  • Ohos.account.event.LOGOUT
  • Ohos.account.event.TOKEN_INVALID
  • Ohos.account.event.LOGOFF
-

scalableData

-

object

-

No

-

Extended information about a distributed account. Customized information is passed in key-value pairs.

-

Note: This parameter is reserved and not used in query and update methods.

-
+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a distributed account. It must be a non-null string.| +| id | string | Yes| UID of a distributed account. It must be a non-null string.| +| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| 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 ce1692a8b20588c1b332eec8739d260158e7d6ee..d813b75b3e7a4f677fc96f87d9d38cb4719251e7 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -26,29 +26,29 @@ Creates a **KVManager** object to manage key-value (KV) stores. This method uses | config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** object, including the bundle name and user information of the caller.| | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** object created.| - **Example** - - let kvManager; - try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } +``` +let kvManager; +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("createKVManager err: " + JSON.stringify(err)); - return; - } - console.log("createKVManager success"); - kvManager = manager; - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("createKVManager err: " + JSON.stringify(err)); + return; + } + console.log("createKVManager success"); + kvManager = manager; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ## distributedData.createKVManager @@ -72,25 +72,26 @@ Creates a **KVManager** object to manage KV stores. This method uses a promise t **Example** - let kvManager; - try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } +``` +let kvManager; +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("createKVManager success"); - kvManager = manager; - }).catch((err) => { - console.log("createKVManager err: " + JSON.stringify(err)); - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); } - + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("createKVManager success"); + kvManager = manager; + }).catch((err) => { + console.log("createKVManager err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ## KVManagerConfig @@ -103,8 +104,6 @@ Provides configuration of the **KVManager** object, including the bundle name an | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| - - ## UserInfo Defines user information. @@ -132,8 +131,6 @@ Defines the user type. Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use **createKVManager** to create a **KVManager** object. - - ### getKVStore getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void @@ -152,30 +149,30 @@ Creates and obtains a KV store. This method uses an asynchronous callback to ret **Example** - ``` - let kvStore; - let kvManager; - try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options, function (err, store) { - if (err) { - console.log("getKVStore err: " + JSON.stringify(err)); - return; - } - console.log("getKVStore success"); - kvStore = store; - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +let kvManager; +try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + securityLevel : distributedData.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.log("getKVStore err: " + JSON.stringify(err)); + return; + } + console.log("getKVStore success"); + kvStore = store; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### getKVStore @@ -200,31 +197,30 @@ Creates and obtains a KV store. This method uses a promise to return the result. | -------------------------------------- | ------------------------ | | Promise<T> <T extends KVStore> | Promise used to return the KV store created.| - **Example** - ``` - let kvStore; - let kvManager; - try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options).then((store) => { - console.log("getKVStore success"); - kvStore = store; - }).catch((err) => { - console.log("getKVStore err: " + JSON.stringify(err)); - }); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +let kvManager; +try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + securityLevel : distributedData.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("getKVStore success"); + kvStore = store; + }).catch((err) => { + console.log("getKVStore err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### closeKVStore8+ ### @@ -244,33 +240,33 @@ Closes a KV store. This method uses an asynchronous callback to return the resul | kvStore | [KVStore](#kvstore) | Yes | KV store to close. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is closed, **true** will be returned. Otherwise, **false** will be returned. | - **Example** - ``` - 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 { - kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); - }); - } catch (e) { - console.log('closeKVStore e ' + e); - } - ``` +``` +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 { + kvManager.getKVStore('storeId', options, async function (err, store) { + console.log('getKVStore success'); + kvStore = store; + await kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { + console.log('closeKVStore success'); + }); + }); +} catch (e) { + console.log('closeKVStore e ' + e); +} +``` + ### closeKVStore8+ ### @@ -296,34 +292,34 @@ Closes a KV store. This method uses a promise to return the result. **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - await 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) { - console.log('closeKVStore e ' + e); - } - ``` +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} + try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('getKVStore success'); + kvStore = store; + await 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) { + console.log('closeKVStore e ' + e); +} +``` ### deleteKVStore8+ ### @@ -342,33 +338,32 @@ Deletes a KV store. This method uses an asynchronous callback to return the resu | storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed the value of [MAX_STORE_ID_LENGTH](#constants).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the KV store is deleted, **true** will be returned. Otherwise, **false** will be returned. | - **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('store', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { - console.log('deleteKVStore success'); - }); +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} +try { + kvManager.getKVStore('store', options, async function (err, store) { + console.log('getKVStore success'); + kvStore = store; + await kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + console.log('deleteKVStore success'); }); - } catch (e) { - console.log('DeleteKVStore e ' + e); - } - ``` + }); +} catch (e) { + console.log('DeleteKVStore e ' + e); +} +``` ### deleteKVStore8+ ### @@ -394,34 +389,34 @@ Deletes a KV store. This method uses a promise to return the result. **Example** - ``` - let kvManager; - let kvStore; - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - await kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('deleteKVStore success'); - }).catch((err) => { - console.log('deleteKVStore err ' + JSON.stringify(err)); - }); +``` +let kvManager; +let kvStore; +const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, + schema : '', + securityLevel : distributedData.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storId', options).then(async (store) => { + console.log('getKVStore success'); + kvStore = store; + await kvManager.deleteKVStore('appId', 'storeId').then(() => { + console.log('deleteKVStore success'); }).catch((err) => { - console.log('getKVStore err ' + JSON.stringify(err)); + console.log('deleteKVStore err ' + JSON.stringify(err)); }); - } catch (e) { - console.log('deleteKVStore e ' + e); - } - ``` + }).catch((err) => { + console.log('getKVStore err ' + JSON.stringify(err)); + }); +} catch (e) { + console.log('deleteKVStore e ' + e); +} +``` ### getAllKVStoreId8+ ### @@ -441,17 +436,17 @@ Obtains the IDs of all the KV stores that are created using **getKvStore** and h **Example** - ``` - let kvManager; - try { - kvManager.getAllKVStoreId('appId', function (err, data) { - console.log('GetAllKVStoreId success'); - console.log('GetAllKVStoreId size = ' + data.length); - }); - } catch (e) { - console.log('GetAllKVStoreId e ' + e); - } - ``` +``` +let kvManager; +try { + kvManager.getAllKVStoreId('appId', function (err, data) { + console.log('GetAllKVStoreId success'); + console.log('GetAllKVStoreId size = ' + data.length); + }); +} catch (e) { + console.log('GetAllKVStoreId e ' + e); +} +``` ### getAllKVStoreId8+ ### @@ -477,20 +472,20 @@ Obtains the IDs of all the KV stores that are created using **getKvStore** and h **Example** - ``` - let kvManager; - try { - console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('apppId').then((data) => { - console.log('getAllKVStoreId success'); - console.log('size = ' + data.length); - }).catch((err) => { - console.log('getAllKVStoreId err ' + JSON.stringify(err)); - }); - } catch(e) { - console.log('getAllKVStoreId e ' + e); - } - ``` +``` +let kvManager; +try { + console.log('GetAllKVStoreId'); + kvManager.getAllKVStoreId('apppId').then((data) => { + console.log('getAllKVStoreId success'); + console.log('size = ' + data.length); + }).catch((err) => { + console.log('getAllKVStoreId err ' + JSON.stringify(err)); + }); +} catch(e) { + console.log('getAllKVStoreId e ' + e); +} +``` ### on8+ ### @@ -508,23 +503,21 @@ Subscribes to the **distributedDataServiceDie** events. This method uses a synch | event | 'distributedDataServiceDie' | Yes | Type of events to subscribe to. | | deathCallback | Callback<void> | Yes | Callback invoked when the distributed data service is dead. | - - **Example** - ``` - let kvManager; - try { - - console.log('KVManagerOn'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.on('distributedDataServiceDie', deathCallback); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); +``` +let kvManager; +try { + + console.log('KVManagerOn'); + const deathCallback = function () { + console.log('death callback call'); } - ``` + kvManager.on('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### off8+ ### @@ -545,19 +538,19 @@ Unsubscribes from the **distributedDataServiceDie** events. This method uses a s **Example** - ``` - let kvManager; - try { - console.log('KVManagerOff'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.off('distributedDataServiceDie', deathCallback); - } catch (e) { - console.log("An unexpected error occurred. Error:" + e); +``` +let kvManager; +try { + console.log('KVManagerOff'); + const deathCallback = function () { + console.log('death callback call'); } + kvManager.off('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} - ``` +``` ## Options @@ -573,7 +566,7 @@ Provides KV store configuration. | autoSync | boolean | No|Whether to automatically synchronize database files. By default, database files are not automatically synchronized. | | kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.| | securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set. | -| schema | [schema](#Schema8+) | No| Schema used to define the values stored in a KV store.| +| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.| ## KVStoreType @@ -589,7 +582,6 @@ Defines the KV store types. | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. | - ## SecurityLevel Defines the KV store security levels. @@ -629,8 +621,8 @@ Defines a database schema. When creating or opening a KV store, you can create a | Name | Type| Description | | --- | ---- | ----------------------- | -| root8+ | [FieldNode](#FieldNode) | JSON root object. | -| indexes8+ | Array | String array in JSON format. | +| root8+ | [FieldNode](#fieldnode8) | JSON root object. | +| indexes8+ | Array\ | String array in JSON format. | | mode8+ | number | Schema mode. | | skip8+ | number | Size of a skip of the schema. | @@ -664,9 +656,9 @@ A constructor used to create a **FieldNode** instance with a string field. **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| name | string | Yes | Value of **FieldNode**. +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | --------------- | +| name | string | Yes | Value of **FieldNode**.| ### appendChild8+ ### @@ -680,7 +672,7 @@ Appends a child node to this **FieldNode**. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| child | [FieldNode](#FieldNode) | Yes | Child node to append. | +| child | [FieldNode](#fieldnode8) | Yes | Child node to append. | **Return value** @@ -691,27 +683,25 @@ Appends a child node to this **FieldNode**. **Example** - ``` - import ddm from '@ohos.data.distributedData'; - try { - let node = new ddm.FieldNode("root"); - let child1 = new ddm.FieldNode("child1"); - let child2 = new ddm.FieldNode("child2"); - let child3 = new ddm.FieldNode("child3"); - node.appendChild(child1); - node.appendChild(child2); - node.appendChild(child3); - console.log("appendNode " + node.toJson()); - child1 = null; - child2 = null; - child3 = null; - node = null; - } catch (e) { - console.log("AppendChild " + e); - } - ``` - - +``` +import ddm from '@ohos.data.distributedData'; +try { + let node = new ddm.FieldNode("root"); + let child1 = new ddm.FieldNode("child1"); + let child2 = new ddm.FieldNode("child2"); + let child3 = new ddm.FieldNode("child3"); + node.appendChild(child1); + node.appendChild(child2); + node.appendChild(child3); + console.log("appendNode " + node.toJson()); + child1 = null; + child2 = null; + child3 = null; + node = null; +} catch (e) { + console.log("AppendChild " + e); +} +``` ## KvStoreResultSet8+ ## @@ -735,23 +725,22 @@ Obtains the number of rows in the result set. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const count = resultSet.getCount(); - console.log("GetCount " + count); - } catch (e) { - console.log("GetCount fail " + e); - } - ``` - +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const count = resultSet.getCount(); + console.log("GetCount " + count); +} catch (e) { + console.log("GetCount fail " + e); +} +``` ### getPosition8+ ### @@ -769,22 +758,22 @@ Obtains the current data read position (position from which data is read) in the **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const positon = resultSet.getPosition(); - console.log("getPosition " + positon); - } catch (e) { - console.log("GetPosition fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const position = resultSet.getPosition(); + console.log("getPosition " + position); +} catch (e) { + console.log("GetPosition fail " + e); +} +``` ### moveToFirst8+ ### @@ -803,22 +792,22 @@ Moves the data read position to the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToFirst(); - console.log("moveToFirst " + moved); - } catch (e) { - console.log("MoveToFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToFirst(); + console.log("moveToFirst " + moved); +} catch (e) { + console.log("MoveToFirst fail " + e); +} +``` ### moveToLast8+ ### @@ -837,22 +826,22 @@ Moves the data read position to the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToLast(); - console.log("moveToLast " + moved); - } catch (e) { - console.log("moveToLast fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToLast(); + console.log("moveToLast " + moved); +} catch (e) { + console.log("moveToLast fail " + e); +} +``` ### moveToNext8+ ### @@ -871,22 +860,22 @@ Moves the data read position to the next row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToNext(); - console.log("moveToNext " + moved); - } catch (e) { - console.log("moveToNext fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToNext(); + console.log("moveToNext " + moved); +} catch (e) { + console.log("moveToNext fail " + e); +} +``` ### moveToPrevious8+ ### @@ -905,22 +894,22 @@ Moves the data read position to the previous row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToPrevious(); - console.log("moveToPrevious " + moved); - } catch (e) { - console.log("moveToPrevious fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToPrevious(); + console.log("moveToPrevious " + moved); +} catch (e) { + console.log("moveToPrevious fail " + e); +} +``` ### move8+ ### @@ -945,22 +934,22 @@ Moves the data read position with the specified offset from the current position **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.move(); - console.log("move " + moved); - } catch (e) { - console.log("move fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.move(); + console.log("move " + moved); +} catch (e) { + console.log("move fail " + e); +} +``` ### moveToPosition8+ ### @@ -985,22 +974,22 @@ Moves the data read position from 0 to an absolute position. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToPosition(); - console.log("moveToPosition " + moved); - } catch (e) { - console.log("moveToPosition fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToPosition(); + console.log("moveToPosition " + moved); +} catch (e) { + console.log("moveToPosition fail " + e); +} +``` ### isFirst8+ ### @@ -1019,22 +1008,22 @@ Checks whether the data read position is the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isFirst(); - console.log("isFirst " + moved); - } catch (e) { - console.log("isFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isFirst(); + console.log("isFirst " + moved); +} catch (e) { + console.log("isFirst fail " + e); +} +``` ### isLast8+ ### @@ -1053,23 +1042,22 @@ Checks whether the data read position is the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isLast(); - console.log("isLast " + moved); - } catch (e) { - console.log("isLast fail " + e); - } - ``` - +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isLast(); + console.log("isLast " + moved); +} catch (e) { + console.log("isLast fail " + e); +} +``` ### isBeforeFirst8+ ### @@ -1087,22 +1075,22 @@ Checks whether the data read position is before the first row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isBeforeFirst(); - console.log("isBeforeFirst " + moved); - } catch (e) { - console.log("isBeforeFirst fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isBeforeFirst(); + console.log("isBeforeFirst " + moved); +} catch (e) { + console.log("isBeforeFirst fail " + e); +} +``` ### isAfterLast8+ ### @@ -1121,22 +1109,22 @@ Checks whether the data read position is after the last row. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.isAfterLast(); - console.log("isAfterLast " + moved); - } catch (e) { - console.log("isAfterLast fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.isAfterLast(); + console.log("isAfterLast " + moved); +} catch (e) { + console.log("isAfterLast fail " + e); +} +``` ### getEntry8+ ### @@ -1155,23 +1143,23 @@ Obtains a KV pair. **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + err); - }); - const moved = resultSet.moveToNext(); - const entry = resultSet.getEntry(); - console.log("getEntry " + JSON.stringify(entry)); - } catch (e) { - console.log("getEntry fail " + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + err); + }); + const moved = resultSet.moveToNext(); + const entry = resultSet.getEntry(); + console.log("getEntry " + JSON.stringify(entry)); +} catch (e) { + console.log("getEntry fail " + e); +} +``` ## Query8+ ## @@ -1206,18 +1194,18 @@ Resets the **Query** object that contains common query options. **Example** - ``` - try { - let query = new distributedData.Query(); - query.equalTo("key", "value"); - console.log("query is " + query.getSqlLike()); - query.reset(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("simply calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.equalTo("key", "value"); + console.log("query is " + query.getSqlLike()); + query.reset(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("simply calls should be ok :" + e); +} +``` ### equalTo8+ ### @@ -1243,16 +1231,16 @@ Creates a **Query** object to match the specified field whose value is equal to **Example** - ``` - try { - let query = new distributedData.Query(); - query.equalTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.equalTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notEqualTo8+ ### @@ -1278,16 +1266,16 @@ Creates a **Query** object to match the specified field whose value is not equal **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### greaterThan8+ ### @@ -1303,7 +1291,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1313,16 +1301,16 @@ Creates a **Query** object to match the specified field whose value is greater t **Example** - ``` - try { - let query = new distributedData.Query(); - query.greaterThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.greaterThan("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### lessThan8+ ### @@ -1338,7 +1326,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1348,16 +1336,16 @@ Creates a **Query** object to match the specified field whose value is less than **Example** - ``` - try { - let query = new distributedData.Query(); - query.lessThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.lessThan("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### greaterThanOrEqualTo8+ ### @@ -1373,7 +1361,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1383,16 +1371,16 @@ Creates a **Query** object to match the specified field whose value is greater t **Example** - ``` - try { - let query = new distributedData.Query(); - query.greaterThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.greaterThanOrEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### lessThanOrEqualTo8+ ### @@ -1408,7 +1396,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It must start with $ and cannot contain ^. | -| value | number/string/boolean | Yes | Value specified.| +| value | number\|string\|boolean | Yes | Value specified.| **Return value** @@ -1418,16 +1406,16 @@ Creates a **Query** object to match the specified field whose value is less than **Example** - ``` - try { - let query = new distributedData.Query(); - query.lessThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.lessThanOrEqualTo("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### isNull8+ ### @@ -1453,16 +1441,16 @@ Creates a **Query** object to match the specified field whose value is **null**. **Example** - ``` - try { - let query = new distributedData.Query(); - query.isNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.isNull("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### inNumber8+ ### @@ -1487,19 +1475,18 @@ Creates a **Query** object to match the specified field whose value is within th | ------ | ------- | | [Query](#query8) |**Query** object Created.| - **Example** - ``` - try { - let query = new distributedData.Query(); - query.inNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.inNumber("field", [0, 1]); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### inString8+ ### @@ -1525,16 +1512,16 @@ Creates a **Query** object to match the specified field whose value is within th **Example** - ``` - try { - let query = new distributedData.Query(); - query.inString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.inString("field", ['test1', 'test2']); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notInNumber8+ ### @@ -1560,16 +1547,16 @@ Creates a **Query** object to match the specified field whose value is not withi **Example** - ``` - try { - let query = new distributedData.Query(); - query.notInNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notInNumber("field", [0, 1]); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### notInString8+ ### @@ -1595,16 +1582,16 @@ Creates a **Query** object to match the specified field whose value is not withi **Example** - ``` - try { - let query = new distributedData.Query(); - query.notInString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notInString("field", ['test1', 'test2']); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### like8+ ### @@ -1630,16 +1617,16 @@ Creates a **Query** object to match the specified field whose value is similar t **Example** - ``` - try { - let query = new distributedData.Query(); - query.like("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.like("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### unlike8+ ### @@ -1665,16 +1652,16 @@ Creates a **Query** object to match the specified field whose value is not simil **Example** - ``` - try { - let query = new distributedData.Query(); - query.unlike("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.unlike("field", "value"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### and8+ ### @@ -1693,18 +1680,18 @@ Creates a **Query** object with the AND condition. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.and(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value1"); + query.and(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### or8+ ### @@ -1723,18 +1710,18 @@ Creates a **Query** object with the OR condition. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.or(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value1"); + query.or(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### orderByAsc8+ ### @@ -1759,17 +1746,17 @@ Creates a **Query** object to sort the query results in ascending order. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByAsc("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.orderByAsc("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### orderByDesc8+ ### @@ -1792,20 +1779,19 @@ Creates a **Query** object to sort the query results in descending order. | ------ | ------- | | [Query](#query8) |**Query** object Created.| - **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByDesc("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.orderByDesc("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### limit8+ ### @@ -1831,17 +1817,17 @@ Creates a **Query** object to specify the number of results and where to start. **Example** - ``` - try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.limit("total", "offset"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.notEqualTo("field", "value"); + query.limit("total", "offset"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### isNotNull8+ ### @@ -1866,16 +1852,16 @@ Creates a **Query** object with a specified field that is not null. **Example** - ``` - try { - let query = new distributedData.Query(); - query.isNotNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.isNotNull("field"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### beginGroup8+ ### @@ -1894,18 +1880,18 @@ Creates a **Query** object for a query condition group with a left parenthesis. **Example** - ``` - try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### endGroup8+ ### @@ -1924,18 +1910,18 @@ Creates a **Query** object for a query condition group with a right parenthesis. **Example** - ``` - try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### prefixKey8+ ### @@ -1960,17 +1946,17 @@ Creates a **Query** object with a specified key prefix. **Example** - ``` - try { - let query = new distributedData.Query(); - query.prefixKey("$.name"); - query.prefixKey("0"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.prefixKey("$.name"); + query.prefixKey("0"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### setSuggestIndex8+ ### @@ -1995,17 +1981,17 @@ Creates a **Query** object with an index preferentially used for query. **Example** - ``` - try { - let query = new distributedData.Query(); - query.setSuggestIndex("$.name"); - query.setSuggestIndex("0"); - console.log("query is " + query.getSqlLike()); - query = null; - } catch (e) { - console.log("dumplicated calls should be ok :" + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.setSuggestIndex("$.name"); + query.setSuggestIndex("0"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("dumplicated calls should be ok :" + e); +} +``` ### deviceId8+ ### @@ -2031,15 +2017,15 @@ Creates a **Query** object with the device ID as the key prefix. **Example** - ``` - try { - let query = new distributedData.Query(); - query.deviceId("deviceId"); - console.log("query is " + query.getSqlLike()); - } catch (e) { - console.log("should be ok on Method Chaining : " + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + query.deviceId("deviceId"); + console.log("query is " + query.getSqlLike()); +} catch (e) { + console.log("should be ok on Method Chaining : " + e); +} +``` ### getSqlLike8+ ### @@ -2058,15 +2044,15 @@ Obtains the query statement of this **Query** object. **Example** - ``` - try { - let query = new distributedData.Query(); - let sql1 = query.getSqlLike(); - console.log("GetSqlLike sql=" + sql1); - } catch (e) { - console.log("dumplicated calls should be ok : " + e); - } - ``` +``` +try { + let query = new distributedData.Query(); + let sql1 = query.getSqlLike(); + console.log("GetSqlLike sql=" + sql1); +} catch (e) { + console.log("dumplicated calls should be ok : " + e); +} +``` ## KVStore @@ -2089,26 +2075,26 @@ Adds a KV pair of the specified type to this KV store. This method uses an async | ----- | ------ | ---- | ----------------------- | | 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 invoked to return the result. | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### put @@ -2132,23 +2118,22 @@ Adds a KV pair of the specified type to this KV store. This method uses a promis | ------ | ------- | | Promise<void> |Promise used to return the result.| - **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### delete @@ -2168,29 +2153,29 @@ Deletes a KV pair from this KV store. This method uses an asynchronous callback **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); + console.log("delete err: " + JSON.stringify(err)); return; } - console.log("put success"); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("delete err: " + JSON.stringify(err)); - return; - } - console.log("delete success"); - }); + console.log("delete success"); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### delete @@ -2215,25 +2200,25 @@ Deletes a KV pair from this KV store. This method uses a promise to return the r **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("delete success"); - }).catch((err) => { - console.log("delete err: " + JSON.stringify(err)); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("delete success"); }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); + console.log("delete err: " + JSON.stringify(err)); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### on @@ -2248,19 +2233,18 @@ Subscribes to data changes of the specified type. This method uses a synchronous | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |'dataChange' | Yes |Type of the events. | +| event |'dataChange' | Yes |Type of the events. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | | observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return the result.| - **Example** - ``` - let kvStore; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); - }); - ``` +``` +let kvStore; +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); +``` ### on @@ -2275,18 +2259,17 @@ Subscribes to data synchronization completion events. This method uses a synchro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |'syncComplete' | Yes |Type of the events. | +| event |'syncComplete' | Yes |Type of the events. | | syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the result. | - **Example** - ``` - let kvStore; - kvStore.on('syncComplete', function (data) { - console.log("syncComplete callback call data: " + data); - }); - ``` +``` +let kvStore; +kvStore.on('syncComplete', function (data) { + console.log("syncComplete callback call data: " + data); +}); +``` ### off8+ @@ -2305,15 +2288,15 @@ Unsubscribes from data change events. This method uses a synchronous callback to **Example** - ``` - let kvStore; - kvStore.on('dataChange', function (data) { - console.log("syncComplete callback call data: " + data); - }); - kvStore.off('dataChange', function (data) { - console.log("syncComplete callback call data: " + data); - }); - ``` +``` +let kvStore; +kvStore.on('dataChange', function (data) { + console.log("syncComplete callback call data: " + data); +}); +kvStore.off('dataChange', function (data) { + console.log("syncComplete callback call data: " + data); +}); +``` ### putBatch8+ @@ -2333,35 +2316,34 @@ Inserts KV pairs in batches to this KV store. This method uses an asynchronous c **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### putBatch8+ @@ -2386,37 +2368,37 @@ Inserts KV pairs in batches to this KV store. This method uses a promise to retu **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('PutBatch ' + JSON.stringify(entries)); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('PutBatch ' + JSON.stringify(entries)); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### deleteBatch8+ @@ -2436,34 +2418,34 @@ Deletes KV pairs in batches from this KV store. This method uses an asynchronous **Example** - ``` - let kvStore; - try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); - keys.push(key + i); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.deleteBatch(keys, async function (err,data) { - console.log('deleteBatch success'); - }); - }); - }catch(e) { - console.log('DeleteBatch e ' + e); + entries.push(entry); + keys.push(key + i); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.deleteBatch(keys, async function (err,data) { + console.log('deleteBatch success'); + }); + }); +}catch(e) { + console.log('DeleteBatch e ' + e); +} +``` ### deleteBatch8+ ### @@ -2488,38 +2470,38 @@ Deletes KV pairs in batches from this KV store. This method uses a promise to re **Example** - ``` - let kvStore; - try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); - keys.push(key + i); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.deleteBatch(keys).then((err) => { - console.log('deleteBatch success'); - }).catch((err) => { - console.log('deleteBatch fail ' + JSON.stringify(err)); - }); + entries.push(entry); + keys.push(key + i); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.deleteBatch(keys).then((err) => { + console.log('deleteBatch success'); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('deleteBatch fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('DeleteBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('DeleteBatch e ' + e); +} +``` ### startTransaction8+ ### @@ -2538,40 +2520,40 @@ Starts the transaction in this KV store. This method uses an asynchronous callba **Example** - ``` - let kvStore; - function putBatchString(len, prefix) { - let entries = []; - for (var i = 0; i < len; i++) { - var entry = { - key : prefix + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +function putBatchString(len, prefix) { + let entries = []; + for (var i = 0; i < len; i++) { + var entry = { + key : prefix + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - return entries; + entries.push(entry); } - try { - var count = 0; - kvStore.on('dataChange', 0, function (data) { - console.log('startTransaction 0' + data) - count++; - }); - kvStore.startTransaction(async function (err,data) { - console.log('startTransaction success'); - let entries = putBatchString(10, 'batch_test_string_key'); - console.log('entries: ' + JSON.stringify(entries)); - await kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - }); + return entries; +} +try { + var count = 0; + kvStore.on('dataChange', 0, function (data) { + console.log('startTransaction 0' + data) + count++; + }); + kvStore.startTransaction(async function (err,data) { + console.log('startTransaction success'); + let entries = putBatchString(10, 'batch_test_string_key'); + console.log('entries: ' + JSON.stringify(entries)); + await kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); }); - }catch(e) { - console.log('startTransaction e ' + e); - } - ``` + }); +}catch(e) { + console.log('startTransaction e ' + e); +} +``` ### startTransaction8+ ### @@ -2590,23 +2572,23 @@ Starts the transaction in this KV store. This method uses a promise to return th **Example** - ``` - let kvStore; - try { - var count = 0; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log('startTransaction ' + JSON.stringify(data)); - count++; - }); - kvStore.startTransaction().then(async (err) => { - console.log('startTransaction success'); - }).catch((err) => { - console.log('startTransaction fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('startTransaction e ' + e); - } - ``` +``` +let kvStore; +try { + var count = 0; + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { + console.log('startTransaction ' + JSON.stringify(data)); + count++; + }); + kvStore.startTransaction().then(async (err) => { + console.log('startTransaction success'); + }).catch((err) => { + console.log('startTransaction fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('startTransaction e ' + e); +} +``` ### commit8+ ### @@ -2625,20 +2607,20 @@ Commits the transaction in this KV store. This method uses an asynchronous callb **Example** - ``` - let kvStore; - try { - kvStore.commit(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); - }catch(e) { - console.log('Commit e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.commit(function (err,data) { + if (err == undefined) { + console.log('commit success'); + } else { + console.log('commit fail'); + } + }); +}catch(e) { + console.log('Commit e ' + e); +} +``` ### commit8+ ### @@ -2657,18 +2639,18 @@ Commits the transaction in this KV store. This method uses a promise to return t **Example** - ``` - let kvStore; - try { - kvStore.commit().then(async (err) => { - console.log('commit success'); - }).catch((err) => { - console.log('commit fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('Commit e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.commit().then(async (err) => { + console.log('commit success'); + }).catch((err) => { + console.log('commit fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('Commit e ' + e); +} +``` ### rollback8+ ### @@ -2687,20 +2669,20 @@ Rolls back the transaction in this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - try { - kvStore.rollback(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); - }catch(e) { - console.log('Rollback e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.rollback(function (err,data) { + if (err == undefined) { + console.log('commit success'); + } else { + console.log('commit fail'); + } + }); +}catch(e) { + console.log('Rollback e ' + e); +} +``` ### rollback8+ ### @@ -2719,18 +2701,18 @@ Rolls back the transaction in this KV store. This method uses a promise to retur **Example** - ``` - let kvStore; - try { - kvStore.rollback().then(async (err) => { - console.log('rollback success'); - }).catch((err) => { - console.log('rollback fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('Rollback e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.rollback().then(async (err) => { + console.log('rollback success'); + }).catch((err) => { + console.log('rollback fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('Rollback e ' + e); +} +``` ### enableSync8+ ### @@ -2750,20 +2732,20 @@ Sets data synchronization, which can be enabled or disable. This method uses an **Example** - ``` - let kvStore; - try { - kvStore.enableSync(true, function (err,data) { - if (err == undefined) { - console.log('enableSync success'); - } else { - console.log('enableSync fail'); - } - }); - }catch(e) { - console.log('EnableSync e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.enableSync(true, function (err,data) { + if (err == undefined) { + console.log('enableSync success'); + } else { + console.log('enableSync fail'); + } + }); +}catch(e) { + console.log('EnableSync e ' + e); +} +``` ### enableSync8+ ### @@ -2788,18 +2770,18 @@ Enables or disables data synchronization. This method uses a promise to return t **Example** - ``` - let kvStore; - try { - kvStore.enableSync(true).then((err) => { - console.log('enableSync success'); - }).catch((err) => { - console.log('enableSync fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('EnableSync e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.enableSync(true).then((err) => { + console.log('enableSync success'); + }).catch((err) => { + console.log('enableSync fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('EnableSync e ' + e); +} +``` ### setSyncRange8+ ### @@ -2820,18 +2802,18 @@ Sets the data synchronization range. This method uses an asynchronous callback t **Example** - ``` - let kvStore; - try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { - console.log('SetSyncRange put success'); - }); - }catch(e) { - console.log('SetSyncRange e ' + e); - } - ``` +``` +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { + console.log('SetSyncRange put success'); + }); +}catch(e) { + console.log('SetSyncRange e ' + e); +} +``` ### setSyncRange8+ ### @@ -2858,20 +2840,20 @@ Sets the data synchronization range. This method uses a promise to return the re **Example** - ``` - let kvStore; - try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('setSyncRange success'); - }).catch((err) => { - console.log('delete fail ' + err); - }); - }catch(e) { - console.log('SetSyncRange e ' + e); - } - ``` +``` +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + console.log('setSyncRange success'); + }).catch((err) => { + console.log('delete fail ' + err); + }); +}catch(e) { + console.log('SetSyncRange e ' + e); +} +``` ## SubscribeType @@ -2958,34 +2940,34 @@ Obtains the value of a specified key. This method uses an asynchronous callback | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array / string / boolean / number>) | Yes |Callback used to return the value obtained. | +| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback used to return the value obtained. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log("get success data: " + data); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + if (err != undefined) { + console.log("put err: " + JSON.stringify(err)); + return; + } + console.log("put success"); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { + console.log("get success data: " + data); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### get -get(key: string): Promise<Uint8Array | string | boolean | number> +get(key: string): Promise<Uint8Array | string | boolean | number> Obtains the value of a specified key. This method uses a promise to return the result. @@ -3002,30 +2984,29 @@ Obtains the value of a specified key. This method uses a promise to return the r | Type | Description | | ------ | ------- | -|Promise<Uint8Array / string / boolean / number> |Promise used to return the value obtained.| - +|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("get success data: " + data); - }).catch((err) => { - console.log("get err: " + JSON.stringify(err)); - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log("put success: " + JSON.stringify(data)); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log("get success data: " + data); }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); + console.log("get err: " + JSON.stringify(err)); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); - } - ``` + }).catch((err) => { + console.log("put err: " + JSON.stringify(err)); + }); +}catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` ### getEntries8+ ### @@ -3040,37 +3021,37 @@ Obtains the KV pairs that match the specified key prefix. This method uses an as | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<Entry[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_number_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.INTEGER, - value : 222 - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_number_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.INTEGER, + value : 222 } - entries.push(entry); } - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_number_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_number_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -3095,40 +3076,40 @@ Obtains the KV pairs that match the specified key prefix. This method uses a pro **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + entries); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); + console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -3144,42 +3125,42 @@ Obtains the KV pairs that match the specified **Query** object. This method uses | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<Entry[]> | Yes |Callback used to return the KV pairs obtained. | +| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -3204,39 +3185,39 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getResultSet8+ ### @@ -3256,36 +3237,36 @@ Obtains the result set with the specified key prefix from this single KV store. **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('GetResultSet putBatch success'); - await kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('GetResultSet closeResultSet success'); - }) - }); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('GetResultSet putBatch success'); + await kvStore.getResultSet('batch_test_string_key', async function (err, result) { + console.log('GetResultSet getResultSet success'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + console.log('GetResultSet closeResultSet success'); + }) + }); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -3310,42 +3291,42 @@ Obtains the result set with the specified key prefix from this single KV store. **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResult closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResult e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('PutBatch putBatch fail ' + JSON.stringify(err)); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('GetResult getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('GetResult closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResult e ' + e); +} +``` ### getResultSet8+ ### @@ -3365,35 +3346,35 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSet(query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -3418,40 +3399,39 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` - + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log(' getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -3470,21 +3450,21 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('closeResultSet success'); + } else { + console.log('closeResultSet fail'); + } + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -3509,19 +3489,19 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### getResultSize8+ ### @@ -3541,33 +3521,33 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSize(query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -3592,37 +3572,37 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### removeDeviceData8+ ### @@ -3642,29 +3622,29 @@ Deletes data of a device. This method uses an asynchronous callback to return th **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('put success'); + const deviceid = 'no_exist_device_id'; + await kvStore.removeDeviceData(deviceid, async function (err,data) { + if (err == undefined) { + console.log('removeDeviceData success'); + } else { + console.log('removeDeviceData fail'); + await kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData get success'); + }); + } }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### removeDeviceData8+ ### @@ -3689,31 +3669,31 @@ Deletes data of a device. This method uses a promise to return the result. **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('removeDeviceData put success'); - }).catch((err) => { - console.log('put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('removeDeviceData put success'); + }).catch((err) => { + console.log('put fail ' + JSON.stringify(err)); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('removeDeviceData success'); + }).catch((err) => { + console.log('removeDeviceData fail ' + JSON.stringify(err)); + }); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('get success data:' + data); + }).catch((err) => { + console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### on8+ ### @@ -3733,30 +3713,30 @@ Subscribes to the synchronization completion events. This method uses a synchron **Example** - ``` - let kvStore; - const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; - const VALUE_TEST_FLOAT_ELEMENT = 321.12; - try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); - }catch(e) { - console.log('syncComplete put e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log('syncComplete ' + data) + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('syncComplete put success'); + }).catch((error) => { + console.log('syncComplete put fail ' + error); + }); +}catch(e) { + console.log('syncComplete put e ' + e); +} +``` ### off8+ ### off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization completion events. This method uses a synchronization callback to return the result. +Unsubscribes from the synchronization completion events. This method uses a synchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3767,21 +3747,20 @@ Unsubscribes from the synchronization completion events. This method uses a sync | event |'syncComplete' | Yes |Event triggered when the synchronization is complete. | | syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - **Example** - ``` - let kvStore; - try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); - }catch(e) { - console.log('syncComplete e ' + e); - } - ``` +``` +let kvStore; +try { + const func = function (data) { + console.log('syncComplete ' + data) + }; + kvStore.on('syncComplete', func); + kvStore.off('syncComplete', func); +}catch(e) { + console.log('syncComplete e ' + e); +} +``` ### sync @@ -3789,6 +3768,7 @@ Unsubscribes from the synchronization completion events. This method uses a sync sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3802,10 +3782,10 @@ Manually triggers KV store synchronization synchronously. **Example** - ``` - let kvStore; - kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); - ``` +``` +let kvStore; +kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); +``` ### setSyncParam8+ ### @@ -3822,20 +3802,19 @@ Sets the default delay of database synchronization. This method uses an asynchro | defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | | callback |AsyncCallback<void> | Yes |Callback used to return the result. | - **Example** - ``` - let kvStore; - try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { - console.log('SetSyncParam put success'); - }); - }catch(e) { - console.log('testSingleKvStoreSetSyncParam e ' + e); - } - ``` +``` +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { + console.log('SetSyncParam put success'); + }); +}catch(e) { + console.log('testSingleKvStoreSetSyncParam e ' + e); +} +``` ### setSyncParam8+ ### @@ -3861,19 +3840,19 @@ Sets the default delay of database synchronization. This method uses a promise t **Example** - ``` - let kvStore; - try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('SetSyncParam put success'); - }).catch((err) => { - console.log('SetSyncParam put fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('SetSyncParam e ' + e); - } - ``` +``` +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + console.log('SetSyncParam put success'); + }).catch((err) => { + console.log('SetSyncParam put fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('SetSyncParam e ' + e); +} +``` ### getSecurityLevel8+ ### @@ -3892,16 +3871,16 @@ Obtains the security level of this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - try { - kvStore.getSecurityLevel(function (err,data) { - console.log('getSecurityLevel success'); - }); - }catch(e) { - console.log('GetSecurityLeve e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.getSecurityLevel(function (err,data) { + console.log('getSecurityLevel success'); + }); +}catch(e) { + console.log('GetSecurityLeve e ' + e); +} +``` ### getSecurityLevel8+ ### @@ -3918,21 +3897,20 @@ Obtains the security level of this KV store. This method uses a promise to retur | ------ | ------- | |Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| - **Example** - ``` - let kvStore; - try { - kvStore.getSecurityLevel().then((data) => { - console.log(' getSecurityLevel success'); - }).catch((err) => { - console.log('getSecurityLevel fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetSecurityLeve e ' + e); - } - ``` +``` +let kvStore; +try { + kvStore.getSecurityLevel().then((data) => { + console.log(' getSecurityLevel success'); + }).catch((err) => { + console.log('getSecurityLevel fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetSecurityLeve e ' + e); +} +``` ## DeviceKVStore8+ ## @@ -3947,7 +3925,7 @@ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|num Obtains the string value that matches the specified key for a device. This method uses an asynchronous callback to return the result. -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore **Parameters** @@ -3955,26 +3933,25 @@ Obtains the string value that matches the specified key for a device. This metho | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | key |string | Yes |Key to match. | -| callback |AsyncCallback<boolean/string/number/Uint8Array> | Yes |Callback used to return the value obtained. | - +| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try{ - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log('get success'); - }); - }) - }catch(e) { - console.log('get e' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try{ + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('put success'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { + console.log('get success'); + }); + }) +}catch(e) { + console.log('get e' + e); +} +``` ### get8+ ### @@ -4000,25 +3977,25 @@ Obtains the string value that matches the specified key for a device. This metho **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log(' put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success'); - }).catch((err) => { - console.log('get fail ' + JSON.stringify(err)); - }); - }).catch((error) => { - console.log('put error' + error); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + console.log(' put success'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('get success'); + }).catch((err) => { + console.log('get fail ' + JSON.stringify(err)); }); - } catch (e) { - console.log('Get e ' + e); - } - ``` + }).catch((error) => { + console.log('put error' + error); + }); +} catch (e) { + console.log('Get e ' + e); +} +``` ### getEntries8+ ### @@ -4039,34 +4016,34 @@ Obtains the KV pairs that match the specified key prefix for a device. This meth **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - }catch(e) { - console.log('PutBatch e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + entries); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + await kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -4092,40 +4069,40 @@ Obtains the KV pairs that match the specified key prefix for a device. This meth **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); - console.log('entrys[0].value.value: ' + entrys[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + entries); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + await kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entrys) => { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + console.log('entrys[0].value: ' + JSON.stringify(entrys[0].value)); + console.log('entrys[0].value.value: ' + entrys[0].value.value); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - }catch(e) { - console.log('PutBatch e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('PutBatch e ' + e); +} +``` ### getEntries8+ ### @@ -4145,40 +4122,40 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - expect(err == undefined).assertTrue(); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getEntries(query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }); - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + expect(err == undefined).assertTrue(); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getEntries(query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4203,40 +4180,40 @@ Obtains the KV pairs that match the specified **Query** object. This method uses **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getEntries(query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getEntries(query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('GetEntries putBatch fail ' + JSON.stringify(err)) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4257,40 +4234,40 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - expect(err == undefined).assertTrue(); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query, function (err,entrys) { - console.log('getEntries success'); - console.log('entrys.length: ' + entrys.length); - console.log('entrys[0]: ' + JSON.stringify(entrys[0])); - }) - }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); + entries.push(entry); } - ``` + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries, async function (err,data) { + console.log('putBatch success'); + expect(err == undefined).assertTrue(); + var query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + await kvStore.getEntries('localDeviceId', query, function (err,entrys) { + console.log('getEntries success'); + console.log('entrys.length: ' + entrys.length); + console.log('entrys[0]: ' + JSON.stringify(entrys[0])); + }) + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getEntries8+ ### @@ -4316,41 +4293,41 @@ Obtains the KV pairs that match the specified **Query** object for a device. Thi **Example** - ``` - let kvStore; - try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } +``` +let kvStore; +try { + var arr = new Uint8Array([21,31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.BYTE_ARRAY, + value : arr } - entries.push(entry); } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - await kvStore.getEntries('localDeviceId', query).then((entrys) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); + entries.push(entry); + } + console.log('entries: ' + JSON.stringify(entries)); + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + var query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + await kvStore.getEntries('localDeviceId', query).then((entrys) => { + console.log('getEntries success'); }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); + console.log('getEntries fail ' + JSON.stringify(err)); }); - console.log('GetEntries success'); - }catch(e) { - console.log('GetEntries e ' + e); - } - ``` + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + console.log('GetEntries success'); +}catch(e) { + console.log('GetEntries e ' + e); +} +``` ### getResultSet8+ ### @@ -4371,21 +4348,21 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }catch(e) { - console.log('GetResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4411,25 +4388,25 @@ Obtains the **KvStoreResultSet** object that matches the specified key prefix fo **Example** - ``` - let kvStore; - try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4449,39 +4426,39 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getResultSet(query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4506,46 +4483,46 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + err); - }); - const query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.getResultSet(query).then((result) => { - console.log('getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + err); + }); + const query = new distributedData.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.getResultSet(query).then((result) => { + console.log('getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4566,38 +4543,38 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet success'); - resultSet = result; - await kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); - } catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSet('localDeviceId', query, async function (err, result) { + console.log('getResultSet success'); + resultSet = result; + await kvStore.closeResultSet(resultSet, function (err, data) { + console.log('closeResultSet success'); + }) + }); + }); +} catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### getResultSet8+ ### @@ -4623,47 +4600,47 @@ Obtains the **KvStoreResultSet** object that matches the specified **Query** obj **Example** - ``` - let kvStore; - try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('GetResultSet putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet success'); - resultSet = result; - }).catch((err) => { - console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResultSet closeResultSet success'); - }).catch((err) => { - console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); - }); - - }catch(e) { - console.log('GetResultSet e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('GetResultSet putBatch success'); + }).catch((err) => { + console.log('PutBatch putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('GetResultSet getResultSet success'); + resultSet = result; + }).catch((err) => { + console.log('GetResultSet getResultSet fail ' + JSON.stringify(err)); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('GetResultSet closeResultSet success'); + }).catch((err) => { + console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); + }); + +}catch(e) { + console.log('GetResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -4683,22 +4660,22 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + console.log('CloseResultSet success'); + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('closeResultSet success'); + } else { + console.log('closeResultSet fail'); + } + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### closeResultSet8+ ### @@ -4723,20 +4700,20 @@ Closes the **KvStoreResultSet** object obtained by **getResultSet**. This method **Example** - ``` - let kvStore; - try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('CloseResultSet e ' + e); - } - ``` +``` +let kvStore; +try { + console.log('CloseResultSet success'); + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('closeResultSet success'); + }).catch((err) => { + console.log('closeResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('CloseResultSet e ' + e); +} +``` ### getResultSize8+ ### @@ -4756,34 +4733,34 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - await kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + await kvStore.getResultSize(query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4808,38 +4785,38 @@ Obtains the number of results that matches the specified **Query** object. This **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.getResultSize(query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4860,33 +4837,33 @@ Obtains the number of results that matches the specified **Query** object for a **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet success'); - }); - }); - } catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries, async function (err, data) { + console.log('putBatch success'); + const query = new distributedData.Query(); + query.prefixKey("batch_test"); + await kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + console.log('getResultSet success'); + }); + }); +} catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### getResultSize8+ ### @@ -4912,37 +4889,37 @@ Obtains the number of results that matches the specified **Query** object for a **Example** - ``` - let kvStore; - try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } +``` +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key : key + i, + value : { + type : distributedData.ValueType.STRING, + value : 'batch_test_string_value' } - entries.push(entry); } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - var query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet success'); - }).catch((err) => { - console.log('getResultSet fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('GetResultSize e ' + e); + entries.push(entry); } - ``` + kvStore.putBatch(entries).then(async (err) => { + console.log('putBatch success'); + }).catch((err) => { + console.log('putBatch fail ' + JSON.stringify(err)); + }); + var query = new distributedData.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query).then((resultSize) => { + console.log('getResultSet success'); + }).catch((err) => { + console.log('getResultSet fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('GetResultSize e ' + e); +} +``` ### removeDeviceData8+ ### @@ -4962,29 +4939,29 @@ Removes data of a device from this KV store. This method uses an asynchronous ca **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData put success'); - const deviceid = 'no_exist_device_id'; - await kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData put success'); + const deviceid = 'no_exist_device_id'; + await kvStore.removeDeviceData(deviceid, async function (err,data) { + if (err == undefined) { + console.log('removeDeviceData success'); + } else { + console.log('removeDeviceData fail'); + await kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { + console.log('RemoveDeviceData get success'); + }); + } }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### removeDeviceData8+ ### @@ -5009,31 +4986,31 @@ Removes data of a device from this KV store. This method uses a promise to retur **Example** - ``` - let kvStore; - const KEY_TEST_STRING_ELEMENT = 'key_test_string'; - const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; - try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('RemoveDeviceData put success'); - }).catch((err) => { - console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('RemoveDeviceData get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); - }catch(e) { - console.log('RemoveDeviceData e ' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('RemoveDeviceData put success'); + }).catch((err) => { + console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('removeDeviceData success'); + }).catch((err) => { + console.log('removeDeviceData fail ' + JSON.stringify(err)); + }); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('RemoveDeviceData get success data:' + data); + }).catch((err) => { + console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); + }); +}catch(e) { + console.log('RemoveDeviceData e ' + e); +} +``` ### sync8+ ### @@ -5041,6 +5018,7 @@ Removes data of a device from this KV store. This method uses a promise to retur sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void Manually triggers KV store synchronization synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5052,31 +5030,30 @@ Manually triggers KV store synchronization synchronously. | mode |[SyncMode](#syncmode) | Yes |Data synchronization mode, which can be **PUSH**, **PULL**, or **PUSH_PULL**. | | allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | - **Example** - ``` - let kvStore; - const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; - const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; - try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - kvStore.sync(devices, mode); - }); - }catch(e) { - console.log('Sync e' + e); - } - ``` +``` +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { + console.log('Sync put success'); + const devices = ['deviceList']; + const mode = distributedData.SyncMode.PULL_ONLY; + kvStore.sync(devices, mode); + }); +}catch(e) { + console.log('Sync e' + e); +} +``` ### on8+ ### -on(event: 'syncComplete', syncCallback: Callback<Arrary<[string, number]>>): void +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void Subscribes to the synchronization completion events. This method uses a synchronous callback to return the result. @@ -5087,25 +5064,26 @@ Subscribes to the synchronization completion events. This method uses a synchron | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| -| syncCallback |Callback { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); - }catch(e) { - console.log('syncComplete put e ' + e); - } - ``` + +``` +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log('syncComplete ' + data) + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('syncComplete put success'); + }).catch((error) => { + console.log('syncComplete put fail ' + error); + }); +}catch(e) { + console.log('syncComplete put e ' + e); +} +``` ### off8+ ### @@ -5121,23 +5099,22 @@ Unsubscribes from the synchronization completion events. This method uses a sync | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |'syncComplete' | Yes |Event triggered when the synchronization is complete.| -| syncCallback |Callback ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements event subscription, unsubscription, and triggering. - - -## Usage - - -Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. - - - -```js -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - } -} -``` - - -## EventHub.on - -on(event: string, callback: Function): void; - -Subscribes to an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | Yes| Callback invoked when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", () => { - console.log("call anonymous func 1"); - }); - // Result - // func1 is called - // call anonymous func 1 - this.context.eventHub.emit("123"); - } - func1() { - console.log("func1 is called"); - } - } - ``` - - -## EventHub.off - -off(event: string, callback?: Function): void; - -Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.off("123", this.func1); // Unsubscribe from func1. - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", this.func2); - this.context.eventHub.off("123"); // Unsubscribe from func1 and func2. - } - func1() { - console.log("func1 is called"); - } - func2() { - console.log("func2 is called"); - } - } - ``` - - -## EventHub.emit - -emit(event: string, ...args: Object[]): void; - -Triggers an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability' - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - // Result - // func1 is called,undefined,undefined - this.context.eventHub.emit("123"); - // Result - // func1 is called,1,undefined - this.context.eventHub.emit("123", 1); - // Result - // func1 is called,1,2 - this.context.eventHub.emit("123", 1, 2); - } - func1(a: string, b: string) { - console.log("func1 is called," + a + "," + b); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-extension-context.md index 5a9466444cd91cc39805c69028cd083fae8e4843..3a18f757b31e1e6ce33f31ae11f23c7ea840b0f8 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -1,7 +1,7 @@ # ExtensionContext > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Implements the extension context. This module is inherited from **Context**. @@ -9,6 +9,8 @@ Implements the extension context. This module is inherited from **Context**. ## Attributes +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core | +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP. | diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index e1bae182816c3b58d503b4f3e34ba36c30782d33..f5f75e537f719657bed473a63899b15cae850f4b 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -1,7 +1,7 @@ # ExtensionRunningInfo > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Provides extension running information. @@ -26,15 +26,15 @@ abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core - | Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an extension.| -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Extension start time.| -| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](#bundle-extensionabilitytype) | Yes| No| Extension type.| +| extension | ElementName | Yes| No| Information that matches an extension.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| startTime | number | Yes| No| Extension start time.| +| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| +| type | [bundle.ExtensionAbilityType](#bundleextensionabilitytype) | Yes| No| Extension type.| ## bundle.ExtensionAbilityType @@ -45,13 +45,13 @@ Enumerates extension types. | Name| Value| Description| | -------- | -------- | -------- | -| FORM | 0 | Extension information of the form type. | -| WORK_SCHEDULER | 1 | Extension information of the work scheduler type. | -| INPUT_METHOD | 2 | Extension information of the input method type. | -| SERVICE | 3 | Extension information of the service type. | -| ACCESSIBILITY | 4 | Extension information of the accessibility type. | -| DATA_SHARE | 5 | Extension information of the data share type. | -| FILE_SHARE | 6 | Extension information of the file share type. | -| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type. | -| WALLPAPER | 8 | Extension information of the wallpaper type. | -| UNSPECIFIED | 9 | Extension information of the unspecified type. | +| FORM | 0 | Extension information of the form type.< | +| WORK_SCHEDULER | 1 | Extension information of the work scheduler type.< | +| INPUT_METHOD | 2 | Extension information of the input method type.< | +| SERVICE | 3 | Extension information of the service type.< | +| ACCESSIBILITY | 4 | Extension information of the accessibility type.< | +| DATA_SHARE | 5 | Extension information of the data share type.< | +| FILE_SHARE | 6 | Extension information of the file share type.< | +| STATIC_SUBSCRIBER | 7 | Extension information of the static subscriber type.< | +| WALLPAPER | 8 | Extension information of the wallpaper type.< | +| UNSPECIFIED | 9 | Extension information of the unspecified type.< | diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 9e4324677acf9b4643b8980c65f3a20796dc0930..430e3a52acb154b0bacfb15e1b7aab238d4f094c 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -23,10 +23,10 @@ Starts an ability. This method uses a callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------------------- | ---- | ------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -62,9 +62,9 @@ Starts an ability. This method uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | --------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| **Example** @@ -100,14 +100,14 @@ Obtains a **dataAbilityHelper** object. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | ------ | ---- | ------------------------ | -| uri | string | Yes | URI of the file to open.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| uri | string | Yes | URI of the file to open.| **Return value** -| Type | Description | -| ----------------- | -------------------------------------------- | +| Type | Description | +| ----------------- | ------------------------------- | | DataAbilityHelper | A utility class used to help other abilities access the Data ability.| **Example** @@ -129,10 +129,10 @@ Starts an ability. This method uses a callback to return the execution result wh **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | --------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | **Example** @@ -166,14 +166,14 @@ Starts an ability. This method uses a promise to return the execution result whe **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | ------------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ------------- | +| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| **Return value** -| Type | Description | -| ----------------------------------------- | -------------- | +| Type | Description | +| ---------------------------------------- | ------- | | Promise\<[AbilityResult](#abilityresult)> | Promised returned with the execution result.| **Example** @@ -222,10 +222,10 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------- | ---- | ------------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | -------------- | +| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -270,14 +270,14 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------- | ---- | ------------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------------- | ---- | ------------- | +| parameter | [AbilityResult](#abilityresult) | Yes | Ability to start.| **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------- | | Promise\ | Promise used to return the result.| **Example** @@ -327,9 +327,9 @@ Checks whether the main window of this ability has the focus. This method uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| **Example** @@ -350,8 +350,8 @@ Checks whether the main window of this ability has the focus. This method uses a **Return value** -| Type | Description | -| ----------------- | ---------------------------------------------------------- | +| Type | Description | +| ----------------- | ------------------------------------- | | Promise\ | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| **Example** @@ -375,9 +375,9 @@ Obtains the **Want** object sent from this ability. This method uses a callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ------------------ | -| callback | AsyncCallback\<[Want](#want)> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------- | ---- | --------- | +| callback | AsyncCallback\<[Want](#want)> | Yes | Callback used to return the result.| **Example** @@ -398,8 +398,8 @@ Obtains the **Want** object sent from this ability. This method uses a promise t **Return value** -| Type | Description | -| ----------------------- | ------------------------- | +| Type | Description | +| ----------------------- | ---------------- | | Promise\<[Want](#want)> | Promise used to return the result.| **Example** @@ -421,8 +421,8 @@ Obtains the application context. **Return value** -| Type | Description | -| ------- | -------------------- | +| Type | Description | +| ------- | ---------- | | Context | Application context returned.| **Example** @@ -445,9 +445,9 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | -------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -468,8 +468,8 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Return value** -| Type | Description | -| -------------- | ------------------------- | +| Type | Description | +| -------------- | ---------------- | | Promise\ | Promise used to return the result.| **Example** @@ -490,35 +490,35 @@ Connects this ability to a specific Service ability. This method uses a callback **Parameters** -| Name | Type | Mandatory| Description | -| ------- | -------------- | ---- | ---------------------------- | -| request | [Want](#want) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------- | -------------- | ---- | --------------------- | +| request | [Want](#want) | Yes | Service ability to connect.| +| options | ConnectOptions | Yes | Callback used to return the result. | Want **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable | Type | Mandatory| Description | -| ------------ | -------- | -------- | ---- | ---------------------------------- | -| deviceId | Read-only | string | No | Device ID of the Service ability to connect. The default value is the local device ID.| -| bundleName | Read-only | string | Yes | Bundle name of the Service ability to connect. | -| abilityName | Read-only | string | Yes | Class name of the Service ability to connect. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ---------------------------------------- | +| deviceId | Read-only | string | No | Device ID of the Service ability to connect. The default value is the local device ID.| +| bundleName | Read-only | string | Yes | Bundle name of the Service ability to connect. | +| abilityName | Read-only | string | Yes | Class name of the Service ability to connect. | ConnectOptions **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------ | -------- | -------- | ---- | ---------------------------------- | -| onConnect | Read-only | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | Read-only | function | Yes | Callback invoked when the connection fails. | -| onFailed | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------ | ---- | -------- | ---- | ------------------------- | +| onConnect | Read-only | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect | Read-only | function | Yes | Callback invoked when the connection fails. | +| onFailed | Read-only | function | Yes | Callback invoked when **connectAbility** fails to be called.| **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ------ | -------------------- | | number | Returns the ID of the Service ability connected.| **Example** @@ -559,10 +559,10 @@ Disconnects this ability from a specific Service ability. This method uses a cal **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------- | ---- | ------------------------------ | -| connection | number | Yes | ID of the Service ability to disconnect.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | -------------------- | ---- | ----------------------- | +| connection | number | Yes | ID of the Service ability to disconnect.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -606,14 +606,14 @@ Disconnects this ability from a specific Service ability. This method uses a pro **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------------------ | -| connection | number | Yes | ID of the Service ability to disconnect.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ----------------------- | +| connection | number | Yes | ID of the Service ability to disconnect.| **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------- | | Promise\ | Promise used to return the result.| **Example** @@ -658,16 +658,14 @@ Obtains the window corresponding to this ability. This method uses a callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the window.| **Example** ```javascript -GetWindow(){ - featureAbility.getWindow() - } +featureAbility.getWindow() ``` ## featureAbility.getWindow7+ @@ -680,20 +678,148 @@ Obtains the window corresponding to this ability. This method uses a promise to **Return value** -| Type | Description | -| ----------------- | ---------------------------------------------------------- | +| Type | Description | +| ----------------------- | ----------------------------- | | Promise\ | Promise used to return the window.| **Example** ```javascript -GetWindowPromise(){ - featureAbility.getWindow().then((data) => { - console.info("=============getWindowPromise========== " + JSON.stringify(data)); - }); - } +featureAbility.getWindow().then((data) => { + console.info("=============getWindowPromise========== " + JSON.stringify(data)); +}); +``` + +## ConnectOptions.onConnect7+ + +onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void; + +Callback invoked when the connection is successful. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ----------------- | ---- | -------- | +| elementName | ElementName | Yes | Element name. | +| remote | rpc.IRemoteObject | Yes | RPC remote object.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +## ConnectOptions.onDisconnect7+ + +onDisconnect(elementName: ElementName): void; + +Callback invoked when the connection fails. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ----------- | ---- | ---- | +| elementName | ElementName | Yes | Element name.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); ``` +## ConnectOptions.onFailed7+ + +onFailed(code: number): void; + +Callback invoked when **connectAbility** fails to be called. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| code | number | Yes | Number type.| + +**Example** + +```javascript +import rpc from '@ohos.rpc' +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: "", + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + + + + ## AbilityWindowConfiguration @@ -705,13 +831,15 @@ The value is obtained through the **featureAbility.AbilityWindowConfiguration** featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED ``` -| Name | Name| Description | -| --------------------------- | ---- | ---------- | -| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Name | Description | +| ---------------------------------------- | ---- | ---------------------------------------- | +| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.| +| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode. | +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.| ## AbilityStartSetting @@ -726,34 +854,40 @@ The value is obtained through the **featureAbility.AbilityStartSetting** API. featureAbility.AbilityStartSetting.BOUNDS_KEY ``` -| Name | Name | Description | -| --------------- | --------------- | -------------------------- | -| BOUNDS_KEY7+ | "abilityBounds" | Ability window size.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| WINDOW_MODE_KEY7+ | "windowMode" | Ability window display mode.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel | -| DISPLAY_ID_KEY7+ | "displayId" | Display device ID.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Name | Description | +| ---------------------------- | --------------- | ---------------------------------------- | +| BOUNDS_KEY7+ | "abilityBounds" | Ability window size.| +| WINDOW_MODE_KEY7+ | "windowMode" | Ability window display mode.| +| DISPLAY_ID_KEY7+ | "displayId" | Display device ID.| ## ErrorCode Enumerates error codes. -| Variable | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| NO_ERROR7+ | 0 | No error occurs.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| INVALID_PARAMETER7+ | -1 | Invalid parameter.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| ABILITY_NOT_FOUND7+ | -2 | The ability is not found.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| PERMISSION_DENY7+ | -3 | The request is denied.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Variable | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| NO_ERROR7+ | 0 | No error occurs.| +| INVALID_PARAMETER7+ | -1 | Invalid parameter.| +| ABILITY_NOT_FOUND7+ | -2 | The ability is not found.| +| PERMISSION_DENY7+ | -3 | The request is denied.| ## DataAbilityOperationType Enumerates operation types of the Data ability. -| Variable | Value | Description | -| ----------------------------- | ---- | ------------------------------------------------------------ | -| TYPE_INSERT7+ | 1 | Insert operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_UPDATE7+ | 2 | Update operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_DELETE7+ | 3 | Deletion operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| TYPE_ASSERT7+ | 4 | Assert operation.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Variable | Value | Description | +| ------------------------ | ---- | ---------------------------------------- | +| TYPE_INSERT7+ | 1 | Insert operation.| +| TYPE_UPDATE7+ | 2 | Update operation.| +| TYPE_DELETE7+ | 3 | Deletion operation.| +| TYPE_ASSERT7+ | 4 | Assert operation.| @@ -761,56 +895,56 @@ Enumerates operation types of the Data ability. **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ---------- | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| resultCode7+ | Read-only | number | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| -| want7+ | Read-only | [Want](#want) | No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------------------- | ---- | ------------- | ---- | ------------------------------------- | +| resultCode7+ | Read-only | number | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| +| want7+ | Read-only | [Want](#want) | No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | ## StartAbilityParameter **System capability**: SystemCapability.AbilityRuntime.FAModel -| Name | Readable/Writable| Type | Mandatory| Description | -| ------------------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| want | Read-only | [Want](#want) | Yes | Information about the ability to start. | -| abilityStartSetting | Read-only | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------------- | ---- | -------------------- | ---- | -------------------------------------- | +| want | Read-only | [Want](#want) | Yes | Information about the ability to start. | +| abilityStartSetting | Read-only | {[key: string]: any} | No | Special attribute of the ability to start. This attribute can be passed in the method call.| ## Want **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId8+ | Read-only | string | No | ID of the device that runs the ability. | -| bundleName8+ | Read-only | string | No | Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| -| abilityName8+ | Read-only | string | No | Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| -| uri8+ | Read-only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type8+ | Read-only | string | No | MIME type, for example, text/plain or image/*. | -| flags8+ | Read-only | number | No | How the **Want** object will be handled. By default, a number is passed. For details, see [flags](#flags).| -| action8+ | Read-only | string | No | Action option. | -| parameters8+ | Read-only | {[key: string]: any} | No | List of parameters in a **Want** object. | -| entities8+ | Read-only | Array\ | No | List of entities. | +| Name | Readable/Writable| Type | Mandatory| Description | +| -------------------------------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read-only | string | No | ID of the device that runs the ability. | +| bundleName | Read-only | string | No | Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read-only | string | No | Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| uri | Read-only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | Read-only | string | No | MIME type, for example, text/plain or image/*. | +| flags | Read-only | number | No | How the **Want** object will be handled. By default, a number is passed. For details, see [flags](#flags).| +| action | Read-only | string | No | Action option. | +| parameters | Read-only | {[key: string]: any} | No | List of parameters in the **Want** object. | +| entities | Read-only | Array\ | No | List of entities. | ## flags **System capability**: SystemCapability.Ability.AbilityBase -| Name | Name | Description | -| ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | -| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | -| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | -| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | -| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | -| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object passed to **ohos.app.Context#startAbility** and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | +| Name | Name | Description | +| ------------------------------------ | ---------- | ---------------------------------------- | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 67e1d8d19ef2eb70aa14c8a9a18e5281367b974f..f574cc158968757560d2821e960819e3ea4e9b49 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -45,13 +45,13 @@ Asynchronously obtains file information. This method uses a promise to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the file information obtained.| - Example @@ -73,10 +73,10 @@ Asynchronously obtains file information. This method uses a callback to return t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked to return the file information obtained.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked to return the file information obtained.| - Example ```js @@ -95,14 +95,14 @@ Synchronously obtains file information. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | File information obtained.| - Example @@ -121,13 +121,13 @@ Asynchronously opens a directory. This method uses a promise to return the resul **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------- | + | path | string | Yes | Absolute path of the directory to open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------- | -------- | | Promise<[Dir](#dir)> | A **Dir** instance corresponding to the directory.| - Example @@ -149,10 +149,10 @@ Asynchronously opens a directory. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| - | callback | AsyncCallback<[Dir](#dir)> | Yes| Callback invoked when the directory is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | -------------------------------- | ---- | -------------- | + | path | string | Yes | Absolute path of the directory to open. | + | callback | AsyncCallback<[Dir](#dir)> | Yes | Callback invoked when the directory is open asynchronously.| - Example ```js @@ -173,13 +173,13 @@ Synchronously opens a directory. - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to open.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------- | + | path | string | Yes | Absolute path of the directory to open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ----------- | -------- | | [Dir](#dir) | A **Dir** instance corresponding to the directory.| - Example @@ -199,14 +199,14 @@ Asynchronously checks whether the current process can access a file. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -228,11 +228,11 @@ Asynchronously checks whether the current process can access a file. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is asynchronously checked.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously checked. | - Example ```js @@ -251,10 +251,10 @@ Synchronously checks whether the current process can access the specified file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | No| Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | No | Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is **0**.
The options are as follows:
- **0**: check whether the file exists.
- **1**: check whether the current process has the execute permission on the file.
- **2**: check whether the current process has the write permission on the file.
- **4**: check whether the current process has the read permission on the file.| - Example ```js @@ -275,13 +275,13 @@ Asynchronously closes a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -304,10 +304,10 @@ Asynchronously closes a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is closed asynchronously.| - Example ```js @@ -327,9 +327,9 @@ Synchronously closes a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to close.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to close.| - Example ```js @@ -346,8 +346,8 @@ Asynchronously closes the stream. This method uses a promise to return the resul **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -369,9 +369,9 @@ Asynchronously closes the stream. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback invoked when the stream is closed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| - Example ```js @@ -390,15 +390,15 @@ Asynchronously copies a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -420,12 +420,12 @@ Asynchronously copies a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is copied asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is copied asynchronously. | - Example ```js @@ -444,11 +444,11 @@ Synchronously copies a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | src | string \| number | Yes| Path or file descriptor of the file to copy.| - | dest | string \| number | Yes| Path or file descriptor of the new file.| - | mode | number | No| Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| + | Name | Type | Mandatory | Description | + | ---- | -------------------------- | ---- | ---------------------------------------- | + | src | string \| number | Yes | Path or file descriptor of the file to copy. | + | dest | string \| number | Yes | Path or file descriptor of the new file. | + | mode | number | No | Option for overwriting the file of the same name in the destination path. The default value is **0**, which is the only value supported.
**0**: Completely overwrite the file with the same name and truncate the part that is not overwritten.| - Example ```js @@ -465,14 +465,14 @@ Asynchronously creates a directory. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -494,11 +494,11 @@ Asynchronously creates a directory. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the directory is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is created asynchronously. | - Example ```js @@ -519,10 +519,10 @@ Synchronously creates a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to create.| - | mode | number | No| Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the directory to create. | + | mode | number | No | Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o775**.
- **0o775**: The owner has the read, write, and execute permissions, and other users have the read and execute permissions.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -539,15 +539,15 @@ Asynchronously opens a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | No| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | No| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ----- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | ----------- | | Promise<number> | File descriptor of the file opened.| - Example @@ -569,12 +569,12 @@ Asynchronously opens a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | Yes| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | Yes | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | - Example ```js @@ -593,15 +593,15 @@ Synchronously opens a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | flags | number | No| Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| - | mode | number | No| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| + | Name | Type | Mandatory | Description | + | ----- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | flags | number | No | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** points to a directory, throw an exception.

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| + | mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.
The file permissions on newly created files are affected by umask, which is set as the process starts. Currently, the modification of umask is not open.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------- | | number | File descriptor of the file opened.| - Example @@ -623,15 +623,15 @@ Asynchronously reads data from a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------------- | ------ | | Promise<[ReadOut](#readout)> | Data read.| - Example @@ -659,12 +659,12 @@ Asynchronously reads data from a file. This method uses a callback to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes| Callback invoked when the data is read asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously. | - Example ```js @@ -691,15 +691,15 @@ Synchronously reads data from a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to read.| - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to read. | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------- | | number | Length of the data read.| - Example @@ -719,13 +719,13 @@ Asynchronously deletes a directory. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the directory to delete.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -747,10 +747,10 @@ Asynchronously deletes a directory. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the directory is deleted asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | path | string | Yes | Absolute path of the directory to delete. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the directory is deleted asynchronously.| - Example ```js @@ -769,9 +769,9 @@ Synchronously deletes a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the directory to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the directory to delete.| - Example ```js @@ -788,13 +788,13 @@ Asynchronously deletes a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the file to delete.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -816,10 +816,10 @@ Asynchronously deletes a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is deleted asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------ | + | path | string | Yes | Absolute path of the file to delete. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is deleted asynchronously.| - Example ```js @@ -840,9 +840,9 @@ Synchronously deletes a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to delete.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the file to delete.| - Example ```js @@ -864,15 +864,15 @@ Asynchronously writes data into a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | -------- | | Promise<number> | Length of the data written in the file.| - Example @@ -900,12 +900,12 @@ Asynchronously writes data into a file. This method uses a callback to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - | callback | AsyncCallback<number> | Yes| Callback invoked when the data is written asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | - Example ```js @@ -932,15 +932,15 @@ Synchronously writes data into a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to write.| - | buffer | ArrayBuffer \| string | Yes| Data to write. It can be a string or data from a buffer.| - | options | Object | No| The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the file to write. | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------- | | number | Length of the data written in the file.| - Example @@ -959,14 +959,14 @@ Asynchronously calculates the hash value of a file. This method uses a promise t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | algorithm | string | Yes| Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| + | Name | Type | Mandatory | Description | + | --------- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | -------------------------- | | Promise<string> | Promise used to return the hash value of the file. The hash value is a hexadecimal string consisting of digits and uppercase letters.| - Example @@ -988,11 +988,11 @@ Asynchronously calculates the hash value of a file. This method uses a callback **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | algorithm | string | Yes| Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| - | callback | AsyncCallback<string> | Yes| Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| + | Name | Type | Mandatory | Description | + | --------- | --------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**.**sha256** is recommended for security purposes.| + | callback | AsyncCallback<string> | Yes | Callback used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.| - Example ```js @@ -1013,14 +1013,14 @@ Asynchronously changes the file permissions based on its path. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1042,11 +1042,11 @@ Asynchronously changes the file permissions based on its path. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file permissions are changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file permissions are changed asynchronously. | - Example ```js @@ -1065,10 +1065,10 @@ Synchronously changes the file permissions based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -1085,12 +1085,12 @@ Asynchronously obtains file status information based on the file descriptor. Thi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| - Return value - | Type| Description| + | Type | Description | | -------- | -------- | | Promise<[Stat](#stat)> | Promise used to return the file status information obtained.| @@ -1113,10 +1113,10 @@ Asynchronously obtains file status information based on the file descriptor. Thi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked when the file status information is obtained asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | ---------------- | + | fd | number | Yes | File descriptor of the target file. | + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked when the file status information is obtained asynchronously.| - Example ```js @@ -1136,13 +1136,13 @@ Synchronously obtains file status information based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | File status information obtained.| - Example @@ -1161,14 +1161,14 @@ Asynchronously truncates a file based on the file descriptor. This method uses a **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1191,11 +1191,11 @@ Asynchronously truncates a file based on the file descriptor. This method uses a **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is truncated asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | - Example ```js @@ -1214,10 +1214,10 @@ Synchronously truncates a file based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to truncate.| - | len | number | No| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | fd | number | Yes | File descriptor of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| - Example ```js @@ -1234,14 +1234,14 @@ Asynchronously truncates a file based on its path. This method uses a promise to **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1263,11 +1263,11 @@ Asynchronously truncates a file based on its path. This method uses a callback t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | Yes| File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file is truncated asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | Yes | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback invoked when the file is truncated asynchronously. | - Example ```js @@ -1286,10 +1286,10 @@ Synchronously truncates a file based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the file to truncate.| - | len | number | No| File length, in bytes, after truncation.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------- | + | path | string | Yes | Absolute path of the file to truncate. | + | len | number | No | File length, in bytes, after truncation.| - Example ```js @@ -1310,14 +1310,14 @@ Asynchronously reads the text of a file. This method uses a promise to return th **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | -------- | ------ | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------- | ---------- | | Promise<string> | Promise used to return the content of the file read.| - Example @@ -1343,11 +1343,11 @@ Asynchronously reads the text of a file. This method uses a callback to return t **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - | callback | AsyncCallback<string> | Yes| Callback invoked when the file is read asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<string> | Yes | Callback invoked when the file is read asynchronously. | - Example ```js @@ -1370,15 +1370,15 @@ Synchronously reads the text of a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filePath | string | Yes| Absolute path of the file to read.| - | options | Object | No| The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| + | Name | Type | Mandatory | Description | + | -------- | ------ | ---- | ---------------------------------------- | + | filePath | string | Yes | Absolute path of the file to read. | + | options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **encoding** (string): format of the data (string) to be encoded. The default value is **utf-8**, which is the only value supported.| - Return value - | Type| Description| - | -------- | -------- | - | <string>| Content of the file read.| + | Type | Description | + | ------ | -------------------- | + | string | Content of the file read.| - Example ```js @@ -1395,13 +1395,13 @@ Asynchronously obtains link status information. This method uses a promise to re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------- | ---------- | | Promise<[Stat](#stat)> | Promise used to return the link status obtained.| - Example @@ -1423,10 +1423,10 @@ Asynchronously obtains link status information. This method uses a callback to r **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| - | callback | AsyncCallback<[Stat](#stat)> | Yes| Callback invoked when the link status information is obtained asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------- | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| + | callback | AsyncCallback<[Stat](#stat)> | Yes | Callback invoked when the link status information is obtained asynchronously. | - Example ```js @@ -1445,13 +1445,13 @@ Synchronously obtains link status information. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file, pointing to the link status.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------------- | + | path | string | Yes | Absolute path of the target file, pointing to the link status.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------- | ---------- | | [Stat](#stat) | Link status obtained.| - Example @@ -1473,14 +1473,14 @@ Asynchronously reads data from a file. This method uses a promise to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ---------------------------------- | ------ | | Promise<[ReadOut](#readout)> | Data read.| - Example @@ -1506,11 +1506,11 @@ Asynchronously reads data from a file. This method uses a callback to return the **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer | Yes| Buffer used to store the file data read.| - | options | Object | No| The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| - | callback | AsyncCallback<[ReadOut](#readout)> | Yes| Callback invoked when the data is read asynchronously from the file.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file data read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when the data is read asynchronously from the file. | - Example ```js @@ -1532,19 +1532,19 @@ Asynchronously renames a file. This method uses a promise to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldPath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------ | + | oldPath | string | Yes | Absolute path of the file to rename.| + | newPath | String | Yes | Absolute path of the file renamed. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example ```js - fileio.rename(oldPath, Newpath).then(function() { + fileio.rename(oldPath, newPath).then(function() { console.info("rename successfully"); }).catch(function(err){ console.info("rename failed with error:"+ err); @@ -1561,15 +1561,15 @@ Asynchronously renames a file. This method uses a callback to return the result. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldpath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| - | Callback | AsyncCallback<void> | Yes| Callback invoked when the file is asynchronously renamed.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | oldPath | string | Yes | Absolute path of the file to rename. | + | newPath | String | Yes | Absolute path of the file renamed. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is asynchronously renamed.| - Example ```js - fileio.rename(oldpath, Newpath, function(err){ + fileio.rename(oldPath, newPath, function(err){ }); ``` @@ -1583,14 +1583,14 @@ Synchronously renames a file. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | oldPath | string | Yes| Absolute path of the file to rename.| - | Newpath | String | Yes| Absolute path of the file renamed.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | oldPath | string | Yes | Absolute path of the file to rename.| + | newPath | String | Yes | Absolute path of the file renamed. | - Example ```js - fileio.renameSync(oldpath, newpath); + fileio.renameSync(oldPath, newPath); ``` @@ -1603,13 +1603,13 @@ Asynchronously synchronizes a file. This method uses a promise to return the res **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -1631,10 +1631,10 @@ Asynchronously synchronizes a file. This method uses a callback to return the re **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| - | Callback | AsyncCallback<void> | Yes| Callback invoked when the file is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the file to synchronize. | + | Callback | AsyncCallback<void> | Yes | Callback invoked when the file is synchronized in asynchronous mode.| - Example ```js @@ -1653,9 +1653,9 @@ Synchronizes a file in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Example ```js @@ -1672,13 +1672,13 @@ Asynchronously synchronizes data in a file. This method uses a promise to return **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1700,10 +1700,10 @@ Asynchronously synchronizes data in a file. This method uses a callback to retur **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file data is synchronized in asynchronous mode.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ----------------- | + | fd | number | Yes | File descriptor of the file to synchronize. | + | callback | AsyncCallback <void> | Yes | Callback invoked when the file data is synchronized in asynchronous mode.| - Example ```js @@ -1722,9 +1722,9 @@ Synchronizes data in a file in synchronous mode. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the file to synchronize.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the file to synchronize.| - Example ```js @@ -1741,14 +1741,14 @@ Asynchronously creates a symbolic link based on a path. This method uses a promi **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link.| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1770,11 +1770,11 @@ Asynchronously creates a symbolic link based on a path. This method uses a callb **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the symbolic link is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------- | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the symbolic link is created asynchronously.| - Example ```js @@ -1793,10 +1793,10 @@ Synchronously creates a symbolic link based on a specified path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | target | string | Yes| Absolute path of the symbolic link.| - | srcPath | string | Yes| Absolute path of the referenced file or directory contained in the symbolic link.| + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ------------ | + | target | string | Yes | Absolute path of the symbolic link. | + | srcPath | string | Yes | Absolute path of the referenced file or directory contained in the symbolic link.| - Example ```js @@ -1813,15 +1813,15 @@ Asynchronously changes the file owner based on its path. This method uses a prom **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New user ID (UID).| - | gid | number | Yes| New group ID (GID).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New user ID (UID). | + | gid | number | Yes | New group ID (GID).| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1844,12 +1844,12 @@ Asynchronously changes the file owner based on its path. This method uses a call **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -1869,11 +1869,11 @@ Synchronously changes the file owner based on its path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -1891,13 +1891,13 @@ Asynchronously creates a temporary directory. This method uses a promise to retu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | --------------------- | ---------- | | Promise<string> | Unique path generated.| - Example @@ -1919,10 +1919,10 @@ Asynchronously creates a temporary directory. This method uses a callback to ret **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| - | callback | AsyncCallback<string> | Yes| Callback invoked when a temporary directory is created asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------- | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| + | callback | AsyncCallback<string> | Yes | Callback invoked when a temporary directory is created asynchronously. | - Example ```js @@ -1941,13 +1941,13 @@ Synchronously creates a temporary directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | prefix | string | Yes| A randomly generated string used to replace "XXXXXX" in a directory.| + | Name | Type | Mandatory | Description | + | ------ | ------ | ---- | --------------------------- | + | prefix | string | Yes | A randomly generated string used to replace "XXXXXX" in a directory.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------ | ---------- | | string | Unique path generated.| - Example @@ -1965,14 +1965,14 @@ Asynchronously changes the file permissions based on the file descriptor. This m **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result asynchronously. An empty value is returned.| - Example @@ -1994,11 +1994,11 @@ Asynchronously changes the file permissions based on the file descriptor. This m **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - | callback | AsyncCallback <void> | Yes| Callback invoked when the file permissions are changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | callback | AsyncCallback <void> | Yes | Callback invoked when the file permissions are changed asynchronously. | - Example ```js @@ -2017,10 +2017,10 @@ Synchronously changes the file permissions based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | number | Yes| Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | number | Yes | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| - Example ```js @@ -2037,14 +2037,14 @@ Asynchronously opens a stream based on the file path. This method uses a promise **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| - Example @@ -2066,11 +2066,11 @@ Asynchronously opens a stream based on the file path. This method uses a callbac **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - | callback | AsyncCallback<[Stream](#stream7)> | Yes| Callback invoked when the stream is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------------------- | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | callback | AsyncCallback<[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | - Example ```js @@ -2089,14 +2089,14 @@ Synchronously opens a stream based on the file path. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | path | string | Yes | Absolute path of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| - Example @@ -2114,14 +2114,14 @@ Asynchronously opens a stream based on the file descriptor. This method uses a p **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | --------------------------------- | --------- | | Promise<[Stream](#stream7)> | Promise used to return the result.| - Example @@ -2143,11 +2143,11 @@ Asynchronously opens a stream based on the file descriptor. This method uses a c **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - | callback | AsyncCallback <[Stream](#stream7)> | Yes| Callback invoked when the stream is open asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | callback | AsyncCallback <[Stream](#stream7)> | Yes | Callback invoked when the stream is open asynchronously. | - Example ```js @@ -2166,14 +2166,14 @@ Synchronously opens a stream based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | mode | string | Yes| - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ---------------------------------------- | + | fd | number | Yes | File descriptor of the target file. | + | mode | string | Yes | - **r**: Open a file for reading. The file must exist.
- **r+**: Open a file for both reading and writing. The file must exist.
- **w**: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
- **w+**: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
- **a**: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
- **a+**: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).| - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | ------------------ | --------- | | [Stream](#stream7) | Stream opened.| - Example @@ -2191,15 +2191,15 @@ Asynchronously changes the file owner based on the file descriptor. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -2222,12 +2222,12 @@ Asynchronously changes the file owner based on the file descriptor. This method **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | fd | number | Yes | File descriptor of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -2247,11 +2247,11 @@ Synchronously changes the file owner based on the file descriptor. **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -2269,15 +2269,15 @@ Asynchronously changes the file owner based on the file path, changes the owner **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------- | ---------------------------- | | Promise<void> | Promise used to return the result. An empty value is returned.| - Example @@ -2300,12 +2300,12 @@ Asynchronously changes the file owner based on the file path, changes the owner **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the file owner is changed asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | --------------- | + | path | string | Yes | Absolute path of the target file. | + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | + | callback | AsyncCallback<void> | Yes | Callback invoked when the file owner is changed asynchronously.| - Example ```js @@ -2325,11 +2325,11 @@ Synchronously changes the file owner based on the file path and changes the owne **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Absolute path of the target file.| - | uid | number | Yes| New UID.| - | gid | number | Yes| New GID.| + | Name | Type | Mandatory | Description | + | ---- | ------ | ---- | ----------- | + | path | string | Yes | Absolute path of the target file.| + | uid | number | Yes | New UID. | + | gid | number | Yes | New GID. | - Example ```js @@ -2347,15 +2347,15 @@ Asynchronously listens for the changes of a file or directory. This method uses **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | filename | string | Yes| Absolute path of the target file.| - | events | Number | Yes| - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| - | callback | AsyncCallback<number > | Yes| Called each time a change is detected.| + | Name | Type | Mandatory | Description | + | -------- | --------------------------------- | ---- | ---------------------------------------- | + | filename | string | Yes | Absolute path of the target file. | + | events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| + | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | - Return value - | Name| Description| - | -------- | -------- | + | Name | Description | + | -------------------- | ---------- | | [Watcher](#watcher7) | Instance for listening for a file change event.| - Example @@ -2372,11 +2372,11 @@ Obtains the file read result. This class applies only to the **read()** method. **System capability**: SystemCapability.FileManagement.File.FileIO -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| bytesRead | number | Yes| Yes| Length of the data read.| -| offset | number | Yes| Yes| Position of the buffer to which the data will be read in reference to the start address of the buffer.| -| buffer | ArrayBufer | Yes| Yes| Buffer for storing the data read.| +| Name | Type | Readable | Writable | Description | +| --------- | ---------- | ---- | ---- | ----------------- | +| bytesRead | number | Yes | Yes | Length of the data read. | +| offset | number | Yes | Yes | Position of the buffer to which the data will be read in reference to the start address of the buffer.| +| buffer | ArrayBufer | Yes | Yes | Buffer for storing the data read. | ## Stat @@ -2387,20 +2387,20 @@ Provides detailed file information. Before calling a method of the **Stat** clas ### Attributes -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| dev | number | Yes| No| Major device number.| -| ino | number | Yes| No| File ID. Different files on the same device have different **ino**s.| -| mode | number | Yes| No| File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| -| nlink | number | Yes| No| Number of hard links in the file.| -| uid | number | Yes| No| User ID, that is ID of the file owner.| -| gid | number | Yes| No| Group ID, that is, ID of the user group of the file.| -| rdev | number | Yes| No| Minor device number.| -| size | number | Yes| No| File size, in bytes. This parameter is valid only for regular files.| -| blocks | number | Yes| No| Number of blocks occupied by a file. Each block is 512 bytes.| -| atime | number | Yes| No| Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| -| mtime | number | Yes| No| Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| -| ctime | number | Yes| No| Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| dev | number | Yes | No | Major device number. | +| ino | number | Yes | No | File ID. Different files on the same device have different **ino**s. | +| mode | number | Yes | No | File type and permissions. The first four bits indicate the file type, and the last 12 bits indicate the permissions. The bit fields are described as follows:
- **0o170000**: mask used to obtain the file type.
- **0o140000**: The file is a socket.
- **0o120000**: The file is a symbolic link.
- **0o100000**: The file is a regular file.
- **0o060000**: The file is a block device.
- **0o040000**: The file is a directory.
- **0o020000**: The file is a character device.
- **0o010000**: The file is a named pipe (FIFO).
- **0o0700**: mask used to obtain the owner permissions.
- **0o0400**: The owner has the permission to read a regular file or a directory entry.
- **0o0200**: The owner has the permission to write a regular file or create and delete a directory entry.
- **0o0100**: The owner has the permission to execute a regular file or search for the specified path in a directory.
- **0o0070**: mask used to obtain the user group permissions.
- **0o0040**: The user group has the permission to read a regular file or a directory entry.
- **0o0020**: The user group has the permission to write a regular file or create and delete a directory entry.
- **0o0010**: The user group has the permission to execute a regular file or search for the specified path in a directory.
- **0o0007**: mask used to obtain the permissions of other users.
- **0o0004**: Other users have the permission to read a regular file or a directory entry.
- **0o0002**: Other users have the permission to write a regular file or create and delete a directory entry.
- **0o0001**: Other users have the permission to execute a regular file or search for the specified path in a directory.| +| nlink | number | Yes | No | Number of hard links in the file. | +| uid | number | Yes | No | User ID, that is ID of the file owner. | +| gid | number | Yes | No | Group ID, that is, ID of the user group of the file. | +| rdev | number | Yes | No | Minor device number. | +| size | number | Yes | No | File size, in bytes. This parameter is valid only for regular files. | +| blocks | number | Yes | No | Number of blocks occupied by a file. Each block is 512 bytes. | +| atime | number | Yes | No | Time of the last access to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| mtime | number | Yes | No | Time of the last modification to the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | +| ctime | number | Yes | No | Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970. | ### isBlockDevice @@ -2412,8 +2412,8 @@ Checks whether the current directory entry is a block special file. A block spec **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ---------------- | | boolean | Whether the directory entry is a block special file.| - Example @@ -2431,8 +2431,8 @@ Checks whether the current directory entry is a character special file. A charac **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------- | | boolean | Whether the directory entry is a character special file.| - Example @@ -2450,8 +2450,8 @@ Checks whether a directory entry is a directory. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ------------- | | boolean | Whether the directory entry is a directory.| - Example @@ -2469,8 +2469,8 @@ Checks whether the current directory entry is a named pipe (or FIFO). Named pipe **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------- | | boolean | Whether the directory entry is a FIFO.| - Example @@ -2488,8 +2488,8 @@ Checks whether a directory entry is a regular file. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------- | | boolean | Whether the directory entry is a regular file.| - Example @@ -2507,8 +2507,8 @@ Checks whether a directory entry is a socket. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------- | | boolean | Whether the directory entry is a socket.| - Example @@ -2526,8 +2526,8 @@ Checks whether a directory entry is a symbolic link. **System capability**: SystemCapability.FileManagement.File.FileIO - Return value - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------- | | boolean | Whether the directory entry is a symbolic link.| - Example @@ -2564,9 +2564,9 @@ Asynchronously stops **watcher**. This method uses a callback to return the resu **System capability**: SystemCapability.FileManagement.File.FileIO - Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback invoked when **watcher** is stopped asynchronously.| + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ---------------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when **watcher** is stopped asynchronously.| - Example ```js @@ -2574,3 +2574,564 @@ Asynchronously stops **watcher**. This method uses a callback to return the resu // Do something. }); ``` + + +## Stream7+ + +File stream. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. + + +### close7+ + +close(): Promise<void> + +Asynchronously closes the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream close result.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.close().then(function(){ + console.info("close fileStream successfully"); + }).catch(function(err){ + console.info("close fileStream failed with error:"+ err); + }); + ``` + + +### close7+ + +close(callback: AsyncCallback<void>): void + +Asynchronously closes the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | ------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is closed asynchronously.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.close(function (err) { + // do something + }); + ``` + + +### closeSync + +closeSync(): void + +Synchronously closes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.closeSync(); + ``` + + +### flush7+ + +flush(): Promise<void> + +Asynchronously flushes the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------------------- | ------------- | + | Promise<void> | Promise used to return the stream flushing result.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flush().then(function (){ + console.info("flush successfully"); + }).catch(function(err){ + console.info("flush failed with error:"+ err); + }); + ``` + + +### flush7+ + +flush(callback: AsyncCallback<void>): void + +Asynchronously flushes the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------- | ---- | -------------- | + | callback | AsyncCallback<void> | Yes | Callback invoked when the stream is asynchronously flushed.| + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flush(function (err) { + // do something + }); + ``` + + +### flushSync7+ + +flushSync(): void + +Synchronously flushes the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let ss= fileio.createStreamSync(path); + ss.flushSync(); + ``` + + +### write7+ + +write(buffer: ArrayBuffer | string, options?: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}): Promise<number> + +Asynchronously writes data into the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + +- Return value + | Type | Description | + | --------------------- | -------- | + | Promise<number> | Length of the data written in the file.| + +- Example + ```js + let ss= fileio.createStreamSync(fpath, "r+"); + ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ + console.info("write successfully:"+ number); + }).catch(function(err){ + console.info("write failed with error:"+ err); + }); + ``` + + +### write7+ + +write(buffer: ArrayBuffer | string, options: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}, callback: AsyncCallback<number>): void + +Asynchronously writes data into the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + | callback | AsyncCallback<number> | Yes | Callback invoked when the data is written asynchronously. | + +- Example + ```js + let ss= fileio.createStreamSync(fpath, "r+"); + ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { + if (!err) { + // do something + console.log(bytesWritten); + } + }); + ``` + + +### writeSync7+ + +writeSync(buffer: ArrayBuffer | string, options?: { + offset?: number; + length?: number; + position?: number; + encoding?: string; +}): number + +Synchronously writes data into the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer \| string | Yes | Data to write. It can be a string or data from a buffer. | + | options | Object | No | The options are as follows:
- **offset** (number): position of the data to write in reference to the start address of the data. The default value is **0**.
- **length** (number): length of the data to write. The default value is the buffer length minus the offset.
- **position** (number): start position to write the data in the file. By default, data is written from the current position.
- **encoding** (string): format of the string to be encoded. The default value is **utf-8**, which is the only value supported.| + +- Return value + | Type | Description | + | ------ | -------- | + | number | Length of the data written in the file.| + +- Example + ```js + let ss= fileio.createStreamSync(fpath,"r+"); + let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); + ``` + + +### read7+ + +read(buffer: ArrayBuffer, options?: { + position?: number; + offset?: number; + length?: number; +}): Promise<ReadOut> + +Asynchronously reads data from the stream. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + +- Return value + | Type | Description | + | ---------------------------------- | ------ | + | Promise<[ReadOut](#readout)> | Data read.| + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ + console.info("read data successfully"); + }).catch(function(err){ + console.info("read data failed with error:"+ err); + }); + ``` + + +### read7+ + +read(buffer: ArrayBuffer, options: { + position?: number; + offset?: number; + length?: number; +}, callback: AsyncCallback<ReadOut>): void + +Asynchronously reads data from the stream. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + | callback | AsyncCallback<[ReadOut](#readout)> | Yes | Callback invoked when data is read asynchronously from the stream. | + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { + if (!err) { + // do something + } + }); + ``` + + +### readSync7+ + +readSync(buffer: ArrayBuffer, options?: { + position?: number; + offset?: number; + length?: number; +}): number + +Synchronously reads data from the stream. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ----------- | ---- | ---------------------------------------- | + | buffer | ArrayBuffer | Yes | Buffer used to store the file read. | + | options | Object | No | The options are as follows:
- **offset** (number): position to store the data read in the buffer in reference to the start address of the buffer. The default value is **0**.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
- **position** (number): position of the data to read in the file. By default, data is read from the current position.| + +- Return value + | Type | Description | + | ------ | -------- | + | number | Length of the data read.| + +- Example + ```js + let ss = fileio.createStreamSync(fpath, "r+"); + let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); + ``` + + +## Dir + +Manages directories. Before calling a method of the **Dir** class, use the [opendir()](#fileioopendir) method synchronously or asynchronously to create a **Dir** instance. + + +### read + +read(): Promise<Dirent> + +Asynchronously reads the next directory entry. This method uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | -------------------------------- | ------------- | + | Promise<[Dirent](#dirent)> | Directory entry that is read asynchronously.| + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.read().then(function (dirent){ + console.info("read successfully:"+ dirent.name); + }).catch(function(err){ + console.info("read failed with error:"+ err); + }); + ``` + + +### read + +read(callback: AsyncCallback<Dirent>): void + +Asynchronously reads the next directory entry. This method uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Parameters + | Name | Type | Mandatory | Description | + | -------- | -------------------------------------- | ---- | ---------------- | + | callback | AsyncCallback<[Dirent](#dirent)> | Yes | Callback invoked when the next directory entry is asynchronously read.| + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.read(function (err, dirent) { + if (!err) { + // do something + console.log(dirent.name) + } + }); + ``` + + +### readSync + +readSync(): Dirent + +Synchronously reads the next directory entry. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ----------------- | -------- | + | [Dirent](#dirent) | Directory entry read.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let dirent = dir.readSync(); + ``` + + +### closeSync + +closeSync(): void + +Closes a directory. After a directory is closed, the file descriptor in Dir will be released and no directory entry can be read from Dir. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Example + ```js + let dir = fileio.opendirSync(path); + dir.closeSync(); + ``` + + +## Dirent + +Provides information about files and directories. Before calling a method of the **Dirent** class, use the [dir.read()](#read) method synchronously or asynchronously to create a **Dirent** instance. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------- | +| name | string | Yes | No | Directory entry name.| + + +### isBlockDevice + +isBlockDevice(): boolean + +Checks whether the current directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ---------------- | + | boolean | Whether the directory entry is a block special file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isBLockDevice = dir.readSync().isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice(): boolean + +Checks whether a directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ----------------- | + | boolean | Whether the directory entry is a character special file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isCharacterDevice = dir.readSync().isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory(): boolean + +Checks whether a directory entry is a directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | ------------- | + | boolean | Whether the directory entry is a directory.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isDirectory = dir.readSync().isDirectory(); + ``` + + +### isFIFO + +isFIFO(): boolean + +Checks whether the current directory entry is a named pipe (or FIFO). Named pipes are used for inter-process communication. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a FIFO.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isFIFO = dir.readSync().isFIFO(); + ``` + + +### isFile + +isFile(): boolean + +Checks whether a directory entry is a regular file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a regular file.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isFile = dir.readSync().isFile(); + ``` + + +### isSocket + +isSocket(): boolean + +Checks whether a directory entry is a socket. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | -------------- | + | boolean | Whether the directory entry is a socket.| + +- Example + ```js + let dir = fileio.opendirSync(dpath); + let isSocket = dir.readSync().isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink(): boolean + +Checks whether a directory entry is a symbolic link. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +- Return value + | Type | Description | + | ------- | --------------- | + | boolean | Whether the directory entry is a symbolic link.| + +- Example + ```js + let dir = fileio.opendirSync(path); + let isSymbolicLink = dir.readSync().isSymbolicLink(); + ``` diff --git a/en/application-dev/reference/apis/js-apis-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index 18891f758ae42915da893256ebf027564cd92d6b..c3b738b12c4e0b3f1ea674feb3b5e25304ba9f9d 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -2,7 +2,7 @@ >![icon-note.gif](public_sys-resources/icon-note.gif) **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. ->- This is a system API and cannot be called by third-party applications. Currently, it can be called only by **filepicker**. +>- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. ## Modules to Import ```js diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..1091770862af33647f271be1d0097859c7440ad1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formInfo.md @@ -0,0 +1,116 @@ +# FormInfo + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + +Provides widget information. + +## Modules to Import + +``` +import formInfo from '@ohos.application.formInfo'; +``` + +## Required Permissions + +None. + +## FormInfo + +Describes widget information. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Readable/Writable| Type | Description | +| ----------- | -------- | -------------------- | ------------------------------------------------------------ | +| bundleName | Read only | string | Name of the bundle to which the widget belongs. | +| moduleName | Read only | string | Name of the module to which the widget belongs. | +| abilityName | Read only | string | Name of the ability to which the widget belongs. | +| name | Read only | string | Widget name. | +| description | Read only | string | Description of the widget. | +| type | Read only | [FormType](#formtype) | Widget type. Currently, only JS widgets are supported.| +| jsComponentName | Read only | string | Component name of the JS widget. | +| colorMode | Read only | [ColorMode](#colormode) | Color mode of the widget. | +| isDefault | Read only | boolean | Whether the widget is the default one. | +| updateEnabled | Read only | boolean | Whether the widget is updatable. | +| formVisibleNotify | Read only | string | Whether to send a notification when the widget is visible. | +| relatedBundleName | Read only | string | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | Read only | string | Time when the widget was updated. | +| formConfigAbility | Read only | string | Configuration ability of the widget. | +| updateDuration | Read only | string | Widget update period.| +| defaultDimension | Read only | number | Default dimension of the widget. | +| supportDimensions | Read only | Array<number> | Dimensions supported by the widget. | +| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Automatic mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Readable/Writable| Type | Description | +| ----------- | -------- | -------------------- | ------------------------------------------------------------ | +| formState | Read only | [FormState](#formstate) | Widget state. | +| want | Read only | Want | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | ID of a widget. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md index 54470f52311e717a64d6ce1a98f5f427d557913c..5f92677ec4a9856d96bc78b8787059ad5fb180ac 100644 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ b/en/application-dev/reference/apis/js-apis-formbindingdata.md @@ -25,7 +25,7 @@ Creates a **FormBindingData** object. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object or string| No | Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| +| obj | Object or string| No | Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| **Return value** @@ -38,20 +38,20 @@ Creates a **FormBindingData** object. **Example** ```js - let obj = {"temperature": "21°"}; + let fd = fileio.openSync(path); + let obj = { + "temperature": "21°", + "formImages": {"image": fd} + }; let formBindingDataObj = formBindingData.createFormBindingData(obj); ``` -## formBindingData.FormBindingData - -data: Object +## Attributes Describes a **FormBindingData** object. **System capability**: SystemCapability.Ability.Form -**Parameters** - -| Name| Type | Description | -| ---- | -------------- | ------------------------------------------------------------ | -| data | Object or string| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| +| Name| Readable| Writable| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | -------- | +| data | Yes| No| Object | Yes| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-formerror.md new file mode 100644 index 0000000000000000000000000000000000000000..37eecd85304700c21d92e6f07d3cd11229a32c64 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formerror.md @@ -0,0 +1,49 @@ +# FormError + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + +Provides widget-related error codes. + +## Modules to Import + +``` +import formError from '@ohos.application.formError'; +``` + +## Required Permissions + +None. + +## enum FormError + +Enumerates the available error codes. + +**System capability** + +SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| ERR_COMMON | 1 | Default error code. | +| ERR_PERMISSION_DENY | 2 | No permission to perform the operation. | +| ERR_GET_INFO_FAILED | 4 | Failed to query widget information. | +| ERR_GET_BUNDLE_FAILED | 5 | Failed to query the bundle information. | +| ERR_GET_LAYOUT_FAILED | 6 | Failed to query the layout information. | +| ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. | +| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match. | +| ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. | +| ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. | +| ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. | +| ERR_MAX_INSTANCES_PER_FORM | 12 | The number of instances per widget exceeds the upper limit. | +| ERR_OPERATION_FORM_NOT_SELF | 13 | The application is not allowed to operate widgets applied by other applications. | +| ERR_PROVIDER_DEL_FAIL | 14 | The widget provider failed to delete the widget. | +| ERR_MAX_FORMS_PER_CLIENT | 15 | The number of widgets applied for by the widget host exceeds the upper limit. | +| ERR_MAX_SYSTEM_TEMP_FORMS | 16 | The number of temporary widgets exceeds the upper limit. | +| ERR_FORM_NO_SUCH_MODULE | 17 | The module does not exist. | +| ERR_FORM_NO_SUCH_ABILITY | 18 | The ability component does not exist. | +| ERR_FORM_NO_SUCH_DIMENSION | 19 | The widget dimension does not exist. | +| ERR_FORM_FA_NOT_INSTALLED | 20 | The FA where the widget is located is not installed. | +| ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. | +| ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | +| ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md deleted file mode 100644 index a96feb9ef29393127bc1916a9a4a13ea7eba1817..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ /dev/null @@ -1,219 +0,0 @@ -# FormExtension - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - -Provides **FormExtension** APIs. - -## Modules to Import - -``` -import FormExtension from '@ohos.application.FormExtension'; -``` - -## Required Permissions - -None - -## Attributes - -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This class is inherited from **ExtensionContext**.
**System capability**: SystemCapability.Ability.Form| - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -Called to notify the widget provider that a **Form** instance (widget) has been created. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | - | want | [Want](js-apis-featureAbility.md#want) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } - } - ``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -Called to notify the widget provider that a temporary widget has been converted to a normal one. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| - -**Example** - - ``` - export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } - } - ``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-formextensioncontext.md) class to update the widget data. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - ``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -Called to notify the widget provider of the change of visibility. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | --------- | ------------------------- | ---- | ---------------------------- | - | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - } - ``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -Called to instruct the widget provider to receive and process the widget event. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ---------------------- | - | formId | string | Yes | ID of the widget that requests the event.| - | message | string | Yes | Event message. | - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } - } - ``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -Called to notify the widget provider that a **Form** instance (widget) has been destroyed. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget to be destroyed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } - } - ``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](#section188911144124715) | Yes| New configuration.| - -**Example** - - ```js - class MyFormExtension extends MyFormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md new file mode 100644 index 0000000000000000000000000000000000000000..0cf54af57b8aacb91bb487e49bf8a74074ecc8da --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formhost.md @@ -0,0 +1,1010 @@ +# FormHost + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + +Provides APIs related to the widget host. + +## Modules to Import + +``` +import formHost from '@ohos.application.formHost'; +``` + +## Required Permissions + +ohos.permission.REQUIRE_FORM + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void; + +Deletes a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.deleteForm(formId, (error, data) => { + if (error) { + console.log('formHost deleteForm, error:' + error.code); + } + }); + ``` + +## deleteForm + +deleteForm(formId: string): Promise<void>; + +Deletes a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Parameters** + + ```js + var formId = "12400633174999288"; + formHost.deleteForm(formId).catch((error) => { + console.log('formProvider deleteForm, error:' + JSON.stringify(error)); + }); + ``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void; + +Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + error.code); + } + }); + ``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void; + +Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and determines whether to retain the cache information based on the setting. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ----------- | + | formId | string | Yes | ID of a widget. | + | isReleaseCache | boolean | Yes | Whether to release the cache.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error, data) => { + if (error) { + console.log('formHost releaseForm, error:' + error.code); + } + }); + ``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void>; + +Releases a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and determines whether to retain the cache information based on the setting. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ----------- | + | formId | string | Yes | ID of a widget. | + | isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.releaseForm(formId, true).catch((error) => { + console.log('formProvider releaseForm, error:' + JSON.stringify(error)); + }); + ``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void; + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**System capability** + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.requestForm(formId, (error, data) => { + if (error) { + console.log('formHost requestForm, error:' + error.code); + } + }); + ``` + +## requestForm + +requestForm(formId: string): Promise<void>; + +Requests a widget update. This API uses a promise to return the result. + +**System capability** + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.requestForm(formId).catch((error) => { + console.log('formProvider requestForm, error:' + JSON.stringify(error)); + }); + ``` + +## castTempForm + +castTempForm(formId: string, callback: AsyncCallback<void>): void; + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.castTempForm(formId, (error, data) => { + if (error) { + console.log('formHost castTempForm, error:' + error.code); + } + }); + ``` + +## castTempForm + +castTempForm(formId: string): Promise<void>; + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.castTempForm(formId).catch((error) => { + console.log('formProvider castTempForm, error:' + JSON.stringify(error)); + }); + ``` + +## notifyVisibleForms + +notifyVisibleForms(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget visible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyVisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyVisibleForms, error:' + error.code); + } + }); + ``` + +## notifyVisibleForms + +notifyVisibleForms(formId: string): Promise<void>; + +Instructs the widget framework to make a widget visible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyVisibleForms(formId).catch((error) => { + console.log('formProvider notifyVisibleForms, error:' + JSON.stringify(error)); + }); + ``` + +## notifyInvisibleForms + +notifyInvisibleForms(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget invisible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyInvisibleForms(formId, (error, data) => { + if (error) { + console.log('formHost notifyInvisibleForms, error:' + error.code); + } + }); + ``` + +## notifyInvisibleForms + +notifyInvisibleForms(formId: string): Promise<void>; + +Instructs the widget framework to make a widget invisible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.notifyInvisibleForms(formId).catch((error) => { + console.log('formProvider notifyInvisibleForms, error:' + JSON.stringify(error)); + }); + ``` + +## enableFormsUpdate + +enableFormsUpdate(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget to be updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.enableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost enableFormsUpdate, error:' + error.code); + } + }); + ``` + +## enableFormsUpdate + +enableFormsUpdate(formId: string): Promise<void>; + +Instructs the widget framework to make a widget to be updatable. This API uses a promise to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.enableFormsUpdate(formId).catch((error) => { + console.log('formProvider enableFormsUpdate, error:' + JSON.stringify(error)); + }); + ``` + +## disableFormsUpdate + +disableFormsUpdate(formId: string, callback: AsyncCallback<void>): void; + +Instructs the widget framework to make a widget not to be updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the disabled state and cannot receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.disableFormsUpdate(formId, (error, data) => { + if (error) { + console.log('formHost disableFormsUpdate, error:' + error.code); + } + }); + ``` + +## disableFormsUpdate + +disableFormsUpdate(formId: string): Promise<void>; + +Instructs the widget framework to make a widget not to be updatable. This API uses a promise to return the result. After this API is called, the widget is in the disabled state and cannot receive updates from the widget provider. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.disableFormsUpdate(formId).catch((error) => { + console.log('formProvider disableFormsUpdate, error:' + JSON.stringify(error)); + }); + ``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void; + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.isSystemReady((error, data) => { + if (error) { + console.log('formHost isSystemReady, error:' + error.code); + } + }); + ``` + +## isSystemReady + +isSystemReady(): Promise<void>; + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formId = "12400633174999288"; + formHost.isSystemReady().catch((error) => { + console.log('formProvider isSystemReady, error:' + JSON.stringify(error)); + }); + ``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo((error, data) => { + if (error) { + console.log('formHost getAllFormsInfo, error:' + error.code); + } + }); + ``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<FormInfo>>; + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo().catch((error) => { + console.log('formProvider getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getFormsInfo("com.example.ohos.accountjsdemo", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + error.code); + } + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<FormInfo>>): void; + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | moduleName | string | Yes| Module name.| + | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| + +**Example** + + ```js + formHost.getFormsInfo("com.example.ohos.accountjsdemo", (error, data) => { + if (error) { + console.log('formHost getFormsInfo, error:' + error.code); + } + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<FormInfo>>; + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | bundleName | string | Yes| Bundle name of the target application.| + | moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| + +**Example** + + ```js + formHost.getAllFormsInfo().catch((error) => { + console.log('formProvider getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void; + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | callback | AsyncCallback<number> | Yes| Callback used to return the number of widgets deleted.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds, (error, data) => { + if (error) { + console.log('formHost deleteInvalidForms, error:' + error.code); + } + }); + ``` + +## deleteInvalidForms + +function deleteInvalidForms(formIds: Array<string>): Promise<number>; + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds).catch((error) => { + console.log('formProvider deleteInvalidForms, error:' + JSON.stringify(error)); + }); + ``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<FormStateInfo>): void; + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-featureAbility.md#want) | Yes | **Want** information carried to query the widget state.| +| callback | AsyncCallback<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Yes| Callback used to return the widget state.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + formHost.acquireFormState(want, (error, data) => { + if (error) { + console.log('formHost acquireFormState, error:' + error.code); + } + }); + ``` + +## acquireFormState + +function acquireFormState(want: Want): Promise<FormStateInfo>; + +Obtains the widget state. This API uses a promise to return the result. + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Promise used to return the widget state.| + +**System capability**: + +SystemCapability.Ability.Form + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + formHost.acquireFormState(want).catch((error) => { + console.log('formProvider acquireFormState, error:' + JSON.stringify(error)); + }); + ``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void; + +Subscribes to widget uninstall events. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| + | callback | Callback<string> | Yes| Callback used to return the result.| + +**Example** + + ```js + formHost.on("formUninstall", (error, data) => { + if (error) { + console.log('formHost on formUninstall, error:' + error.code); + } + }); + ``` + +## off("formUninstall") + +off(type: "formUninstall", callback: Callback<string>): void; + +Unsubscribes from widget uninstall events. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | type | string | Yes | Type of event to unsubscribe from. The value **formUninstall** indicates a widget uninstallation event.| + | callback | Callback<string> | Yes| Callback used to return the result.| + +**Example** + + ```js + formHost.off("formUninstall", (error, data) => { + if (error) { + console.log('formHost off formUninstall, error:' + error.code); + } + }); + ``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void; + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isVisible | boolean | Yes | Whether to be visible.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsVisible(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsVisible, error:' + error.code); + } + }); + ``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void>; + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isVisible | boolean | Yes | Whether to be visible.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsVisible(formIds, true).catch((error) => { + console.log('formProvider notifyFormsVisible, error:' + JSON.stringify(error)); + }); + ``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void; + +Instructs the widgets to enable or disable update. This API uses an asynchronous callback to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to enable update.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + if (error) { + console.log('formHost notifyFormsEnableUpdate, error:' + error.code); + } + }); + ``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void>; + +Instructs the widgets to enable or disable update. This API uses a promise to return the result. + +**System capability**: + +SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to enable update.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + +**Example** + + ```js + var formIds = new Array("12400633174999288", "12400633174999289"); + formHost.notifyFormsEnableUpdate(formIds, true).catch((error) => { + console.log('formProvider notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index f682cbc36b446e792a971035e04de9a59924eca9..40367d50bcec160ec9d2bf932f3d8c6275a86d5f 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -61,6 +61,12 @@ SystemCapability.Ability.Form | formId | string | Yes | ID of a widget. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +**Return value** + + | Type | Description | + | ------------- | ---------------------------------- | + | Promise\ |Promise used to return the result. | + **Example** ```js @@ -118,6 +124,12 @@ SystemCapability.Ability.Form | formId | string | Yes | ID of the widget to update.| | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise used to return the result.| + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 2c6fbbdfac2693968b4d4f5aaabebe2ba940791b..7d4694bfa7cac837438ecd4f38a9f414316e92e0 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,7 +1,7 @@ -# Geolocation - New +# Geolocation -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,26 +12,23 @@ import geolocation from '@ohos.geolocation'; ``` - -## Required Permissions - -ohos.permission.LOCATION - -ohos.permission.LOCATION_IN_BACKGROUND - - ## geolocation.on('locationChange') on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void Registers a listener for location changes with a location request initiated. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationChange** indicates a location change event. | - | request | LocationRequest | Yes | Location request. | - | callback | Callback<[Location](#location)> | Yes | Callback used to return the location change event. | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | request | LocationRequest | Yes| Location request.| + | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + - Example @@ -50,11 +47,16 @@ off(type: 'locationChange', callback?: Callback<Location>) : void Unregisters the listener for location changes with the corresponding location request deleted. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationChange** indicates a location change event. | - | callback | Callback<[Location](#location)> | No | Callback used to return the location change event. | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| + - Example @@ -74,11 +76,16 @@ on(type: 'locationServiceState', callback: Callback<boolean>) : void Registers a listener for location service status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationServiceState** indicates a location service status change event. | - | callback | Callback<boolean> | Yes | Callback used to return the location service status change event. | + | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| + | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| + - Example @@ -96,11 +103,16 @@ off(type: 'locationServiceState', callback?: Callback<boolean>) : void; Unregisters the listener for location service status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **locationServiceState** indicates a location service status change event. | - | callback | Callback<boolean> | No | Callback used to return the location service status change event. | + | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| + | callback | Callback<boolean> | No| Callback used to return the location service status change event.| + - Example @@ -113,18 +125,23 @@ Unregisters the listener for location service status change events. ``` -## geolocation.on('cachedGnssLocationsReporting') +## geolocation.on('cachedGnssLocationsReporting')8+ on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; Registers a listener for cached GNSS location reports. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations. | - | request | CachedGnssLocationsRequest | Yes | Request for reporting cached GNSS location. | - | callback | Callback<boolean> | Yes | Callback used to return cached GNSS locations. | + | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| + | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| + | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + - Example @@ -137,17 +154,22 @@ Registers a listener for cached GNSS location reports. ``` -## geolocation.off('cachedGnssLocationsReporting') +## geolocation.off('cachedGnssLocationsReporting')8+ off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; Unregisters the listener for cached GNSS location reports. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations. | - | callback | Callback<boolean> | No | Callback used to return cached GNSS locations. | + | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| + | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| + - Example @@ -161,17 +183,22 @@ Unregisters the listener for cached GNSS location reports. ``` -## geolocation.on('gnssStatusChange') +## geolocation.on('gnssStatusChange')8+ on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; Registers a listener for GNSS satellite status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **gnssStatusChange** indicates a GNSS satellite status change. | - | callback | Callback<SatelliteStatusInfo> | Yes | Callback used to return GNSS satellite status changes. | + | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| + | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| + - Example @@ -183,17 +210,21 @@ Registers a listener for GNSS satellite status change events. ``` -## geolocation.off('gnssStatusChange') +## geolocation.off('gnssStatusChange')8+ off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; Unregisters the listener for GNSS satellite status change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **gnssStatusChange** indicates a GNSS satellite status change. | - | callback | Callback<SatelliteStatusInfo> | No | Callback used to return GNSS satellite status changes. | + | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| + | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| - Example @@ -206,17 +237,22 @@ Unregisters the listener for GNSS satellite status change events. ``` -## geolocation.on('nmeaMessageChange') +## geolocation.on('nmeaMessageChange')8+ on(type: 'nmeaMessageChange', callback: Callback<string>) : void; Registers a listener for GNSS NMEA message change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change. | - | callback | Callback<string> | Yes | Callback used to return GNSS NMEA message changes. | + | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| + | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| + - Example @@ -228,17 +264,22 @@ Registers a listener for GNSS NMEA message change events. ``` -## geolocation.off('nmeaMessageChange') +## geolocation.off('nmeaMessageChange')8+ off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; Unregisters the listener for GNSS NMEA message change events. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change. | - | callback | Callback<string> | No | Callback used to return GNSS NMEA message changes. | + | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| + | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| + - Example @@ -251,18 +292,23 @@ Unregisters the listener for GNSS NMEA message change events. ``` -## geolocation.on('fenceStatusChange') +## geolocation.on('fenceStatusChange')8+ on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; Registers a listener for status change events of the specified geofence. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **fenceStatusChange** indicates a geofence status change. | - | request | GeofenceRequest | Yes | Geofencing request. | - | want | WantAgent | Yes | **WantAgent** used to return geofence (entrance or exit) events. | + | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| + | request | GeofenceRequest | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + - Example @@ -313,18 +359,22 @@ Registers a listener for status change events of the specified geofence. ``` -## geolocation.off('fenceStatusChange') +## geolocation.off('fenceStatusChange')8+ off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; Unregisters the listener for status change events of the specified geofence. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes | Event type. The value **fenceStatusChange** indicates a geofence status change. | - | request | GeofenceRequest | Yes | Geofencing request. | - | want | WantAgent | Yes | **WantAgent** used to return geofence (entrance or exit) events. | + | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| + | request | GeofenceRequest | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| - Example @@ -381,14 +431,17 @@ Unregisters the listener for status change events of the specified geofence. getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void -Obtains the current location. This method uses an asynchronous callback to return the result. +Obtains the current location. This API uses an asynchronous callback to return the result. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No | Location request. | - | callback | AsyncCallback<[Location](#location)> | Yes | Callback used to return the current location. | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| - Example @@ -407,18 +460,22 @@ Obtains the current location. This method uses an asynchronous callback to retur getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> -Obtains the current location. This method uses a promise to return the result. +Obtains the current location. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No | Location request. | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the current location. | + | Promise<[Location](#location)> | Promise used to return the current location.| + - Example @@ -434,12 +491,17 @@ Obtains the current location. This method uses a promise to return the result. getLastLocation(callback: AsyncCallback<Location>) : void -Obtains the previous location. This method uses an asynchronous callback to return the result. +Obtains the previous location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Location](#location)> | Yes | Callback used to return the previous location. | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the previous location.| + - Example @@ -454,12 +516,17 @@ Obtains the previous location. This method uses an asynchronous callback to retu getLastLocation() : Promise<Location> -Obtains the previous location. This method uses a promise to return the result. +Obtains the previous location. This API uses a promise to return the result. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the previous location. | + | Promise<[Location](#location)> | Promise used to return the previous location.| + - Example @@ -475,13 +542,17 @@ Obtains the previous location. This method uses a promise to return the result. isLocationEnabled(callback: AsyncCallback<boolean>) : void -Checks whether the location service is enabled. This method uses an asynchronous callback to return the result. +Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the location service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + - Example @@ -496,12 +567,16 @@ Checks whether the location service is enabled. This method uses an asynchronous isLocationEnabled() : Promise<boolean> -Checks whether the location service is enabled. This method uses a promise to return the result. +Checks whether the location service is enabled. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION -- Return values - | Name | Description | +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status. | + | Promise<boolean> | Promise used to return the location service status.| - Example @@ -517,13 +592,17 @@ Checks whether the location service is enabled. This method uses a promise to re requestEnableLocation(callback: AsyncCallback<boolean>) : void -Requests to enable the location service. This method uses an asynchronous callback to return the result. +Requests to enable the location service. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the location service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + - Example @@ -538,12 +617,17 @@ Requests to enable the location service. This method uses an asynchronous callba requestEnableLocation() : Promise<boolean> -Requests to enable the location service. This method uses a promise to return the result. +Requests to enable the location service. This API uses a promise to return the result. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status. | + | Promise<boolean> | Promise used to return the location service status.| + - Example @@ -554,16 +638,127 @@ Requests to enable the location service. This method uses a promise to return th ``` +## geolocation.enableLocation + +enableLocation(callback: AsyncCallback<boolean>) : void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + + +- Example + + ``` + geolocation.enableLocation((err, data) => { + console.log('enableLocation: ' + err + " data: " + data); + }); + ``` + + +## geolocation.enableLocation + +enableLocation() : Promise<boolean> + +Enables the location service. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the location service status.| + + +- Example + + ``` + geolocation.enableLocation().then((result) => { + console.log('promise, enableLocation: ' + result); + }); + ``` + +## geolocation.disableLocation + +disableLocation(callback: AsyncCallback<boolean>) : void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + + +- Example + + ``` + geolocation.disableLocation((err, data) => { + console.log('disableLocation: ' + err + " data: " + data); + }); + ``` + + +## geolocation.disableLocation + +disableLocation() : Promise<boolean> + +Enables the location service. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +- Return value + | Name| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the location service status.| + + +- Example + + ``` + geolocation.disableLocation().then((result) => { + console.log('promise, disableLocation: ' + result); + }); + ``` + ## geolocation.isGeoServiceAvailable isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void -Checks whether the (reverse) geocoding service is available. This method uses an asynchronous callback to return the result. +Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the (reverse) geocoding service status. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| + - Example @@ -578,12 +773,17 @@ Checks whether the (reverse) geocoding service is available. This method uses an isGeoServiceAvailable() : Promise<boolean> -Checks whether the (reverse) geocoding service is available. This method uses a promise to return the result. +Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the (reverse) geocoding service status. | + | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| + - Example @@ -599,13 +799,17 @@ Checks whether the (reverse) geocoding service is available. This method uses a getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void -Converts coordinates into geographic description through reverse geocoding. This method uses an asynchronous callback to return the result. +Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse geocoding request. | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes | Callback used to return the reverse geocoding result. | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| - Example @@ -621,17 +825,21 @@ Converts coordinates into geographic description through reverse geocoding. This getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; -Converts coordinates into geographic description through reverse geocoding. This method uses a promise to return the result. +Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes | Reverse geocoding request. | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result. | + | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| - Example @@ -647,13 +855,18 @@ Converts coordinates into geographic description through reverse geocoding. This getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void -Converts geographic description into coordinates through geocoding. This method uses an asynchronous callback to return the result. +Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding request. | - | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes | Callback used to return the geocoding result. | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| + - Example @@ -669,17 +882,21 @@ Converts geographic description into coordinates through geocoding. This method getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> -Converts geographic description into coordinates through geocoding. This method uses a promise to return the result. +Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [GeoCodeRequest](#geocoderequest) | Yes | Geocoding request. | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the geocoding result. | + | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| - Example @@ -692,16 +909,20 @@ Converts geographic description into coordinates through geocoding. This method -## geolocation.getCachedGnssLocationsSize +## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; -Obtains the number of cached GNSS locations. +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | Yes | Callback used to return the number of cached GNSS locations. | + | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | - Example @@ -712,16 +933,20 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.getCachedGnssLocationsSize +## geolocation.getCachedGnssLocationsSize8+ getCachedGnssLocationsSize() : Promise<number>; -Obtains the number of cached GNSS locations. +Obtains the number of cached GNSS locations. -- Return values - | Name | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +- Return value + | Name| Description| | -------- | -------- | - | Promise<number> | Promise used to return the number of cached GNSS locations. | + | Promise<number> | Promise used to return the number of cached GNSS locations.| - Example @@ -732,16 +957,20 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.flushCachedGnssLocations +## geolocation.flushCachedGnssLocations8+ flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; -Obtains all cached GNSS locations and clears the GNSS cache queue. +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -752,16 +981,20 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.flushCachedGnssLocations +## geolocation.flushCachedGnssLocations8+ flushCachedGnssLocations() : Promise<boolean>; -Obtains all cached GNSS locations and clears the GNSS cache queue. +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. | + | Promise<boolean> | Promise used to return the operation result.| - Example @@ -772,17 +1005,21 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.sendCommand +## geolocation.sendCommand8+ sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; -Sends an extended command to the location subsystem. This function can only be called by system applications. +Sends an extended command to the location subsystem. This API can only be called by system applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes | Extended command (string) to be sent. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | command | LocationCommand | Yes| Extended command (string) to be sent.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -794,21 +1031,25 @@ Sends an extended command to the location subsystem. This function can only be c ``` -## geolocation.sendCommand +## geolocation.sendCommand8+ sendCommand(command: LocationCommand) : Promise<boolean>; -Sends extended commands to the location subsystem. This function can only be called by system applications. +Sends an extended command to the location subsystem. This API can only be called by system applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes | Extended command (string) to be sent. | + | command | LocationCommand | Yes| Extended command (string) to be sent.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result. | + | Promise<boolean> | Callback used to return the operation result.| - Example @@ -820,17 +1061,23 @@ Sends extended commands to the location subsystem. This function can only be cal ``` -## geolocation.isLocationPrivacyConfirmed +## geolocation.isLocationPrivacyConfirmed8+ isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; -Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications. +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the result, which indicates whether the user agrees with the privacy statement. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - Example @@ -841,21 +1088,27 @@ Checks whether a user agrees with the privacy statement of the location service. ``` -## geolocation.isLocationPrivacyConfirmed +## geolocation.isLocationPrivacyConfirmed8+ isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This function can only be called by system applications. +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the result, which indicates whether the user agrees with the privacy statement. | + | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - Example @@ -866,18 +1119,24 @@ Checks whether a user agrees with the privacy statement of the location service. ``` -## geolocation.setLocationPrivacyConfirmStatus +## geolocation.setLocationPrivacyConfirmStatus8+ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications. +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | isConfirmed | boolean | Yes | Whether the user agrees with the privacy statement of the location service. | - | callback | AsyncCallback<boolean> | Yes | Callback used to return the operation result. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| + | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| - Example @@ -888,22 +1147,28 @@ Sets the user confirmation status for the privacy statement of the location serv ``` -## geolocation.setLocationPrivacyConfirmStatus +## geolocation.setLocationPrivacyConfirmStatus8+ setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This function can only be called by system applications. +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +This is a system API and cannot be called by third-party applications. + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core - Parameters - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes | Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service. | - | isConfirmed | boolean | Yes | Whether the user agrees with the privacy statement of the location service. | + | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| + | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -- Return values - | Name | Description | +- Return value + | Name| Description| | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result. | + | Promise<boolean> | Callback used to return the operation result.| - Example @@ -919,201 +1184,262 @@ Sets the user confirmation status for the privacy statement of the location serv Sets the priority of the location request. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| UNSET | 0x200 | Priority unspecified. | -| ACCURACY | 0x201 | Location accuracy. | -| LOW_POWER | 0x202 | Power efficiency. | -| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible. | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| ## LocationRequestScenario Sets the scenario of the location request. - | Name | Default Value | Description | + +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| UNSET | 0x300 | Scenario unspecified. | -| NAVIGATION | 0x301 | Navigation. | -| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking. | -| CAR_HAILING | 0x303 | Ride hailing. | -| DAILY_LIFE_SERVICE | 0x304 | Daily life services. | -| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location. | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| ## GeoLocationErrorCode Enumerates error codes of the location service. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters. | -| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API. | -| GEOCODE_ERROR | 103 | Failed to call the geocoding API. | -| LOCATOR_ERROR | 104 | Failed to obtain the location. | -| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch. | -| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location. | -| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time. | +| INPUT_PARAMS_ERROR | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR | 107 | Failed to obtain the location within the specified time.| ## ReverseGeoCodeRequest Defines a reverse geocoding request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| latitude | number | Yes | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | Yes | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| maxItems | number | No | Maximum number of location records to be returned. | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | No| Maximum number of location records to be returned.| ## GeoCodeRequest Defines a geocoding request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| description | number | Yes | Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**. | -| maxItems | number | No | Maximum number of location records to be returned. | -| minLatitude | number | No | Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges. | -| minLongitude | number | No | Minimum longitude. | -| maxLatitude | number | No | Maximum latitude. | -| maxLongitude | number | No | Maximum longitude. | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| +| maxItems | number | No| Maximum number of location records to be returned.| +| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| +| minLongitude | number | No| Minimum longitude.| +| maxLatitude | number | No| Maximum latitude.| +| maxLongitude | number | No| Maximum longitude.| ## GeoAddress Defines a geographic location. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | No | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| locale | string | No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English. | -| placeName | string | No | Landmark of the location. | -| countryCode | string | No | Country code. | -| countryName | string | No | Country name. | -| administrativeArea | string | No | Administrative region name. | -| subAdministrativeArea | string | No | Sub-administrative region name. | -| locality | string | No | Locality information. | -| subLocality | string | No | Sub-locality information. | -| roadName | string | No | Road name. | -| subRoadName | string | No | Auxiliary road information. | -| premises | string | No | House information. | -| postalCode | string | No | Postal code. | -| phoneNumber | string | No | Phone number. | -| addressUrl | string | No | Website URL. | -| descriptions | Array<string> | No | Additional description. | -| descriptionsSize | number | No | Total number of additional descriptions. | +| latitude | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName | string | No| Landmark of the location.| +| countryCode | string | No| Country code.| +| countryName | string | No| Country name.| +| administrativeArea | string | No| Administrative region name.| +| subAdministrativeArea | string | No| Sub-administrative region name.| +| locality | string | No| Locality information. | +| subLocality | string | No| Sub-locality information. | +| roadName | string | No| Road name.| +| subRoadName | string | No| Auxiliary road information.| +| premises | string | No| House information.| +| postalCode | string | No| Postal code.| +| phoneNumber | string | No| Phone number.| +| addressUrl | string | No| Website URL.| +| descriptions | Array<string> | No| Additional description.| +| descriptionsSize | number | No| Total number of additional descriptions.| ## LocationRequest Defines a location request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority of the location request. | -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes | Scenario of the location request. | -| timeInterval | number | No | Time interval at which location information is reported. | -| distanceInterval | number | No | Distance interval at which location information is reported. | -| maxAccuracy | number | No | Location accuracy. | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| +| timeInterval | number | No| Time interval at which location information is reported.| +| distanceInterval | number | No| Distance interval at which location information is reported.| +| maxAccuracy | number | No| Location accuracy.| ## CurrentLocationRequest Defines the current location request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No | Priority of the location request. | -| scenario | [LocationRequestScenario](#locationrequestscenario) | No | Scenario of the location request. | -| maxAccuracy | number | No | Location accuracy, in meters. | -| timeoutMs | number | No | Timeout duration, in milliseconds. The minimum value is **1000**. | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| +| maxAccuracy | number | No| Location accuracy, in meters.| +| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| -## SatelliteStatusInfo +## SatelliteStatusInfo8+ Defines the satellite status information. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes | Number of satellites. | -| satelliteIds | Array<number> | Yes | Array of satellite IDs. | -| carrierToNoiseDensitys | Array<number> | Yes | Carrier-to-noise density ratio, that is, cn0. | -| altitudes | Array<number> | Yes | Altitude information. | -| azimuths | Array<number> | Yes | Azimuth information. | -| carrierFrequencies | Array<number> | Yes | Carrier frequency. | +| satellitesNumber | number | Yes| Number of satellites.| +| satelliteIds | Array<number> | Yes| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| Altitude information.| +| azimuths | Array<number> | Yes| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| Carrier frequency.| -## CachedGnssLocationsRequest +## CachedGnssLocationsRequest8+ Represents a request for reporting cached GNSS locations. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | Yes | Interval for reporting the cached GNSS locations, in milliseconds. | -| wakeUpCacheQueueFull | boolean | Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full. | +| reportingPeriodSec | number | Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| -## Geofence +## Geofence8+ Defines a GNSS geofence. Currently, only circular geofences are supported. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes | Latitude information. | -| longitude | number | Yes | Longitude information. | -| radius | number | Yes | Radius of a circular geofence. | -| expiration | number | Yes | Expiration period of a geofence, in milliseconds. | +| latitude | number | Yes| Latitude information.| +| longitude | number | Yes| Longitude information.| +| radius | number | Yes| Radius of a circular geofence.| +| expiration | number | Yes| Expiration period of a geofence, in milliseconds.| -## GeofenceRequest +## GeofenceRequest8+ Represents a GNSS geofencing request. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | Yes | Priority of the location information. | -| scenario | LocationRequestScenario | Yes | Location scenario. | -| geofence | Geofence | Yes | Geofence information. | +| priority | LocationRequestPriority | Yes| Priority of the location information.| +| scenario | LocationRequestScenario | Yes| Location scenario.| +| geofence | Geofence | Yes| Geofence information.| -## LocationPrivacyType +## LocationPrivacyType8+ Defines the privacy statement type. - | Name | Default Value | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Default Value| Description| | -------- | -------- | -------- | -| OTHERS | 0 | Other scenarios. | -| STARTUP | 1 | Privacy statement displayed in the startup wizard. | -| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service. | +| OTHERS | 0 | Other scenarios.| +| STARTUP | 1 | Privacy statement displayed in the startup wizard.| +| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| -## LocationCommand +## LocationCommand8+ Defines an extended command. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | Yes | Location scenario. | -| command | string | Yes | Extended command, in the string format. | +| scenario | LocationRequestScenario | Yes| Location scenario.| +| command | string | Yes| Extended command, in the string format.| ## Location Defines a location. - | Name | Type | Mandatory | Description | +**Permission required**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| latitude | number | Yes | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude. | -| longitude | number | Yes | Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude . | -| altitude | number | Yes | Location altitude, in meters. | -| accuracy | number | Yes | Location accuracy, in meters. | -| speed | number | Yes | Speed, in m/s. | -| timeStamp | number | Yes | Location timestamp in the UTC format. | -| direction | number | Yes | Direction information. | -| timeSinceBoot | number | Yes | Location timestamp since boot. | -| additions | Array<string> | No | Additional description. | -| additionSize | number | No | Number of additional descriptions. | +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| altitude | number | Yes| Location altitude, in meters.| +| accuracy | number | Yes| Location accuracy, in meters.| +| speed | number | Yes| Speed, in m/s.| +| timeStamp | number | Yes| Location timestamp in the UTC format.| +| direction | number | Yes| Direction information.| +| timeSinceBoot | number | Yes| Location timestamp since boot.| +| additions | Array<string> | No| Additional information.| +| additionSize | number | No| Number of additional descriptions.| diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index 0e5074650a58f11ca81e4a50580a02df48ab0fe1..612f81c27952b106218a84edb569c09a23203863 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -333,8 +333,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | HashMap | No| Instance that invokes the **forEach** method.| **Example** @@ -351,7 +351,7 @@ hashMap.forEach((value, key) => { ### entries -entries(): IterableIterator<[K, V]> +entries(): IterableIterator<[K, V]> Obtains an iterator that contains all the entries in this container. @@ -359,7 +359,7 @@ Obtains an iterator that contains all the entries in this container. | Type| Description| | -------- | -------- | -| IterableIterator<[K, V]> | Iterator obtained.| +| IterableIterator<[K, V]> | Iterator obtained.| **Example** @@ -387,7 +387,7 @@ Obtains an iterator, each item of which is a JavaScript object. | Type| Description| | -------- | -------- | -| IterableIterator<[K, V]> | Iterator obtained.| +| IterableIterator<[K, V]> | Iterator obtained.| **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 0a85c59cf83ccb22240ef7258394651a852db2d8..4e33216b1a17ff78364fddc103de84035f5d3a74 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -198,7 +198,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key | T | No| Key of the entry that is currently traversed (same as **value**).| | set | HashSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index 0d8534643b50338f4b9a96c97ed1c7f86bd2381b..4ec4c1062d7915888ae6d13037aa0ff9235e6c2c 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,4 +1,4 @@ -# Application dotting +# HiAppEvent > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -11,25 +11,22 @@ import hiAppEvent from '@ohos.hiAppEvent'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiAppEvent - - ## hiAppEvent.write write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. +Writes event information to the event file of the current day. This API supports JSON parameters and uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| eventName | string | Yes| App event name.| -| eventType | [EventType](#eventtype) | Yes| Application event type.| -| keyValues | object | Yes| Array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).| -| callback | AsyncCallback<void> | No| Callback used to process the received return value.
- The value **0** indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0** indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ------------------------------------------------------------ | +| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| +| eventType | [EventType](#eventtype) | Yes | Application event type. | +| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| +| callback | AsyncCallback<void> | No | Callback used to process the received return value.
-  Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously.
-  A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
-  A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file.| **Example** @@ -51,20 +48,22 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str write(eventName: string, eventType: EventType, keyValues: object): Promise<void> -Writes event information to the event file of the current day. This function supports JSON parameters and uses a promise to return the result. +Writes event information to the event file of the current day. This API supports JSON parameters and uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| eventName | string | Yes| App event name.| -| eventType | [EventType](#eventtype) | Yes| Application event type.| -| keyValues | object | Yes| Array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).| +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------------------------------------------------------ | +| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.| +| eventType | [EventType](#eventtype) | Yes | Application event type. | +| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed.| **Example** @@ -87,16 +86,18 @@ configure(config: ConfigOption): boolean Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [ConfigOption](#configoption) | Yes| Configuration items for application event logging.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ------------------------ | +| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ----------------------------------------------------------- | | boolean | Returns **true** if the configuration is successful; returns **false** otherwise.| **Example** @@ -117,41 +118,49 @@ hiAppEvent.configure({ Provides the configuration items for application event logging. -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| disable | boolean | No| Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.| -| maxStorage | string | No| Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ------------------------------------------------------------ | +| disable | boolean | No | Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.| +| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.| ## EventType Enumerates event types. -| Name| Default Value| Description| -| -------- | -------- | -------- | -| FAULT | 1 | Fault event| -| STATISTIC | 2 | Statistical event| -| SECURITY | 3 | Security event| -| BEHAVIOR | 4 | Behavior event| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Default Value| Description | +| --------- | ------ | -------------- | +| FAULT | 1 | Fault event| +| STATISTIC | 2 | Statistical event| +| SECURITY | 3 | Security event| +| BEHAVIOR | 4 | Behavior event| ## Event Provides constants that define the names of all predefined events. -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| USER_LOGIN | string | Yes| No| User login event.| -| USER_LOGOUT | string | Yes| No| User logout event.| -| DISTRIBUTED_SERVICE_START | string | Yes| No| Distributed service startup event.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Readable| Writable| Description | +| ------------------------- | -------- | ---- | ---- | -------------------- | +| USER_LOGIN | string | Yes | No | User login event. | +| USER_LOGOUT | string | Yes | No | User logout event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| ## Param Provides constants that define the names of all predefined event parameters. -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| USER_ID | string | Yes| No| Custom user ID.| -| DISTRIBUTED_SERVICE_NAME | string | Yes| No| Distributed service name.| -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes| No| Distributed service instance ID.| +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Readable| Writable| Description | +| ------------------------------- | -------- | ---- | ---- | ------------------ | +| USER_ID | string | Yes | No | Custom user ID. | +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index 70022fd0211204446dee616640221bd394f61e7e..eef977c21d3d9248d28961a7eebe482769573119 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -11,21 +11,19 @@ import hichecker from '@ohos.hichecker'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiChecker - -## Rule Constants +## Constants Provides the constants of all rule types. -| Name| Type| Description| +**System capability**: SystemCapability.HiviewDFX.HiChecker + +| Name | Type| Description | | ---------------------------------- | -------- | ------------------------------------------------------ | -| RULE_CAUTION_PRINT_LOG | BigInt | Alarm rule, which is programmed to print a log when an alarm is generated.| -| RULE_CAUTION_TRIGGER_CRASH | BigInt | Alarm rule, which is programmed to force the application to exit when an alarm is generated.| -| RULE_THREAD_CHECK_SLOW_PROCESS | BigInt | Caution rule, which is programmed to detect whether any time-consuming function is invoked.| -| RULE_CHECK_SLOW_EVENT | BigInt | Caution rule, which is programmed to detect whether the event distribution or processing time has exceeded the specified time threshold.| -| RULE_CHECK_ABILITY_CONNECTION_LEAK | BigInt | Caution rule, which is programmed to detect whether ability leakage has occurred.| +| RULE\_CAUTION\_PRINT\_LOG | BigInt | Alarm rule, which is programmed to print a log when an alarm is generated. | +| RULE\_CAUTION\_TRIGGER\_CRASH | BigInt | Alarm rule, which is programmed to force the application to exit when an alarm is generated. | +| RULE\_THREAD\_CHECK\_SLOW\_PROCESS | BigInt | Caution rule, which is programmed to detect whether any time-consuming function is invoked. | +| RULE\_CHECK\_SLOW\_EVENT | BigInt | Caution rule, which is programmed to detect whether the event distribution or processing time has exceeded the specified time threshold.| +| RULE\_CHECK\_ABILITY\_CONNECTION\_LEAK| BigInt | Caution rule, which is programmed to detect whether ability leakage has occurred. | ## hichecker.addRule @@ -34,11 +32,13 @@ addRule(rule: BigInt): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be added.| +| rule | BigInt | Yes | Rule to be added.| **Example** @@ -57,11 +57,13 @@ removeRule(rule: BigInt): void Removes one or more rules. The removed rules will become ineffective. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be removed.| +| rule | BigInt | Yes | Rule to be removed.| **Example** @@ -80,9 +82,11 @@ getRule(): BigInt Obtains a collection of thread, process, and alarm rules that have been added. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Return value** -| Type| Description| +| Type | Description | | ------ | ---------------------- | | BigInt | Collection of added rules.| @@ -93,7 +97,7 @@ Obtains a collection of thread, process, and alarm rules that have been added. hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Obtain the collection of added rules. -hichecker.getRule(); // return 1n; +hichecker.getRule(); // Return 1n. ``` ## hichecker.contains @@ -102,15 +106,17 @@ contains(rule: BigInt): boolean Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread. +**System capability**: SystemCapability.HiviewDFX.HiChecker + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| rule | BigInt | Yes| Rule to be checked.| +| rule | BigInt | Yes | Rule to be checked.| **Return value** -| Type| Description| +| Type | Description | | ------- | ---------------------------------------------------------- | | boolean | Returns **true** if the rule exists in the collection of added rules; returns **false** otherwise.| @@ -121,6 +127,6 @@ Checks whether the specified rule exists in the collection of added rules. If th hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Check whether the added rule exists in the collection of added rules. -hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; -hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // return false; +hichecker.contains(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // Return true. +hichecker.contains(hichecker.RULE_CAUTION_PRINT_LOG); // Return false. ``` diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 7e2473e5f45acddec718e6d400c8eec88bcfd1e9..c0844b51cbcc220251492c04c2d2d222b0f7f018 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -12,24 +12,22 @@ import hidebug from '@ohos.hidebug'; ``` -## System Capabilities -SystemCapability.HiviewDFX.HiProfiler.HiDebug - - ## hidebug.getNativeHeapSize getNativeHeapSize(): bigint Obtains the total size of the native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Total size of the native heap memory.| +**Return Value** +| Type | Description | +| ------ | --------------------------- | +| bigint | Total size of the native heap memory.| -- **Example** + +**Example** ``` let nativeHeapSize = hidebug.getNativeHeapSize(); ``` @@ -41,14 +39,16 @@ getNativeHeapAllocatedSize(): bigint Obtains the size of the allocated native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the allocated native heap memory.| +**Return Value** +| Type | Description | +| ------ | --------------------------------- | +| bigint | Size of the allocated native heap memory.| -- **Example** + +**Example** ``` let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize(); ``` @@ -60,14 +60,16 @@ getNativeHeapFreeSize(): bigint Obtains the size of the free native heap memory. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the free native heap memory.| +**Return Value** +| Type | Description | +| ------ | ------------------------------- | +| bigint | Size of the free native heap memory.| -- **Example** + +**Example** ``` let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize(); ``` @@ -79,14 +81,16 @@ getPss(): bigint Obtains the PSS of this process. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | PSS of the process.| +**Return Value** +| Type | Description | +| ------ | ------------------------- | +| bigint | PSS of the process.| -- **Example** + +**Example** ``` let pss = hidebug.getPss(); ``` @@ -98,14 +102,16 @@ getSharedDirty(): bigint Obtains the size of the shared dirty memory of this process. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug -- **Return value** - | Type| Description| - | -------- | -------- | - | bigint | Size of the shared dirty memory of the process.| +**Return Value** +| Type | Description | +| ------ | -------------------------- | +| bigint | Size of the shared dirty memory of the process.| -- **Example** + +**Example** ``` let sharedDirty = hidebug.getSharedDirty(); ``` @@ -117,11 +123,13 @@ startProfiling(filename : string) : void Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes| User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| +| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| **Example** @@ -141,6 +149,8 @@ stopProfiling() : void Stops the profiling method. `stopProfiling()` and `startProfiling()` are called in pairs. `stopProfiling()` always occurs after `startProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Example** ```js @@ -157,11 +167,13 @@ dumpHeapData(filename : string) : void Exports the heap data. +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + **Parameters** -| Name| Type| Mandatory| Description| +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| filename | string | Yes| User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the app based on the specified `filename`.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index a2a02fd14c79b4a736f59aa98e476d33f6290480..13814a6e63646a33956f8c7c8a89d919b50a6ea6 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -2,7 +2,7 @@ > **Note:** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -10,9 +10,6 @@ import hilog from '@ohos.hilog'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiLog ## hilog.debug @@ -20,14 +17,16 @@ debug(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the DEBUG level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -41,20 +40,22 @@ hilog.debug(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3 09-08 12:49:35.941 1547 2452 D FF00/testTag: 1: hello World 3.0 ``` -## **hilog.info** +## hilog.info info(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the INFO level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -74,14 +75,16 @@ warn(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the WARN level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -101,14 +104,16 @@ error(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the ERROR level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -128,14 +133,16 @@ fatal(domain: number, tag: string, format: string, ...args: any[]) : void Prints logs of the FATAL level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| format | string | Yes| String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| -| args | any[] | Yes| Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior. | +| format | string | Yes | String constant format, including the parameter type and privacy identifier. A parameter without the privacy identifier is treated as a privacy parameter by default.| +| args | any[] | Yes | Variable-length parameter list corresponding to the parameter type in the format string. The number and type of parameters must map to the identifier in the format string.| **Example** @@ -155,13 +162,15 @@ isLoggable(domain: number, tag: string, level: LogLevel) : boolean Checks whether printing is enabled for a domain, tag, or log level. +**System capability**: SystemCapability.HiviewDFX.HiLog + **Parameters** -| Name| Type| Mandatory| Description| +| Name| Type | Mandatory| Description | | ------ | --------------------- | ---- | ------------------------------------------ | -| domain | number | Yes| Service domain. The value ranges from **0x0** to **0xFFFFF**.| -| tag | string | Yes| String constant used to identify the class or service behavior.| -| level | [LogLevel](#loglevel) | Yes| Log level.| +| domain | number | Yes | Service domain. The value ranges from **0x0** to **0xFFFFF**. | +| tag | string | Yes | String constant used to identify the class or service behavior.| +| level | [LogLevel](#loglevel) | Yes | Log level. | **Example** @@ -173,10 +182,12 @@ hilog.isLoggable(0xFF00, "testTag", hilog.DEBUG); Enumerates event types. -| Name| Default Value| Description| +**System capability**: SystemCapability.HiviewDFX.HiLog + +| Name | Default Value| Description | | ----- | ------ | ----------- | | DEBUG | 3 | DEBUG level| -| INFO | 4 | INFO level| -| WARN | 5 | WARN level| +| INFO | 4 | INFO level | +| WARN | 5 | WARN level | | ERROR | 6 | ERROR level| | FATAL | 7 | FATAL level| diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index b5af74e563915592773475c7a2409f1bbe682690..9cd2fd38fb05d16e9b3e8c2d849c1419e66d5b31 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -82,7 +82,7 @@ Starts call chain tracing. This API works in synchronous manner. | name | string | Yes| Traced service name.| | flags | number | Yes| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag).| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -124,7 +124,7 @@ Obtains the trace ID. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -184,7 +184,7 @@ Creates a trace span. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -237,7 +237,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous | -------- | -------- | -------- | -------- | | id | [HiTraceId](#hitraceid) | Yes| **HiTraceId** instance.| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | @@ -265,7 +265,7 @@ Checks whether the specified trace flag in the **HiTraceId** instance is enabled | id | [HiTraceId](#hitraceid) | Yes| **HiTraceId** instance.| | flag | [HiTraceFlag](#hitraceflag) | Yes| Specified trace flag.| -**Return value** +**Return Value** | Type| Description| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index 17f62fb18b40894ad208879228387f45eed67f93..ad7e02375571c8d6d7c1829ca5f2520bf3ec13ac 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -11,21 +11,18 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; ``` -## System Capabilities - -SystemCapability.HiviewDFX.HiTrace - - ## hiTraceMeter.startTrace startTrace(name: string, taskId: number): void -Starts a trace task. +Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For a specific example, refer to an example in [hiTraceMeter.finishTrace](#hitracemeterfinishtrace). +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| @@ -37,6 +34,7 @@ If the trace tasks with the same name are not performed at the same time, the sa ``` hiTraceMeter.startTrace("myTestFunc", 1); +hiTraceMeter.startTrace("myTestFunc", 1, 5); // The expected duration of the trace task is 5 ms. ``` @@ -48,6 +46,8 @@ Stops a trace task. To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in [startTrace](#hitracemeterstarttrace). +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| @@ -90,6 +90,8 @@ traceByValue(name: string, count: number): void Traces the value changes of a variable. +**System capability**: SystemCapability.HiviewDFX.HiTrace + **Parameters** | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md new file mode 100644 index 0000000000000000000000000000000000000000..804832a1d404dffa132b55aded09528367869b7c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -0,0 +1,1191 @@ +# HUKS + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + +Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. +HUKS also provides APIs for applications to import or generate keys. + +## Modules to Import + +```js +import huks from '@ohos.security.huks' +``` +## HuksErrorCode + +Enumerates error codes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description| +| -------------------------- | ----- | ---- | +| HUKS_SUCCESS | 0 |Success.| +| HUKS_FAILURE | -1 |Failure.| +| HUKS_ERROR_BAD_STATE | -2 |Incorrect state.| +| HUKS_ERROR_INVALID_ARGUMENT | -3 |Invalid argument.| +| HUKS_ERROR_NOT_SUPPORTED | -4 |Not supported.| +| HUKS_ERROR_NO_PERMISSION | -5 |No permission.| +| HUKS_ERROR_INSUFFICIENT_DATA | -6 |Insufficient data.| +| HUKS_ERROR_BUFFER_TOO_SMALL | -7 |Insufficient buffer.| +| HUKS_ERROR_INSUFFICIENT_MEMORY | -8 |Insufficient memory.| +| HUKS_ERROR_COMMUNICATION_FAILURE | -9 |Communication failed.| +| HUKS_ERROR_STORAGE_FAILURE | -10 |Storage failure.| +| HUKS_ERROR_HARDWARE_FAILURE | -11 |Hardware fault.| +| HUKS_ERROR_ALREADY_EXISTS | -12 |The object already exists.| +| HUKS_ERROR_NOT_EXIST | -13 |The object does not exist.| +| HUKS_ERROR_NULL_POINTER | -14 |Null pointer.| +| HUKS_ERROR_FILE_SIZE_FAIL | -15 |Incorrect file size.| +| HUKS_ERROR_READ_FILE_FAIL | -16 |Failed to read the file.| +| HUKS_ERROR_INVALID_PUBLIC_KEY | -17 |Invalid public key.| +| HUKS_ERROR_INVALID_PRIVATE_KEY | -18 |Invalid private key.| +| HUKS_ERROR_INVALID_KEY_INFO | -19 |Invalid key information.| +| HUKS_ERROR_HASH_NOT_EQUAL | -20 |The hash values are not equal.| +| HUKS_ERROR_MALLOC_FAIL | -21 |MALLOC failed.| +| HUKS_ERROR_WRITE_FILE_FAIL | -22 |Failed to write the file.| +| HUKS_ERROR_REMOVE_FILE_FAIL | -23 |Failed to delete the file.| +| HUKS_ERROR_OPEN_FILE_FAIL | -24 |Failed to open the file.| +| HUKS_ERROR_CLOSE_FILE_FAIL | -25 |Failed to close the file.| +| HUKS_ERROR_MAKE_DIR_FAIL | -26 |Failed to create the directory.| +| HUKS_ERROR_INVALID_KEY_FILE | -27 |Invalid key file.| +| HUKS_ERROR_IPC_MSG_FAIL | -28 |Incorrect IPC information.| +| HUKS_ERROR_REQUEST_OVERFLOWS | -29 |Request overflows.| +| HUKS_ERROR_PARAM_NOT_EXIST | -30 |The parameter does not exist.| +| HUKS_ERROR_CRYPTO_ENGINE_ERROR | -31 |CRYPTO ENGINE error.| +| HUKS_ERROR_COMMUNICATION_TIMEOUT | -32 |Communication timed out.| +| HUKS_ERROR_IPC_INIT_FAIL | -33 |IPC initialization failed.| +| HUKS_ERROR_IPC_DLOPEN_FAIL | -34 |IPC DLOPEN failed.| +| HUKS_ERROR_EFUSE_READ_FAIL | -35 |Failed to read eFUSE.| +| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| +| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| +| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| +| HUKS_ERROR_CHECK_GET_ALG_FAIL | -100 |Failed to check whether the ALG is obtained. | +| HUKS_ERROR_CHECK_GET_KEY_SIZE_FAIL | -101 |Failed to check whether the key size is obtained.| +| HUKS_ERROR_CHECK_GET_PADDING_FAIL | -102 |Failed to check whether padding is obtained.| +| HUKS_ERROR_CHECK_GET_PURPOSE_FAIL | -103 |Failed to check whether the purpose is obtained.| +| HUKS_ERROR_CHECK_GET_DIGEST_FAIL | -104 |Failed to check whether digest is obtained.| +| HUKS_ERROR_CHECK_GET_MODE_FAIL | -105 |Failed to check whether the mode is obtained.| +| HUKS_ERROR_CHECK_GET_NONCE_FAIL | -106 |Failed to check whether the nonce is obtained.| +| HUKS_ERROR_CHECK_GET_AAD_FAIL | -107 |Failed to check whether the AAD is obtained.| +| HUKS_ERROR_CHECK_GET_IV_FAIL | -108 |Failed to check whether the initialization vector (IV) is obtained.| +| HUKS_ERROR_CHECK_GET_AE_TAG_FAIL | -109 |Failed to check whether the AE flag is obtained.| +| HUKS_ERROR_CHECK_GET_SALT_FAIL | -110 |Failed to check whether the SALT is obtained.| +| HUKS_ERROR_CHECK_GET_ITERATION_FAIL | -111 |Failed to check whether the iteration is obtained.| +| HUKS_ERROR_INVALID_ALGORITHM | -112 |Invalid algorithm.| +| HUKS_ERROR_INVALID_KEY_SIZE | -113 |Invalid key size.| +| HUKS_ERROR_INVALID_PADDING | -114 |Invalid padding.| +| HUKS_ERROR_INVALID_PURPOSE | -115 |Invalid purpose.| +| HUKS_ERROR_INVALID_MODE | -116 |Invalid mode.| +| HUKS_ERROR_INVALID_DIGEST | -117 |Invalid digest.| +| HUKS_ERROR_INVALID_SIGNATURE_SIZE | -118 |Invalid signature size.| +| HUKS_ERROR_INVALID_IV | -119 |Invalid IV.| +| HUKS_ERROR_INVALID_AAD | -120 |Invalid AAD.| +| HUKS_ERROR_INVALID_NONCE | -121 |Invalid nonce.| +| HUKS_ERROR_INVALID_AE_TAG | -122 |Invalid AE tag.| +| HUKS_ERROR_INVALID_SALT | -123 |Invalid SALT.| +| HUKS_ERROR_INVALID_ITERATION | -124 |Invalid iteration.| +| HUKS_ERROR_INVALID_OPERATION | -125 |Invalid operation.| +| HUKS_ERROR_INTERNAL_ERROR | -999 |Internal error.| +| HUKS_ERROR_UNKNOWN_ERROR | -1000 |Unknown error.| + + +## HuksKeyPurpose + +Represents the purpose (usage) of a key. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------- | +| HUKS_KEY_PURPOSE_ENCRYPT | 1 | The key is used to encrypt plain text.| +| HUKS_KEY_PURPOSE_DECRYPT | 2 | The key is used to decrypt the cipher text.| +| HUKS_KEY_PURPOSE_SIGN | 4 | The key is used to sign data. | +| HUKS_KEY_PURPOSE_VERIFY | 8 | The key is used to verify the signed data. | +| HUKS_KEY_PURPOSE_DERIVE | 16 | The key is used to derive a key. | +| HUKS_KEY_PURPOSE_WRAP | 32 | The key is used for encrypted import. | +| HUKS_KEY_PURPOSE_UNWRAP | 64 | The key is exported in encrypted mode. | +| HUKS_KEY_PURPOSE_MAC | 128 | The key is used to generate a message authentication code (MAC). | +| HUKS_KEY_PURPOSE_AGREE | 256 | The key is used for key agreement. | + +## HuksKeyDigest + +Enumerates the digest algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_DIGEST_NONE | 0 | No digest algorithm.| +| HUKS_DIGEST_MD5 | 1 | MD5.| +| HUKS_DIGEST_SHA1 | 10 | SHA1.| +| HUKS_DIGEST_SHA224 | 11 | SHA-224.| +| HUKS_DIGEST_SHA256 | 12 | SHA-256.| +| HUKS_DIGEST_SHA384 | 13 | SHA-384.| +| HUKS_DIGEST_SHA512 | 14 | SHA-512.| + +## HuksKeyPadding + +Enumerates the padding algorithms. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------- | ---- | ---------------------------------------- | +| HUKS_PADDING_NONE | 0 | No padding algorithm.| +| HUKS_PADDING_OAEP | 1 | Optimal Asymmetric Encryption Padding (OAEP).| +| HUKS_PADDING_PSS | 2 | Probabilistic Signature Scheme (PSS).| +| HUKS_PADDING_PKCS1_V1_5 | 3 | PKCS1_V1_5.| +| HUKS_PADDING_PKCS5 | 4 | Public Key Cryptography Standards (PKCS)#5.| +| HUKS_PADDING_PKCS7 | 5 | PKCS#7| + +## HuksCipherMode + +Enumerates the cipher modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------- | ---- | --------------------- | +| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode.| +| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode.| +| HUKS_MODE_CTR | 3 | Counter (CTR) mode.| +| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode.| +| HUKS_MODE_CCM | 31 | Counter with CBC-MAC (CCM) mode.| +| HUKS_MODE_GCM | 32 | Galois/Counter (GCM) mode.| + +## HuksKeySize + +Represents the key length. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------------------- | ---- | ------------------------------------------ | +| HUKS_RSA_KEY_SIZE_512 | 512 | Rivest-Shamir-Adleman (RSA) key of 512 bits. | +| HUKS_RSA_KEY_SIZE_768 | 768 | RSA key of 768 bits. | +| HUKS_RSA_KEY_SIZE_1024 | 1024 | RSA key of 1024 bits. | +| HUKS_RSA_KEY_SIZE_2048 | 2048 | RSA key of 2048 bits. | +| HUKS_RSA_KEY_SIZE_3072 | 3072 | RSA key of 3072 bits. | +| HUKS_RSA_KEY_SIZE_4096 | 4096 | RSA key of 4096 bits. | +| HUKS_ECC_KEY_SIZE_224 | 224 | ECC key of 224 bits. | +| HUKS_ECC_KEY_SIZE_256 | 256 | ECC key of 256 bits. | +| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits. | +| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits. | +| HUKS_AES_KEY_SIZE_128 | 128 | AES key of 128 bits. | +| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits. | +| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits. | +| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits. | +| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits.| +| HUKS_DH_KEY_SIZE_2048 | 2048 | DH key of 2048 bits. | +| HUKS_DH_KEY_SIZE_3072 | 3072 | DH key of 3072 bits. | +| HUKS_DH_KEY_SIZE_4096 | 4096 | DH key of 4096 bits. | + +## HuksKeyAlg + +Represents the algorithm used by a key. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ---------------- | ---- | --------------------- | +| HUKS_ALG_RSA | 1 | RSA. | +| HUKS_ALG_ECC | 2 | ECC. | +| HUKS_ALG_DSA | 3 | DSA. | +| HUKS_ALG_AES | 20 | AES. | +| HUKS_ALG_HMAC | 50 | HMAC. | +| HUKS_ALG_HKDF | 51 | HKDF. | +| HUKS_ALG_PBKDF2 | 52 | PBKDF2. | +| HUKS_ALG_ECDH | 100 | ECDH. | +| HUKS_ALG_X25519 | 101 | X25519 algorithm. | +| HUKS_ALG_ED25519 | 102 | ED25519 algorithm.| +| HUKS_ALG_DH | 103 | DH. | + +## HuksKeyGenerateType + +Enumerates the key generation types. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------- | +| HUKS_KEY_GENERATE_TYPE_DEFAULT | 0 | Key generated by default.| +| HUKS_KEY_GENERATE_TYPE_DERIVE | 1 | Derived key.| +| HUKS_KEY_GENERATE_TYPE_AGREE | 2 | Key generated by agreement.| + +## HuksKeyFlag + +Enumerates the key generation modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------- | ---- | ------------------------------------ | +| HUKS_KEY_FLAG_IMPORT_KEY | 1 | The key is imported by using the public key import API. | +| HUKS_KEY_FLAG_GENERATE_KEY | 2 | The key is generated by using the private key generation API. | +| HUKS_KEY_FLAG_AGREE_KEY | 3 | The key is generated by using the key agreement API.| +| HUKS_KEY_FLAG_DERIVE_KEY | 4 | The key is generated by using the key derivation API.| + +## HuksKeyStorageType + +Enumerates the key storage modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| ----------------------- | ---- | ------------------------------ | +| HUKS_STORAGE_TEMP | 0 | The key is managed locally. | +| HUKS_STORAGE_PERSISTENT | 1 | The key is managed by the HUKS service.| + +## HuksSendType + +Enumerates the tag transfer modes. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------- | ---- | ----------------- | +| HUKS_SEND_TYPE_ASYNC | 0 | Send the tag asynchronously.| +| HUKS_SEND_TYPE_SYNC | 1 | Send the tag synchronously.| + +## HuksTagType + +Enumerates the tag data types. + +**System capability**: SystemCapability.Security.Huks + + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| HUKS_TAG_TYPE_INVALID | 0 << 28 | Invalid tag type. | +| HUKS_TAG_TYPE_INT | 1 << 28 | Number of the int type. | +| HUKS_TAG_TYPE_UINT | 2 << 28 | Number of the uint type.| +| HUKS_TAG_TYPE_ULONG | 3 << 28 | bigint. | +| HUKS_TAG_TYPE_BOOL | 4 << 28 | Boolean. | +| HUKS_TAG_TYPE_BYTES | 5 << 28 | Uint8Array. | + +## HuksTag + +Enumerates the tags used to invoke parameters. + +**System capability**: SystemCapability.Security.Huks + +| Name | Value | Description | +| -------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Indicates the algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Indicates the purpose of a key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Indicates the key length. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Indicates the digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Indicates the padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Indicates the cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Indicates the key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Indicates the associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Indicates the field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | Indicates the IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Indicates the information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Indicates the salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Indicates the password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Indicates the number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Indicates the key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Indicates the main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Indicates the factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Indicates the type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Indicates the type of the algorithm used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Indicates the alias of the public key during key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Indicates the private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Indicates the public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Indicates the key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Indicates the size of the derived key. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | Reserved. | +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Indicates the challenge value used in the attestation. | +| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Indicates the application ID used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Indicates the device brand. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Indicates the device. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Indicates the product. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Indicates the device SN. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Indicates the device IMEI. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Indicates the device MEID. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Indicates the device manufacturer. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Indicates the device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Indicates the key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Indicates the device SOCID. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Indicates the device UDID. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Indicates the security credential used for the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Indicates the version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Indicates whether to use the tag of the alias passed during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Indicates the key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Indicates the flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Indicates the process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Indicates the key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | Indicates the operating system version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | Indicates the operating system patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | + +## huks.generateKey + +generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Generates a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huksHuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE +}; +var options = { + properties: properties +}; +huks.generateKey(alias, options, function (err, data){}); +``` + +## huks.generateKey + +generateKey(keyAlias: string, options: HuksOptions) : Promise\ + +Generates a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| keyAlias | string | Yes | Alias of the key. | +| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huksHuksKeyAlg.HUKS_ALG_RSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_512 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_ENCRYPT | huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_DECRYPT +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB +}; +properties[5] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE +}; +var options = { + properties: properties +}; +var result = huks.generateKey(alias, options); +``` + +## huks.deleteKey + +deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Deletes a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var emptyOptions = { + properties: [] +}; +huks.deleteKey(alias, emptyOptions, function (err, data) {}); +``` + +## huks.deleteKey + +deleteKey(keyAlias: string, options: HuksOptions) : Promise\ + +Deletes a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----------------------------------------------------- | +| keyAlias | string | Yes | Key alias passed in when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var alias = 'alias'; +var emptyOptions = { + properties: [] +}; +var result = huks.deleteKey(alias, emptyOptions); +``` + +## huks.getSdkVersion + +getSdkVersion(options: HuksOptions) : string + +Obtains the SDK version of the current system. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------- | ---- | ------------------------- | +| options | [HuksOptions](#huksoptions) | Yes | Empty object, which is used to hold the SDK version.| + +**Return value** + +| Type | Description | +| ------ | ------------- | +| string | SDK version obtained.| + +**Example** + +```js +var emptyOptions = { + properties: [] +}; +var result = huks.getSdkVersion(emptyOptions); +``` + +## huks.importKey + +importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Imports a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------------------------------- | +| keyAlias | string | Yes | Key alias, which is used to hold the key pair.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key pair to import.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: 1024 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: HUKS_DIGEST_SHA1 +}; +var options = { + properties: properties, + inData: importText +}; +huks.importKey(keyAlias, options, function (err, data){}); +``` + +## huks.importKey + +importKey(keyAlias: string, options: HuksOptions) : Promise\ + +Imports a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------ | +| keyAlias | string | Yes | Key alias, which is used to hold the key pair.| +| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key pair to import.| + +**Return value** + +| Type | Description | +| ----------------------------------- | -------------------------------------------------- | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_DSA +}; +properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: 1024 +}; +properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY +}; +properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_NONE +}; +properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: HUKS_DIGEST_SHA1 +}; +var options = { + properties: properties, + inData: importText +}; +var result = huks.importKey(keyAlias, options); +``` + +## huks.exportKey + +exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Exports a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.
**outData** contains the public key exported.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.exportKey(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.exportKey + +exportKey(keyAlias: string, options: HuksOptions) : Promise\ + +Exports a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------------------------------------ | +| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned. For details about the error codes, see **HuksResult**.
**outData** contains the public key exported.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.exportKey(keyAlias, emptyOptions); +``` + +## huks.getKeyProperties + +getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Obtains key properties. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.getKeyProperties + +getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ + +Obtains key properties. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------------------------------------ | +| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ------------------ | ------------------------------------------------------------ | +| Promise\<[HuksResult](#huksoptions)> | Promise used to return the result. In **errorCode**, **HUKS_SUCCESS** will be returned if the operation is successful; an error code will be returned otherwise. For details about the error codes, see **HuksResult**.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.getKeyProperties(keyAlias, emptyOptions); +``` + +## huks.isKeyExist + +isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Checks whether a key exists. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| keyAlias | string | Yes | Alias of the key to check.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); +``` + +## huks.isKeyExist + +isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ + +Checks whether a key exists. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | -------------------------------- | +| keyAlias | string | Yes | Alias of the key to check.| +| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty).| + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| + +**Example** + +```js +var keyAlias = 'keyAlias'; +var emptyOptions = { + properties: [] +}; +var result = huks.isKeyExist(keyAlias, emptyOptions); +``` + + +## huks.init + +init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void + +Initializes a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| keyAlias | string | Yes | Alias of the target key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| +| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback used to return the handle of the **Init** operation.| + +**Example** + +```js +var alias = 'test001' +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.init(alias, options, function(err, data) { + if (err.code !== 0) { + console.log("test init err information: " + JSON.stringify(err)); + } else { + console.log(`test init data: ${JSON.stringify(data)}`); + } +}) +``` + +## huks.init + +init(keyAlias: string, options: HuksOptions) : Promise\ + +Initializes a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| keyAlias | string | Yes | Alias of the target key.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Init** operation.| +| promise | Promise\<[HuksHandle](#hukshandle)> | Yes | Promise used to return the handle of the **Init** operation.| + +**Example** + +```js +var alias = 'test001' +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.init(alias, options).then((data) => { + console.log(`test init data: ${JSON.stringify(data)}`); + handle1 = data.handle1; + handle2 = data.handle2; + handle = { + "handle1": handle1, + "handle2": handle2 + }; +}).catch((err) => { + console.log("test init err information: " + JSON.stringify(err)) +}) +``` + + +## huks.update + +update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void + +Updates a key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation.| +| token | Uint8Array | No| Token of the **Update** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.| +| callback | AsyncCallback\<[HksResult](#hksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.update(handle, options, function (err, data){}); +``` + +## huks.update + +update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ + +Updates a key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Update** operation.| +| token | Uint8Array | No| Token of the **Update** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Update** operation.| +| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.update(handle, options) +``` + +## huks.finish + +finish(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Completes the key operation and releases resources. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.finish(handle, options, function (err, data){}); +``` + +## huks.finish + +finish(handle: number, options: HuksOptions) : Promise\ + +Completes the key operation and releases resources. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Finish** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Finish** operation.| +| promise | Promise\<[HuksResult](#HuksResult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.finish(handle, options) +``` + + +## huks.abort + +abort(handle: number, options: HuksOptions, callback: AsyncCallback\) : void + +Aborts the use of the key. This method uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Abort** operation.| +| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +huks.abort(handle, options, function (err, data){}); +``` + +## huks.abort + +abort(handle: number, options: HuksOptions) : Promise\; + +Aborts the use of the key. This method uses a promise to return the result. + +**System capability**: SystemCapability.Security.Huks + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------- | +| handle | number | Yes | Handle of the **Abort** operation.| +| options | [HuksOptions](#huksoptions) | Yes | Parameter set of the **Abort** operation.| +| promise | Promise\<[HuksResult](#huksresult)> | Yes| Promise used to return the operation result.| + +**Example** + +```js +var properties = new Array(); +properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH +}; +properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE +}; +properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 +}; +var options = { + properties: properties +}; +var result = huks.abort(handle, options); +``` + +## HuksParam + +Defines the **param** in the **properties** array of **options** used in the APIs. + +**System capability**: SystemCapability.Security.Huks + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ---------- | +| tag | HuksTag | Yes | Tag. | +| value | boolean\|number\|bigint\|Uint8Array | Yes | Value of the tag.| + +## HuksOptions + +Defines the **options** used in the APIs. + +**System capability**: SystemCapability.Security.Huks + +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | ------------------------ | +| properties | Array\ | No | Array used to hold **HuksParam**.| +| inData | Uint8Array | No | Input data. | + +## HuksHandle + +Defines the HUKS handle structure. + +**System capability**: SystemCapability.Security.Huks + +| Name | Type | Mandatory| Description | +| ---------- | ---------------- | ---- | -------- | +| errorCode | number | Yes | Error code.| +| handle | number | Yes| Value of the handle.| +| token | Uint8Array | No| Reserved field.| + + +## HuksResult + +Defines the **HuksResult** structure. + +**System capability**: SystemCapability.Security.Huks + + + +| Name | Type | Mandatory| Description | +| ---------- | ----------------- | ---- | -------- | +| errorCode | number | Yes | Error code. | +| outData | Uint8Array | No | Output data.| +| properties | Array\ | No | Properties. | +| certChains | Array\ | No | Certificate chain. | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index f262500a4c6100e3d5a6eef9e9fe2705390321ee..757c0733f14437a0c97bf8b349577aab4e4959fa 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -2,7 +2,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > - This module contains enhanced i18n APIs, which are not defined in ECMA 402. @@ -21,19 +21,19 @@ Obtains the localized script for the specified language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Specified language.| - | locale | string | Yes| Locale ID.| - | sentenceCase | boolean | No| Whether to use sentence case for the localized script.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------- | +| language | string | Yes | Specified language. | +| locale | string | Yes | Locale ID. | +| sentenceCase | boolean | No | Whether to use sentence case for the localized script.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Localized script for the specified language.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Localized script for the specified language.| -- Example +**Example** ``` i18n.getDisplayLanguage("zh", "en-GB", true); i18n.getDisplayLanguage("zh", "en-GB"); @@ -48,26 +48,26 @@ Obtains the localized script for the specified country. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | country | string | Yes| Specified country.| - | locale | string | Yes| Locale ID.| - | sentenceCase | boolean | No| Whether to use sentence case for the localized script.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------------ | ------- | ---- | ---------------- | +| country | string | Yes | Specified country. | +| locale | string | Yes | Locale ID. | +| sentenceCase | boolean | No | Whether to use sentence case for the localized script.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Localized script for the specified country.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Localized script for the specified country.| -- Example +**Example** ``` i18n.getDisplayCountry("zh-CN", "en-GB", true); i18n.getDisplayCountry("zh-CN", "en-GB"); ``` -## i18n.isRTL8+ +## i18n.isRTL7+ isRTL(locale: string): boolean @@ -75,17 +75,17 @@ Checks whether the localized script for the specified language is displayed from **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | locale | string | Locale ID.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | ------- | +| locale | string | Locale ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.| -- Example +**Example** ``` i18n.isRTL("zh-CN");// Since Chinese is not written from right to left, false is returned. i18n.isRTL("ar-EG");// Since Arabic is written from right to left, true is returned. @@ -100,12 +100,12 @@ Obtains the system language. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System language ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System language ID.| -- Example +**Example** ``` i18n.getSystemLanguage(); ``` @@ -117,19 +117,21 @@ setSystemLanguage(language: string): boolean Sets the system language. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | language | string | Language ID.| +**Parameters** +| Name | Type | Description | +| -------- | ------ | ----- | +| language | string | Language ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemLanguage('zh'); ``` @@ -137,18 +139,18 @@ Sets the system language. ## i18n.getSystemLanguages -getSystemLanguages(): Array +getSystemLanguages(): Array<string> Obtains the list of system languages. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of the IDs of system languages.| +**Return Value** +| Type | Description | +| ------------------- | ------------ | +| Array<string> | List of the IDs of system languages.| -- Example +**Example** ``` i18n.getSystemLanguages(); ``` @@ -156,23 +158,23 @@ Obtains the list of system languages. ## i18n.getSystemCountries -getSystemCountries(language: string): Array +getSystemCountries(language: string): Array<string> Obtains the list of countries and regions supported for the specified language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | language | string | Language ID.| +**Parameters** +| Name | Type | Description | +| -------- | ------ | ----- | +| language | string | Language ID.| -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of the IDs of the countries and regions supported for the specified language.| +**Return Value** +| Type | Description | +| ------------------- | ------------ | +| Array<string> | List of the IDs of the countries and regions supported for the specified language.| -- Example +**Example** ``` i18n.getSystemCountries('zh'); ``` @@ -186,12 +188,12 @@ Obtains the system region. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System region ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System region ID.| -- Example +**Example** ``` i18n.getSystemRegion(); ``` @@ -203,19 +205,21 @@ setSystemRegion(region: string): boolean Sets the system region. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | region | string | Region ID.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | ----- | +| region | string | Region ID.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemRegion(); ``` @@ -229,12 +233,12 @@ Obtains the system locale. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | System locale ID.| +**Return Value** +| Type | Description | +| ------ | ------- | +| string | System locale ID.| -- Example +**Example** ``` i18n.getSystemLocale(); ``` @@ -246,19 +250,21 @@ setSystemLocale(locale: string): boolean Sets the system locale. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Description| - | -------- | -------- | -------- | - | locale | string | System locale ID, for example, **zh-CN**.| +**Parameters** +| Name | Type | Description | +| ------ | ------ | --------------- | +| locale | string | System locale ID, for example, **zh-CN**.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -- Example +**Example** ``` i18n.setSystemLocale('zh-CN'); ``` @@ -272,18 +278,18 @@ Checks whether the system language matches the specified region. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Valid language ID, for example, **zh**.| - | region | string | No| Valid region ID, for example, **CN**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------- | +| language | string | Yes | Valid language ID, for example, **zh**.| +| region | string | No | Valid region ID, for example, **CN**. | -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.| -- Example +**Example** ``` i18n.isSuggested('zh', 'CN'); ``` @@ -297,18 +303,18 @@ Obtains a **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Valid locale value, for example, **zh-Hans-CN**.| - | type | string | No| Valid calendar type. Currently, the valid types are as follows: **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic\_civil**, **islamic\_tbla**, **islamic\_umalqura**, **japanese**, and **persian**. If this parameter is left unspecified, the default calendar type of the specified locale is used.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. | +| type | string | No | Valid calendar type. Currently, the valid types are as follows: **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic\_civil**, **islamic\_tbla**, **islamic\_umalqura**, **japanese**, and **persian**. If this parameter is left unspecified, the default calendar type of the specified locale is used.| -- Return value - | Type| Description| - | -------- | -------- | - | [Calendar](#calendar8) | **Calendar** object.| +**Return Value** +| Type | Description | +| ---------------------- | ----- | +| [Calendar](#calendar8) | **Calendar** object.| -- Example +**Example** ``` i18n.getCalendar("zh-Hans", "gregory"); ``` @@ -325,12 +331,12 @@ Sets the date for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | Yes| Date to be set for the **Calendar** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ----------------- | +| date | Date | Yes | Date to be set for the **Calendar** object.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); var date = new Date(2021, 10, 7, 8, 0, 0, 0); @@ -346,12 +352,12 @@ Sets the date and time for this **Calendar** object. The value is represented by **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | time | number | Yes| Number of milliseconds that have elapsed since the Unix epoch.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ---------------------------------------- | +| time | number | Yes | Number of milliseconds that have elapsed since the Unix epoch.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); @@ -366,17 +372,17 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | year | number | Yes| Year to set.| - | month | number | Yes| Month to set.| - | date | number | Yes| Day to set.| - | hour | number | No| Hour to set.| - | minute | number | No| Minute to set.| - | second | number | No| Second to set.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------ | +| year | number | Yes | Year to set. | +| month | number | Yes | Month to set. | +| date | number | Yes | Day to set. | +| hour | number | No | Hour to set.| +| minute | number | No | Minute to set.| +| second | number | No | Second to set. | -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 @@ -391,12 +397,12 @@ Sets the time zone of this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | timezone | string | Yes| Time zone, for example, **Asia/Shanghai**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------- | +| timezone | string | Yes | Time zone, for example, **Asia/Shanghai**.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); @@ -411,12 +417,12 @@ Obtains the time zone of this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Time zone of the **Calendar** object.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Time zone of the **Calendar** object.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); @@ -432,12 +438,12 @@ Obtains the start day of a week for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +**Return Value** +| Type | Description | +| ------ | --------------------- | +| number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| -- Example +**Example** ``` var calendar = I18n.getCalendar("en-US", "gregory"); calendar.getFirstDayOfWeek(); @@ -452,12 +458,12 @@ Sets the start day of a week for this **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | No| Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | --------------------- | +| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setFirstDayOfWeek(0); @@ -472,12 +478,12 @@ Obtains the minimum number of days in the first week of a year. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Minimum number of days in the first week of a year.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| number | Minimum number of days in the first week of a year.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.getMinimalDaysInFirstWeek(); @@ -492,12 +498,12 @@ Sets the minimum number of days in the first week of a year. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | No| Minimum number of days in the first week of a year.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------ | +| value | number | No | Minimum number of days in the first week of a year.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); @@ -512,17 +518,17 @@ Obtains the value of the specified field in the **Calendar** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Value of the specified field in the **Calendar** object. Currently, a valid field can be any of the following: **era**, **year**, **month**, **week\_of\_year**, **week\_of\_month**, **date**, **day\_of\_year**, **day\_of\_week**, **day\_of\_week\_in\_month**, **hour**, **hour\_of\_day**, **minute**, **second**, **millisecond**, **zone\_offset**, **dst\_offset**, **year\_woy**, **dow\_local**, **extended\_year**, **julian\_day**, **milliseconds\_in\_day**, **is\_leap\_month**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| field | string | Yes | Value of the specified field in the **Calendar** object. Currently, a valid field can be any of the following: **era**, **year**, **month**, **week\_of\_year**, **week\_of\_month**, **date**, **day\_of\_year**, **day\_of\_week**, **day\_of\_week\_in\_month**, **hour**, **hour\_of\_day**, **minute**, **second**, **millisecond**, **zone\_offset**, **dst\_offset**, **year\_woy**, **dow\_local**, **extended\_year**, **julian\_day**, **milliseconds\_in\_day**, **is\_leap\_month**.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 @@ -538,17 +544,17 @@ Obtains the name of the **Calendar** object displayed for the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Locale for which the name of the **Calendar** object is displayed. For example, if **locale** is **en-US**, the name of the Buddhist calendar will be **Buddhist Calendar**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Locale for which the name of the **Calendar** object is displayed. For example, if **locale** is **en-US**, the name of the Buddhist calendar will be **Buddhist Calendar**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Name of the **Calendar** object displayed for the specified locale.| +**Return Value** +| Type | Description | +| ------ | ------------------- | +| string | Name of the **Calendar** object displayed for the specified locale.| -- Example +**Example** ``` var calendar = i18n.getCalendar("en-US", "buddhist"); calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. @@ -563,17 +569,17 @@ Checks whether the specified date in this **Calendar** object is a weekend. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | No| Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ---------------------------------------- | +| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the date is a weekend; returns **false** if the date is a weekday.| +**Return Value** +| Type | Description | +| ------- | ----------------------------------- | +| boolean | Returns **true** if the date is a weekend; returns **false** if the date is a weekday.| -- Example +**Example** ``` var calendar = i18n.getCalendar("zh-Hans"); calendar.setTime(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 @@ -595,12 +601,12 @@ Creates a **PhoneNumberFormat** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes| Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No| Options of the **PhoneNumberFormat** object.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------- | +| country | string | Yes | Country or region to which the phone number to be formatted belongs.| +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | -- Example +**Example** ``` var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -614,17 +620,17 @@ Checks whether the format of the specified phone number is valid. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | string | Yes| Phone number to be checked.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------- | +| number | string | Yes | Phone number to be checked.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------- | +| boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.| -- Example +**Example** ``` var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); phonenumberfmt.isValidNumber("15812312312"); @@ -639,17 +645,17 @@ Formats a phone number. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | string | Yes| Phone number to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------- | +| number | string | Yes | Phone number to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Formatted phone number.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Formatted phone number.| -- Example +**Example** ``` var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); phonenumberfmt.format("15812312312"); @@ -662,9 +668,9 @@ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| type | string | Yes| Yes| Format type of a phone number. The value can be **E164**, **INTERNATIONAL**, **NATIONAL**, or **RFC3966**.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | Yes | Yes | Format type of a phone number. The value can be **E164**, **INTERNATIONAL**, **NATIONAL**, or **RFC3966**.| ## UnitInfo8+ @@ -673,10 +679,10 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| unit | string | Yes| Yes| Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| -| measureSystem | string | Yes| Yes| Measurement system. The value can be **SI**, **US**, or **UK**.| +| Name | Type | Readable | Writable | Description | +| ------------- | ------ | ---- | ---- | ---------------------------------------- | +| unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| +| measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| ## Util8+ @@ -690,21 +696,21 @@ Converts one measurement unit into another and formats the unit based on the spe **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fromUnit | [UnitInfo](#unitinfo8) | Yes| Measurement unit to be converted.| - | toUnit | [UnitInfo](#unitinfo8) | Yes| Measurement unit to be converted to.| - | value | number | Yes| Value of the measurement unit to be converted.| - | locale | string | Yes| Locale used for formatting, for example, **zh-Hans-CN**.| - | style | string | No| Style used for formatting. The value can be **long**, **short**, or **medium**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| fromUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted. | +| toUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted to. | +| value | number | Yes | Value of the measurement unit to be converted. | +| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. | +| style | string | No | Style used for formatting. The value can be **long**, **short**, or **medium**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.| +**Return Value** +| Type | Description | +| ------ | ----------------------- | +| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.| -- Example +**Example** ``` I18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); ``` @@ -718,17 +724,17 @@ Creates an **IndexUtil** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | No| A string containing locale information, including the language, optional script, and region.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------- | +| locale | string | No | A string containing locale information, including the language, optional script, and region.| -- Return value - | Type| Description| - | -------- | -------- | - | [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the specified locale.| +**Return Value** +| Type | Description | +| ------------------------ | --------------------- | +| [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the specified locale.| -- Example +**Example** ``` var indexUtil= i18n.IndexUtil.getInstance("zh-CN"); ``` @@ -745,12 +751,12 @@ Obtains the index list for this **locale** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array<string> | Index list for this **locale** object.| +**Return Value** +| Type | Description | +| ------------------- | ------------------ | +| Array<string> | Index list for this **locale** object.| -- Example +**Example** ``` var indexUtil = i18n.getInstance("zh-CN"); var indexList = indexUtil.getIndexList(); @@ -765,12 +771,12 @@ Adds the index of the new **locale** object to the index list. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| A string containing locale information, including the language, optional script, and region.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -- Example +**Example** ``` var indexUtil = i18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); @@ -785,17 +791,17 @@ Obtains the index of a text object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | text | string | Yes| **text** object whose index is to be obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| text | string | Yes | **text** object whose index is to be obtained.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Index of the **text** object.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | Index of the **text** object.| -- Example +**Example** ``` var indexUtil= i18n.getInstance("zh-CN"); indexUtil.getIndex("hi"); // Return h. @@ -813,17 +819,17 @@ Checks whether the input character string is composed of digits. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a digit; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.| -- Example +**Example** ``` var isdigit = Character.isDigit("1"); // Return true. ``` @@ -837,17 +843,17 @@ Checks whether the input character is a space. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a space; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Returns **true** if the input character is a space; returns **false** otherwise.| -- Example +**Example** ``` var isspacechar = Character.isSpaceChar("a"); // Return false. ``` @@ -861,17 +867,17 @@ Checks whether the input character is a white space. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a white space; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.| -- Example +**Example** ``` var iswhitespace = Character.isWhitespace("a"); // Return false. ``` @@ -885,17 +891,17 @@ Checks whether the input character is of the right to left (RTL) language. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.| -- Example +**Example** ``` var isrtl = Character.isRTL("a"); // Return false. ``` @@ -909,17 +915,17 @@ Checks whether the input character is an ideographic character. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.| -- Example +**Example** ``` var isideograph = Character.isIdeograph("a"); // Return false. ``` @@ -933,17 +939,17 @@ Checks whether the input character is a letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------------ | +| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.| -- Example +**Example** ``` var isletter = Character.isLetter("a"); // Return true. ``` @@ -957,17 +963,17 @@ Checks whether the input character is a lowercase letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.| -- Example +**Example** ``` var islowercase = Character.isLowerCase("a"); // Return true. ``` @@ -981,17 +987,17 @@ Checks whether the input character is an uppercase letter. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.| -- Example +**Example** ``` var isuppercase = Character.isUpperCase("a"); // Return false. ``` @@ -1005,17 +1011,17 @@ Obtains the type of the input character string. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | char | string | Yes| Input character.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| char | string | Yes | Input character.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Type of the input character.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | Type of the input character.| -- Example +**Example** ``` var type = Character.getType("a"); ``` @@ -1029,17 +1035,17 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| Valid locale value, for example, **zh-Hans-CN**. The [BreakIterator](#breakiterator8) object segments text according to the rules of the specified locale.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. The [BreakIterator](#breakiterator8) object segments text according to the rules of the specified locale.| -- Return value - | Type| Description| - | -------- | -------- | - | [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.| +**Return Value** +| Type | Description | +| -------------------------------- | ----------- | +| [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.| -- Example +**Example** ``` i18n.getLineInstance("en"); ``` @@ -1056,12 +1062,12 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | text | string | Yes| Text to be processed by the **BreakIterator** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------- | +| text | string | Yes | Text to be processed by the **BreakIterator** object.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1076,12 +1082,12 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Text being processed by the **BreakIterator** object.| +**Return Value** +| Type | Description | +| ------ | ---------------------- | +| string | Text being processed by the **BreakIterator** object.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1097,12 +1103,12 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the **BreakIterator** object in the text being processed.| +**Return Value** +| Type | Description | +| ------ | --------------------------- | +| number | Position of the **BreakIterator** object in the text being processed.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1118,12 +1124,12 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset to the first text boundary of the processed text.| +**Return Value** +| Type | Description | +| ------ | ----------------- | +| number | Offset to the first text boundary of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1139,12 +1145,12 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset of the last text boundary of the processed text.| +**Return Value** +| Type | Description | +| ------ | ------------------ | +| number | Offset of the last text boundary of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1160,17 +1166,17 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | index | number | No| Number of text boundaries by which the [BreakIterator](#breakiterator8) object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as **1**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| index | number | No | Number of text boundaries by which the [BreakIterator](#breakiterator8) object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as **1**.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved by the specified number of text boundaries. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved by the specified number of text boundaries. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1188,12 +1194,12 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved to the previous text boundary. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved to the previous text boundary. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1211,17 +1217,17 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | offset | number | Yes| Offset to the position before the text boundary to which the [BreakIterator](#breakiterator8) object is moved.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| offset | number | Yes | Offset to the position before the text boundary to which the [BreakIterator](#breakiterator8) object is moved.| -- Return value - | Type| Description| - | -------- | -------- | - | number | The value **-1** is returned if the text boundary to which the [BreakIterator](#breakiterator8) object is moved is outside of the processed text.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | The value **-1** is returned if the text boundary to which the [BreakIterator](#breakiterator8) object is moved is outside of the processed text.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1239,17 +1245,17 @@ Checks whether the position specified by the offset is a text boundary. If **tru **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | offset | number | Yes| Position to check.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----------- | +| offset | number | Yes | Position to check.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the position specified by the offset is a text boundary; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the position specified by the offset is a text boundary; returns **false** otherwise.| -- Example +**Example** ``` iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); @@ -1258,7 +1264,7 @@ Checks whether the position specified by the offset is a text boundary. If **tru ``` -## i18n.is24HourClock8+ +## i18n.is24HourClock7+ is24HourClock(): boolean @@ -1266,36 +1272,38 @@ Checks whether the 24-hour clock is used. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.| -- Example +**Example** ``` var is24HourClock = i18n.is24HourClock(); ``` -## i18n.set24HourClock8+ +## i18n.set24HourClock7+ set24HourClock(option: boolean): boolean Sets the 24-hour clock. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | option | boolean | Yes| Whether to enable the 24-hour clock. The value **true** means to enable the 24-hour clock, and the value **false** means the opposite.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | ---------------------------------------- | +| option | boolean | Yes | Whether to enable the 24-hour clock. The value **true** means to enable the 24-hour clock, and the value **false** means the opposite.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.| -- Example +**Example** ``` // Set the system time to the 24-hour clock. var success = I18n.set24HourClock(true); @@ -1308,20 +1316,22 @@ addPreferredLanguage(language: string, index?: number): boolean Adds a preferred language to the specified position on the preferred language list. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | language | string | Yes| Preferred language to add.| - | index | number | No| Position to which the preferred language is added.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ---------- | +| language | string | Yes | Preferred language to add. | +| index | number | No | Position to which the preferred language is added.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.| -- Example +**Example** ``` // Add zh-CN to the preferred language list. var language = 'zh-CN'; @@ -1336,19 +1346,21 @@ removePreferredLanguage(index: number): boolean Deletes a preferred language from the specified position on the preferred language list. +**Required permission**: ohos.permission.UPDATE_CONFIGURATION + **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | index | number | Yes| Position of the preferred language to delete.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | --------------------- | +| index | number | Yes | Position of the preferred language to delete.| -- Return value - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.| +**Return Value** +| Type | Description | +| ------- | ----------------------------- | +| boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.| -- Example +**Example** ``` // Delete the first preferred language from the preferred language list. var index = 0; @@ -1358,18 +1370,18 @@ Deletes a preferred language from the specified position on the preferred langua ## i18n.getPreferredLanguageList8+ -getPreferredLanguageList(): Array +getPreferredLanguageList(): Array<string> Obtains the list of preferred languages. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | Array | List of preferred languages.| +**Return Value** +| Type | Description | +| ------------------- | --------- | +| Array<string> | List of preferred languages.| -- Example +**Example** ``` var preferredLanguageList = i18n.getPreferredLanguageList(); ``` @@ -1383,18 +1395,18 @@ Obtains the first language in the preferred language list. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | First language in the preferred language list.| +**Return Value** +| Type | Description | +| ------ | -------------- | +| string | First language in the preferred language list.| -- Example +**Example** ``` var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); ``` -## i18n.getTimeZone8+ +## i18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1402,17 +1414,17 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | zondID | string | No| Time zone ID.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| zondID | string | No | Time zone ID.| -- Return value - | Type| Description| - | -------- | -------- | - | TimeZone | **TimeZone** object corresponding to the time zone ID.| +**Return Value** +| Type | Description | +| -------- | ------------ | +| TimeZone | **TimeZone** object corresponding to the time zone ID.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); ``` @@ -1429,12 +1441,12 @@ Obtains the ID of the specified **TimeZone** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | Time zone ID corresponding to the **TimeZone** object.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| string | Time zone ID corresponding to the **TimeZone** object.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getID(); @@ -1449,18 +1461,18 @@ Obtains the representation of a **TimeZone** object in the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | No| System locale ID.| - | isDST | boolean | No| Whether to consider DST when obtaining the representation of the **TimeZone** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| locale | string | No | System locale ID. | +| isDST | boolean | No | Whether to consider DST when obtaining the representation of the **TimeZone** object.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Representation of the **TimeZone** object in the specified locale.| +**Return Value** +| Type | Description | +| ------ | ------------- | +| string | Representation of the **TimeZone** object in the specified locale.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getDisplayName("zh-CN", false); @@ -1475,12 +1487,12 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.| +**Return Value** +| Type | Description | +| ------ | ------------------- | +| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getRawOffset(); @@ -1495,12 +1507,12 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point.| +**Return Value** +| Type | Description | +| ------ | ----------------------- | +| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point.| -- Example +**Example** ``` var timezone = i18n.getTimeZone(); timezone.getOffset(1234567890); diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 8a112fc22b0502bbf128227c82a4f5122bec99e1..3fd4d48c7bed58bd32e75c5388ea582b62d2cea1 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,18 +1,16 @@ -Image Processing -========== +# Image Processing > **NOTE** -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - Modules to Import ---------- +## Modules to Import ``` import image from '@ohos.multimedia.image'; ``` ## image.createPixelMap8+ -createPixelMap(colors: ArrayBuffer, opts: InitializetionOptions): Promise\ +createPixelMap(colors: ArrayBuffer, options: InitializetionOptions): Promise\ Creates a **PixelMap** object. This API uses a promise to return the result. @@ -20,30 +18,28 @@ Creates a **PixelMap** object. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| colors | ArrayBuffer | Yes | Color array. | -| opts | [InitializetionOptions](#InitializationOptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| colors | ArrayBuffer | Yes | Color array. | +| options | [InitializetionOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** | Type | Description | | -------------------------------- | -------------- | -| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object created.| +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| **Example** ```js image.createPixelMap(Color, opts) .then((pixelmap) => { - expect(pixelmap !== null).assertTrue() - done() }) ``` ## image.createPixelMap8+ -createPixelMap(colors: ArrayBuffer, opts: InitializetionOptions) callback: AsyncCallback\): void +createPixelMap(colors: ArrayBuffer, options: InitializetionOptions, callback: AsyncCallback\): void Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. @@ -51,18 +47,16 @@ Creates a **PixelMap** object. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------- | -| colors | ArrayBuffer | Yes | Color array. | -| opts | [InitializetionOptions](#InitializationOptions8) | Yes | Pixel properties. | -| callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | -------------------------- | +| colors | ArrayBuffer | Yes | Color array. | +| options | [InitializetionOptions](#initializationoptions8) | Yes | Pixel properties. | +| callback | AsyncCallback\<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js image.createPixelMap(Color, opts, (pixelmap) => { - expect(pixelmap !== null).assertTrue() - done() }) ``` @@ -100,25 +94,10 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u ```js pixelmap.readPixelsToBuffer(readBuffer).then(() => { - var bufferArr = new Uint8Array(readBuffer) - var res = true - for (var i = 0; i < bufferArr.length; i++) { - if (res) { - if (bufferArr[i] !== 0) { - res = false - console.info('TC_020 Success') - expect(true).assertTrue() - done() - break - } - } - } - if (res) { - console.info('TC_020 buffer is all empty') - expect(false).assertTrue() - done() - } - }) + // Called if the condition is met. + }).catch(error => { + // Called if no condition is met. + }) ``` ### readPixelsToBuffer7+ @@ -140,24 +119,6 @@ Reads image pixel map data and writes the data to an **ArrayBuffer**. This API u ```js pixelmap.readPixelsToBuffer(readBuffer, () => { - var bufferArr = new Uint8Array(readBuffer) - var res = true - for (var i = 0; i < bufferArr.length; i++) { - if (res) { - if (bufferArr[i] !== 0) { - res = false - console.info('TC_020-1 Success') - expect(true).assertTrue() - done() - break - } - } - } - if (res) { - console.info('TC_020-1 buffer is all empty') - expect(false).assertTrue() - done() - } }) ``` @@ -185,28 +146,10 @@ Reads pixel map data in an area. This API uses a promise to return the data read ```js pixelmap.readPixels(area).then((data) => { - if(data !== null){ - var bufferArr = new Uint8Array(area.pixels); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - console.info('TC_021 buffer ' + bufferArr[i]); - if(res) { - if (bufferArr[i] == 0) { - res = false; - console.info('TC_021 Success'); - expect(true).assertTrue(); - done(); - break; - } - } - } - if (res) { - console.info('TC_021 buffer is all empty'); - expect(false).assertTrue() - done(); - } - } - }) + // Called if the condition is met. + }).catch(error => { + // Called if no condition is met. + }) ``` ### readPixels7+ @@ -227,22 +170,22 @@ Reads image pixel map data in an area. This API uses a callback to return the da **Example** ```js -pixelmap.readPixels(area,(data) => { - if(data !== null) { - var bufferArr = new Uint8Array(area.pixels); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - console.info('TC_021-1 buffer ' + bufferArr[i]); - if(res) { - if(bufferArr[i] == 0) { - res = false; - console.info('TC_021-1 Success'); - expect(true).assertTrue(); - done(); - break; - } - } - } +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts, (err, pixelmap) => { + if(pixelmap == undefined){ + console.info('createPixelMap failed'); + expect(false).assertTrue(); + done(); + }else{ + const area = { pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} + pixelmap.readPixels(area, () => { + console.info('readPixels success'); + }) + } +}) ``` ### writePixels7+ @@ -257,7 +200,7 @@ Writes image pixel map data to an area. This API uses a promise to return the op | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | -------------------- | -| area | [PositionArea](#PositionArea7) | Yes | Area to which the pixel map data will be written.| +| area | [PositionArea](#positionarea7) | Yes | Area to which the pixel map data will be written.| **Return value** @@ -268,11 +211,39 @@ Writes image pixel map data to an area. This API uses a promise to return the op **Example** ```js -pixelMap.writePixels(area).then(() => { - console.log("Succeeded in writing pixels."); -}).catch((err) => { - console.error("Failed to write pixels."); -}); +const color = new ArrayBuffer(96); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts) + .then( pixelmap => { + if (pixelmap == undefined) { + console.info('createPixelMap failed'); + expect(false).assertTrue() + done(); + } + const area = { pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } + } + var bufferArr = new Uint8Array(area.pixels); + for (var i = 0; i < bufferArr.length; i++) { + bufferArr[i] = i + 1; + } + + 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 } + } + }) + }) + .catch(error => { + console.log('error: ' + error); + expect().assertFail(); + done(); + }) ``` ### writePixels7+ @@ -287,7 +258,7 @@ Writes image pixel map data to an area. This API uses a callback to return the o | Name | Type | Mandatory| Description | | --------- | ------------------------------ | ---- | ------------------------------ | -| area | [PositionArea](#PositionArea7) | Yes | Area to which the pixel map data will be written. | +| area | [PositionArea](#positionarea7) | Yes | Area to which the pixel map data will be written. | | callback: | AsyncCallback\ | Yes | Callback used to return the operation result. If the operation fails, an error message is returned.| **Example** @@ -401,19 +372,7 @@ Obtains pixel map information about this image. This API uses a callback to retu **Example** ```js -pixelmap.getImageInfo((imageInfo) => { - if (imageInfo !== null) { - console.info('TC_024-1 imageInfo is ready') - expect(imageInfo.size.height == 4).assertTrue() - expect(imageInfo.size.width == 6).assertTrue() - expect(imageInfo.pixelFormat == 1).assertTrue() - done() - } else { - console.info('TC_024-1 imageInfo is empty') - expect(false).assertTrue() - done() - } - }) +pixelmap.getImageInfo((imageInfo) => {}) ``` ### getBytesNumberPerRow7+ @@ -433,11 +392,7 @@ Obtains the number of bytes in each line of the image pixel map. **Example** ```js -pixelmap.getBytesNumberPerRow().then((num) => { - console.info('TC_025 num is ' + num) - expect(num == expectNum).assertTrue() - done() - }) +rowCount = pixelmap.getBytesNumberPerRow() ``` ### getPixelBytesNumber7+ @@ -457,11 +412,7 @@ Obtains the total number of bytes of the image pixel map. **Example** ```js -pixelmap.getPixelBytesNumber().then((num) => { - console.info('TC_026 num is ' + num) - expect(num == expectNum).assertTrue() - done() - }) +pixelBytesNumber = pixelmap.getPixelBytesNumber() ``` ### release7+ @@ -481,9 +432,8 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -pixelmap.release() - expect(true).assertTrue() - done() + pixelmap.release().then(() => { }) + .catch(error => {}) ``` ### release7+ @@ -503,11 +453,7 @@ Releases this **PixelMap** object. This API uses a callback to return the result **Example** ```js -pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 success'); - done(); - }) +pixelmap.release(()=>{ }) ``` ## image.createImageSource @@ -526,9 +472,9 @@ Creates an **ImageSource** instance based on the URI. **Return value** -| Type | Description | -| --------------------------- | --------------------------------------- | -| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **null** otherwise.| +| Type | Description | +| --------------------------- | -------------------------------------------- | +| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| **Example** @@ -552,9 +498,9 @@ Creates an **ImageSource** instance based on the file descriptor. **Return value** -| Type | Description | -| --------------------------- | --------------------------------------- | -| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **null** otherwise.| +| Type | Description | +| --------------------------- | -------------------------------------------- | +| [ImageSource](#imagesource) | Returns the **ImageSource** instance if the operation is successful; returns **undefined** otherwise.| **Example** @@ -590,20 +536,7 @@ Obtains information about an image with the specified index. This API uses a cal **Example** ```js -it('TC_046', 0, async function (done) { - const imageSourceApi = image.createImageSource('/sdcard/test.jpg'); - if (imageSourceApi == null) { - console.info('TC_046 create image source failed'); - expect(false).assertTrue(); - done(); - } else { - imageSourceApi.getImageInfo(0,(error, imageInfo) => { - console.info('TC_046 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) - } - }) +imageSourceApi.getImageInfo(0,(error, imageInfo) => {}) ``` ### getImageInfo @@ -623,11 +556,7 @@ Obtains information about this image. This API uses a callback to return the inf **Example** ```js -imageSourceApi.getImageInfo(imageInfo => { - console.info('TC_045 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) +imageSourceApi.getImageInfo(imageInfo => {}) ``` ### getImageInfo @@ -654,11 +583,8 @@ Obtains information about an image with the specified index. This API uses a pro ```js imageSourceApi.getImageInfo(0) - .then(imageInfo => { - console.info('TC_047 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); - }) + .then(imageInfo => {}) + .catch(error => {}) ``` ### getImageProperty7+ @@ -685,7 +611,9 @@ Obtains the value of a property with the specified index in this image. This API **Example** ```js -const w = imageSourceApi.getImageProperty("ImageWidth") +imageSourceApi.getImageProperty("BitsPerSample") + .then(data => {}) + .catch(error => {}) ``` ### getImageProperty7+ @@ -706,7 +634,7 @@ Obtains the value of a property with the specified index in this image. This API **Example** ```js -const w = imageSourceApi.getImageProperty("ImageWidth",w=>{}) +imageSourceApi.getImageProperty("BitsPerSample",(error,data) => {}) ``` ### getImageProperty7+ @@ -728,12 +656,12 @@ Obtains the value of a property in this image. This API uses a callback to retur **Example** ```js - imageSourceApi.getImageProperty("ImageWidth",PropertyOptions,(w)=>{}) +imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {}) ``` ### createPixelMap7+ -createPixelMap(index: number, options: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(options?: DecodingOptions): Promise\ Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. @@ -741,58 +669,46 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------------- | ---- | -------------------- | -| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| index | number | Yes | Image index. | -| AsyncCallback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------ | ---- | ---------- | +| options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| **Example** ```js -imageSourceApi.createPixelMap().then(pixelmap => { - console.info('TC_050-11 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap().then(pixelmap => {}) + .catch(error => {}) ``` ### createPixelMap7+ -createPixelMap(options: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(callback: AsyncCallback\): void -Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. +Creates a **PixelMap** object based on the default parameters. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Image **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js -let decodingOptions = { - sampleSize:1, - editable: true, - desiredSize:{ width:1, height:2}, - rotateDegrees:10, - desiredPixelFormat:1, - desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - }; - imageSourceApi.createPixelMap(0,decodingOptions, pixelmap => { - console.info('TC_050-1 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap(pixelmap => {}) ``` ### createPixelMap7+ -createPixelMap(opts: DecodingOptions, callback: AsyncCallback\): void +createPixelMap(options: DecodingOptions, callback: AsyncCallback\): void Creates a **PixelMap** object based on image decoding parameters. This API uses a callback to return the result. @@ -800,28 +716,15 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | -------------------- | -| opts | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | -| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the operation result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------- | +| options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | +| callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| **Example** ```js -let decodingOptions = { - sampleSize:1, - editable: true, - desiredSize:{ width:1, height:2}, - rotateDegrees:10, - desiredPixelFormat:1, - desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 }, - index:1 - }; - imageSourceApi.createPixelMap(decodingOptions, pixelmap => { - console.info('TC_050-1 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) +imageSourceApi.createPixelMap(decodingOptions, pixelmap => {}) ``` ### release @@ -841,12 +744,7 @@ Releases this **ImageSource** instance. This API uses a callback to return the r **Example** ```js -imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - expect(true).assertTrue(); - done(); - }) - } +imageSourceApi.release(() => {}) ``` ### release @@ -866,11 +764,7 @@ Releases this **ImageSource** instance. This API uses a promise to return the re **Example** ```js - imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - expect(true).assertTrue(); - done(); - }) +imageSourceApi.release().then(()=>{ }).catch(error => {}) ``` ## image.createImagePacker @@ -883,9 +777,9 @@ Creates an **ImagePacker** instance. **Return value** -| Type | Description | -| ----------- | ---------------------- | -| ImagePacker | **ImagePacker** instance created.| +| Type | Description | +| --------------------------- | --------------------- | +| [ImagePacker](#imagepacker) | **ImagePacker** instance created.| **Example** @@ -905,7 +799,60 @@ Provide APIs to pack images. Before calling any API in **ImagePacker**, you must ### packing -packing(source: ImageSource, option: PackingOption, callback: AsyncCallback>): void +packing(source: ImageSource, option: PackingOption, callback: AsyncCallback>): void + +Packs an image. This API uses a callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ---------------------------------- | +| source | [ImageSource](#imagesource) | Yes | Image to pack. | +| option | [PackingOption](#packingoption) | Yes | Option for image packing. | +| callback | AsyncCallback> | Yes | Callback used to return the packed data.| + +**Example** + +```js +let packOpts = { format:["image/jpeg"], quality:98 } +imagePackerApi.packing(imageSourceApi, packOpts, data => {}) +``` + +### packing + +packing(source: ImageSource, option: PackingOption): Promise> + +Packs an image. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| source | [ImageSource](#imagesource) | Yes | Image to pack.| +| option | [PackingOption](#packingoption) | Yes | Option for image packing.| + +**Return value** + +| Type | Description | +| :--------------------------- | :-------------------------------------------- | +| Promise> | Promise used to return the packed data.| + +**Example** + +```js +let packOpts = { format:["image/jpeg"], quality:98 } +imagePackerApi.packing(imageSourceApi, packOpts) + .then( data => { }) + .catch(error => {}) +``` + +### packing + +packing(source: PixelMap, option: PackingOption, callback: AsyncCallback\): void Packs an image. This API uses a callback to return the result. @@ -915,24 +862,20 @@ Packs an image. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ---------------------------------- | -| source | [ImageSource](#imagesource) | Yes | Image to pack. | +| source | [PixelMap](#pixelmap) | Yes | **PixelMap** object to pack. | | option | [PackingOption](#packingoption) | Yes | Option for image packing. | -| callback | AsyncCallback> | Yes | Callback used to return the packed data.| +| callback | AsyncCallback\ | Yes | Callback used to return the packed data.| **Example** ```js let packOpts = { format:["image/jpeg"], quality:98 } - imagePackerApi.packing(imageSourceApi, packOpts, data => { - console.info('TC_062-1 finished'); - expect(data !== null).assertTrue(); - done(); - }) +imagePackerApi.packing(pixelMapApi, packOpts, data => {}) ``` ### packing -packing(source: ImageSource, option: PackingOption): Promise> +packing(source: PixelMap, option: PackingOption): Promise> Packs an image. This API uses a promise to return the result. @@ -942,25 +885,22 @@ Packs an image. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | -------------- | -| source | [ImageSource](#imagesource) | Yes | Image to pack.| +| source | [PixelMap](#pixelmap) | Yes | **PixelMap** object to pack.| | option | [PackingOption](#packingoption) | Yes | Option for image packing.| **Return value** -| Type | Description | -| :---------------------- | :-------------------------------------------- | -| Promise> | Promise used to return the packed data.| +| Type | Description | +| :--------------------------- | :-------------------------------------------- | +| Promise> | Promise used to return the packed data.| **Example** ```js let packOpts = { format:["image/jpeg"], quality:98 } - imagePackerApi.packing(imageSourceApi, packOpts) - .then( data => { - console.info('TC_062 finished'); - expect(data !== null).assertTrue(); - done(); - }) +imagePackerApi.packing(pixelMapApi, packOpts) + .then( data => { }) + .catch(error => {}) ``` ### release @@ -980,10 +920,7 @@ Releases this **ImagePacker** instance. This API uses a callback to return the r **Example** ```js -imagePackerApi.release(()=>{ - console.info('TC_063-1 release'); - expect(true).assertTrue(); - done(); +imagePackerApi.release(()=>{}) ``` ### release @@ -1003,10 +940,8 @@ Releases this **ImagePacker** instance. This API uses a promise to return the re **Example** ```js -imagePackerApi.release(); - console.info('TC_063 release'); - expect(true).assertTrue(); - done(); + imagePackerApi.release().then(()=>{ + }).catch((error)=>{}) ``` ## PositionArea7+ @@ -1015,14 +950,14 @@ Describes area information in an image. **System capability**: SystemCapability.Multimedia.Image -| Name | Type | Readable| Writable| Description | -| ------ | ------------------ | ---- | ---- | -------------------- | -| pixels | ArrayBuffer | Yes | No | Pixels of the image. | -| offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes to read. | -| region | [Region](#region8) | Yes | No | Region to read or write.| +| Name | Type | Readable| Writable| Description | +| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | +| 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. | +| region | [Region](#region8) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| -## **ImageInfo** +## ImageInfo Describes image information. @@ -1055,40 +990,14 @@ Enumerates pixel map formats. | RGBA_8888 | 3 | RGBA_8888.| | RGB_565 | 2 | RGB_565. | -## AlphaType8+ - -Enumerates alpha types. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| -------- | ------ | ----------------------- | -| UNKNOWN | 0 | Unknown alpha type. | -| OPAQUE | 1 | There is no alpha or the image is fully transparent.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | - -## ScaleMode8+ - -Enumerates scale modes. - -**System capability**: SystemCapability.Multimedia.Image - -| Name | Default Value| Description | -| --------------- | ------ | -------------------------------------------------- | -| CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| -| FIT_TARGET_SIZE | 2 | Reduces the image size to the dimensions of the target. | - ## InitializationOptions8+ **System capability**: SystemCapability.Multimedia.Image | Name | Type | Readable| Writable| Description | | ----------- | ---------------------------------- | ---- | ---- | -------------- | -| alphaType | [AlphaType](#alphatype8) | Yes | Yes | Alpha type. | | editable | boolean | Yes | Yes | Whether the image is editable. | | pixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format. | -| scaleMode | [ScaleMode](#scalemode8) | Yes | Yes | Scale mode. | | size | [Size](#size) | Yes | Yes | Image size.| ## DecodingOptions7+ @@ -1100,22 +1009,22 @@ Describes the decoding options. | Name | Type | Readable| Writable| Description | | ------------------ | ---------------------------------- | ---- | ---- | ---------------- | | sampleSize | number | Yes | Yes | Thumbnail sampling size.| -| rotateDegrees | number | Yes | Yes | Rotation angle. | +| rotate | number | Yes | Yes | Rotation angle. | | editable | boolean | Yes | Yes | Whether the image is editable. | | desiredSize | [Size](#size) | Yes | Yes | Expected output size. | -| desiredRegion | [Region](#region8) | Yes | Yes | Region to decode. | +| desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | numer | Yes | Yes | Index of the image to decode. | -## Region8+ +## Region7+ Describes region information. **System capability**: SystemCapability.Multimedia.Image -| Name| Type | Readable| Writable| Description | -| ---- | ------------- | ---- | ---- | ---------- | -| size | [Size](#size) | Yes | Yes | Region size.| +| Name| Type | Readable| Writable| Description | +| ---- | ------------- | ---- | ---- | ------------ | +| size | [Size](#size) | Yes | Yes | Region size. | | x | number | Yes | Yes | X coordinate of the region.| | y | number | Yes | Yes | Y coordinate of the region.| @@ -1145,6 +1054,8 @@ Describes image properties. Describes the exchangeable image file format (Exif) information of an image. +**System capability**: SystemCapability.Multimedia.Image + | Name | Default Value | Description | | ----------------- | ----------------- | -------------------- | | BITS_PER_SAMPLE | "BitsPerSample" | Number of bytes in each pixel. | diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index 0913e6e3ce52acbcf57959768599dde89fed4d87..02b81d4a512f7e08ea27866fc43dc0bc853f4521 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -20,90 +20,187 @@ import inputDevice from '@ohos.multimodalInput.inputDevice'; getDeviceIds(callback: AsyncCallback<Array<number>>): void -Obtains the IDs of all input devices. This method uses an asynchronous callback to return the result. +Obtains the IDs of all input devices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - **Parameters** - | Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result. | +**Parameters** - **Example** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----- | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the result.| + + +**Example** + +``` +export default { + data: { + deviceIds: Array, + }, + callback: function(ids) { + this.deviceIds = ids; + }, + testGetDeviceIds: function () { + console.info("InputDeviceJsTest---start---testGetDeviceIds"); + inputDevice.getDeviceIds(this.callback); + console.info("InputDeviceJsTest---end---testGetDeviceIds"); + } +} +``` + +## inputDevice.getDeviceIds + +function getDeviceIds(): Promise> + +Obtains the IDs of all input devices. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Return value** + +| Name | Description | +| ---------------------- | ------------------ | +| Promise> | Promise used to return the result.| + +**Example** ``` -data: { - deviceIds: Array, -}, -callback: function(ids) { - this.deviceIds = ids; -}, -testGetDeviceIds: function () { - console.info("InputDeviceJsTest---start---testGetDeviceIds"); - inputDevice.getDeviceIds(this.callback); - console.info("InputDeviceJsTest---end---testGetDeviceIds"); +export default { + testGetDeviceIds: function () { + console.info("InputDeviceJsTest---start---testGetDeviceIds"); + let promise = inputDevice.getDeviceIds(); + promise.then((data)=> { + console.info('GetDeviceIds successed, Data: ' + JSON.stringify(data)) + }).catch((err)=>{ + console.error('Failed GetDeviceIds. Cause: ' + JSON.stringify(err)); + }); + } } ``` + + + ## inputDevice.getDevice getDevice(deviceId: number, callback: AsyncCallback<InputDeviceData>): void -Obtains the information about an input device. This method uses an asynchronous callback to return the result. +Obtains the information about an input device. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - **Parameters** - | Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| deviceId | number | Yes | ID of the input device whose information is to be obtained. | -| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | Yes | Callback used to return the **InputDeviceData** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------- | +| deviceId | number | Yes | ID of the input device whose information is to be obtained. | +| callback | AsyncCallback<[InputDeviceData](#inputdevicedata)> | Yes | Callback used to return the **InputDeviceData** object.| - **Example** +**Example** ``` -InputDeviceData { - deviceId : 0, - name : "NA", - sources : Array, - axisRanges : Array, -}, -callback: function(deviceData) { - this.InputDeviceData = deviceData; -}, -testGetDevice: function () { - // The example is used to obtain the information about the device whose ID is 1. - console.info("InputDeviceJsTest---start---testGetDevice"); - inputDevice.getDevice(1, this.callback); - console.info("InputDeviceJsTest---end---testGetDevice"); +export default { + InputDeviceData: { + deviceId : 0, + name : "NA", + sources : Array, + axisRanges : Array, + }, + callback: function(deviceData) { + this.InputDeviceData = deviceData; + }, + testGetDevice: function () { + // The example is used to obtain the information about the device whose ID is 1. + console.info("InputDeviceJsTest---start---testGetDevice"); + inputDevice.getDevice(1, this.callback); + console.info("InputDeviceJsTest---end---testGetDevice"); + } } ``` +## inputDevice.getDevice + +function getDevice(deviceId: number): Promise + +Obtains the information about an input device. This API uses a promise to return the result. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +**Return value** + +| Name | Description | +| ------------------------ | ------------------ | +| Promise | Promise used to return the result.| + +**Example** + +``` +export default { + InputDeviceData: { + deviceId : 0, + name : "NA", + sources : Array, + axisRanges : Array, + }, + testGetDevice: function () { + // The example is used to obtain the information about the device whose ID is 1. + console.info("InputDeviceJsTest---start---testGetDevice"); + let promise = inputDevice.getDevice(1); + promise.then((data)=> { + console.info('GetDeviceId successed, Data: ' + JSON.stringify(data)) + }).catch((err)=>{ + console.error('Failed GetDeviceId. Cause: ' + JSON.stringify(err)); + }); + } +} +``` + + ## InputDeviceData Defines the information about an input device. - **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - | Name | Type | Description | -| -------- | -------- | -------- | -| id | number | Unique identifier of an input device. If the same physical device is repeatedly inserted and removed, its ID changes. | -| name | string | Name of the input device. | -| sources | Array<[SourceType](#sourcetype)> | Source types of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad. | +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +| Name | Type | Description | +| ------- | -------------------------------------- | ---------------------------------------- | +| id | number | Unique identifier of an input device. If the same physical device is repeatedly inserted and removed, its ID changes. | +| name | string | Name of the input device. | +| sources | Array<[SourceType](#sourcetype)> | Source types of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| + +## AxisType + +Axis type. This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. + +## AxisRange + +Defines the axis information of an input device. + +**System capability**: SystemCapability.MultimodalInput.Input.InputDevice + +| Name | Type | Description | +| ------ | ------------------------- | -------- | +| source | [SourceType](#sourcetype) | Input source type of the axis.| +| axis | [AxisType](axistype) | Axis type. | +| max | number | Maximum value reported by the axis. | +| min | number | Minimum value reported by the axis. | + ## SourceType -Enumerates the input source types. +Enumerates the input source types. For example, if a mouse reports an x-axis event, the source of the x-axis is the mouse. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice - | Name | Type | Description | -| -------- | -------- | -------- | -| keyboard | string | The input device is a keyboard. | -| touchscreen | string | The input device is a touchscreen. | -| mouse | string | The input device is a mouse. | -| trackball | string | The input device is a trackball. | -| touchpad | string | The input device is a touchpad. | -| joystick | string | The input device is a joystick. | +| Name | Type | Description | +| ----------- | ------ | ----------- | +| keyboard | string | The input device is a keyboard. | +| touchscreen | string | The input device is a touchscreen.| +| mouse | string | The input device is a mouse. | +| trackball | string | The input device is a trackball.| +| touchpad | string | The input device is a touchpad.| +| joystick | string | The input device is a joystick.| diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md new file mode 100644 index 0000000000000000000000000000000000000000..ed3942bb5920474b06ae829521a77bf483d1cac0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -0,0 +1,57 @@ +# Input Event Client + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs of this module are system APIs and cannot be called by third-party applications. + + +## Modules to Import + + +``` +import inputEventClient from '@ohos.multimodalInput.inputEventClient'; +``` + + +## inputEventClient.injectEvent + +injectEvent({KeyEvent: KeyEvent}): void + +Injects a key. + +**System capability**: SystemCapability.MultimodalInput.Input.InputSimulator + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| KeyEvent | [KeyEvent](#keyevent) | Yes| Information about the key to inject.| + +**Example** + +``` +let keyEvent = { + isPressed: true, + keyCode: 2, + keyDownDuration: 0, + isIntercepted: false +} +res = inputEventClient.injectEvent({KeyEvent: keyEvent}); +``` + + +## KeyEvent + +Defines the information about the key to inject. + +**System capability**: SystemCapability.MultimodalInput.Input.InputSimulator + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| isPressed | boolean | Yes| Whether the key is pressed.| +| keyCode | Number | Yes| Key code.| +| keyDownDuration | boolean | Yes| Duration for which the key is pressed.| +| isIntercepted | Number | Yes| Whether the key can be intercepted.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md new file mode 100644 index 0000000000000000000000000000000000000000..6e5ef326d3bc6362f59ce7b6fffa2ea0214e94f4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -0,0 +1,208 @@ +# Input Method Framework + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + + +## Modules to Import + +``` +import inputMethod from '@ohos.inputMethod'; +``` + +## inputMethod8+ + +Provides the constants. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| + + +## InputMethodProperty8+ + +Describes the input method application attributes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| packageName | string | Yes| No| Package name.| +| methodId | string | Yes| No| Ability name.| + +## inputMethod.getInputMethodController + +getInputMethodController(): InputMethodController + +Obtains an [InputMethodController](#InputMethodController) instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type| Description| + | -------- | -------- | + | [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.| + +- Example + ``` + var InputMethodController = inputMethod.getInputMethodController(); + ``` +## inputMethod.getInputMethodSetting8+ + +getInputMethodSetting(): InputMethodSetting + +Obtains an [InputMethodSetting](#InputMethodSetting) instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | ----------------------------------------- | ---------------------------- | + | [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.| + + +- Example + ``` + var InputMethodSetting = inputMethod.getInputMethodSetting(); + ``` + +## InputMethodController + +In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. + +### stopInput + +stopInput(callback: AsyncCallback<boolean>): void + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the keyboard is successfully hidden.| + +- Example + +``` + InputMethodController.stopInput((error)=>{ + console.info('stopInput'); + }); +``` + +### stopInput + +stopInput(): Promise<boolean> + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| + +- Example + + +``` + var isSuccess = InputMethodController.stopInput(); + console.info('stopInput isSuccess = ' + isSuccess); +``` + +## InputMethodSetting8+ + +In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. + +### listInputMethod + +listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>): void + +Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------------------- | ---- | ---------------------- | + | callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.| + +- Example + ``` + InputMethodSetting.listInputMethod((properties)=>{ + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + }); + ``` + +### listInputMethod + +listInputMethod(): Promise<Array<InputMethodProperty>> + +Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + | Type | Description | + | ----------------------------------------------------------- | ---------------------- | + | Promise> | Promise used to return the list of installed input methods.| + +- Example + ``` + var properties = InputMethodSetting.listInputMethod(); + for (var i = 0;i < properties.length; i++) { + var property = properties[i]; + console.info(property.packageName + "/" + property.methodId); + } + ``` + +### displayOptionalInputMethod + +displayOptionalInputMethod(callback: AsyncCallback<void>): void + +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +- Example + ``` + InputMethodSetting.displayOptionalInputMethod(()=>{ + console.info('displayOptionalInputMethod is called'); + }); + ``` + +### displayOptionalInputMethod + +displayOptionalInputMethod(): Promise<void> + +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. + + **System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + + - Example + ``` + InputMethodSetting.displayOptionalInputMethod(); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md new file mode 100644 index 0000000000000000000000000000000000000000..ba43211b4ae577be55718a6d32f50a565b2093b5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -0,0 +1,756 @@ +# Input Method Engine + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 + +``` +import inputMethodEngine from '@ohos.inputMethodEngine'; +``` + +## inputMethodEngine + +Defines constant values. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ENTER_KEY_TYPE_UNSPECIFIED | number | Yes| No| No function is specified for the Enter key.| +| ENTER_KEY_TYPE_GO | number | Yes| No| The Enter key takes the user to the target.| +| ENTER_KEY_TYPE_SEARCH | number | Yes| No| The Enter key takes the user to the results of their searching.| +| ENTER_KEY_TYPE_SEND | number | Yes| No| The Enter key sends the text to its target.| +| ENTER_KEY_TYPE_NEXT | number | Yes| No| The Enter key takes the user to the next field.| +| ENTER_KEY_TYPE_DONE | number | Yes| No| The Enter key takes the user to the next line.| +| ENTER_KEY_TYPE_PREVIOUS | number | Yes| No| The Enter key takes the user to the previous field.| +| PATTERN_NULL | number | Yes| No| Any type of edit box.| +| PATTERN_TEXT | number | Yes| No| Text edit box.| +| PATTERN_NUMBER | number | Yes| No| Number edit box.| +| PATTERN_PHONE | number | Yes| No| Phone number edit box.| +| PATTERN_DATETIME | number | Yes| No| Date edit box.| +| PATTERN_EMAIL | number | Yes| No| Email edit box.| +| PATTERN_URI | number | Yes| No| URI edit box.| +| PATTERN_PASSWORD | number | Yes| No| Password edit box.| +| OPTION_ASCII | number | Yes| No| ASCII values are allowed.| +| OPTION_NONE | number | Yes| No| No input attribute is specified.| +| OPTION_AUTO_CAP_CHARACTERS | number | Yes| No| Characters are allowed.| +| OPTION_AUTO_CAP_SENTENCES | number | Yes| No| Sentences are allowed.| +| OPTION_AUTO_WORDS | number | Yes| No| Words are allowed.| +| OPTION_MULTI_LINE | number | Yes| No| Multiple lines are allowed.| +| OPTION_NO_FULLSCREEN | number | Yes| No| Half-screen style.| +| FLAG_SELECTING | number | Yes| No| The edit box is being selected.| +| FLAG_SINGLE_LINE | number | Yes| No| The edit box allows only single-line input.| +| DISPLAY_MODE_PART | number | Yes| No| The edit box is displayed in half-screen mode.| +| DISPLAY_MODE_FULL | number | Yes| No| The edit box is displayed in full screen.| + +## inputMethodEngine.getInputMethodEngine + +getInputMethodEngine(): InputMethodEngine + +Obtains an **InputMethodEngine** instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | --------------------------------------- | ------------ | + | [InputMethodEngine](#InputMethodEngine) | **InputMethodEngine** instance obtained.| + +- Example + + ``` + var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); + ``` + +## inputMethodEngine.createKeyboardDelegate + +createKeyboardDelegate(): KeyboardDelegate + +Obtains a **KeyboardDelegate** instance. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description | + | ------------------------------------- | ---------------- | + | [KeyboardDelegate](#KeyboardDelegate) | **KeyboardDelegate** instance obtained.| + +- Example + + ``` + var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); + ``` + +## InputMethodEngine + +In the following API examples, you must first use [getInputMethodEngine](#getInputMethodEngine) to obtain an **InputMethodEngine** instance, and then call the APIs using the obtained instance. + +### on('inputStart') + +on(type: 'inputStart', callback: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void + +Listens for the input method binding event. This API uses a callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| +| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | Yes| Callback used to return the result.| + +- Example + + ``` + InputMethodEngine.on('inputStart', (kbController, textInputClient) => { + KeyboardController = kbController; + TextInputClient = textInputClient; + }); + ``` + +### off('inputStart') + +off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void + +Cancels listening for the input method binding event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| + | callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.| + + + +- Example + + ``` + InputMethodEngine.off('inputStart'); + ``` + +### on('keyboardShow'|'keyboardHide') + +on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void + +Listens for an input method event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| + | callback | void | No | Callback used to return the result. | + +- Example + + ``` + InputMethodEngine.on('keyboardShow', (err) => { + console.info('keyboardShow'); + }); + ``` + +### off('keyboardShow'|'keyboardHide') + +off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void + +Cancels listening for an input method event. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| + | callback | void | No | Callback used to return the result. | + +- Example + + ``` + InputMethodEngine.off('keyboardShow'); + ``` + + +## KeyboardDelegate + +In the following API examples, you must first use [createKeyboardDelegate](#createKeyboardDelegate) to obtain a **KeyboardDelegate** instance, and then call the APIs using the obtained instance. + +### on('keyDown'|'keyUp') + +on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void + +Listens for a hard keyboard even. This API uses a callback to return the key information. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| + | callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| + + + +- Example + + ``` + KeyboardDelegate.on('keyDown', (event) => { + console.info('keyDown'); + }); + ``` + +### off('keyDown'|'keyUp') + +off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void + +Cancels listening for a hard keyboard even. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | --------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| + | callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | + +- Example + + ``` + KeyboardDelegate.off('keyDown'); + ``` + +### on('cursorContextChange') + +on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void + +Listens for cursor context changes. This API uses a callback to return the cursor information. + + **System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| + | callback | number | Yes | Callback used to return the cursor information. | + + + + - Example + + ``` + KeyboardDelegate.on('cursorContextChange', (x, y, height) => { + console.info('cursorContextChange'); + }); + ``` + +### off('cursorContextChange') + +off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void + +Cancels listening for cursor context changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| + | callback | number | No| Callback used to return the cursor information.| + + + - Example + + ``` + KeyboardDelegate.off('cursorContextChange'); + ``` +### on('selectionChange') + +on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void + +Listens for text selection changes. This API uses a callback to return the text selection information. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| + | callback | number | Yes | Callback used to return the text selection information. | + + - Example + + ``` + KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { + console.info('selectionChange'); + }); + ``` + +### off('selectionChange') + +off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void + +Cancels listening for text selection changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| + | callback | number | No| Callback used to return the text selection information.| + + - Example + + ``` + KeyboardDelegate.off('selectionChange'); + ``` + + +### on('textChange') + +on(type: 'textChange', callback: (text: string) => void): void + +Listens for text changes. This API uses a callback to return the current text content. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| + | callback | string | Yes| Callback used to return the current text content.| + + - Example + + ``` + KeyboardDelegate.on('textChange', (text) => { + console.info('textChange'); + }); + ``` + +### off('textChange') + +off(type: 'textChange', callback?: (text: string) => void): void + +Cancels listening for text changes. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name | Type | Mandatory| Description | + | -------- | -------------------- | ---- | ------------------------ | + | type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| + | callback | string | No| Callback used to return the current text content.| + + - Example + + ``` + KeyboardDelegate.off('textChange'); + ``` + +## KeyboardController + +In the following API examples, you must first use [inputStart](#inputStart) to obtain a **KeyboardController** instance, and then call the APIs using the obtained instance. + +### hideKeyboard + +hideKeyboard(callback: AsyncCallback<void>): void + +Hides the keyboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name | Type | Mandatory| Description | + | -------- | ---------------------- | ---- | -------- | + | callback | AsyncCallback<void> | No | Callback used to return the result.| + +- Example + + +``` + KeyboardController.hideKeyboard(()=>{ + }); +``` + +### hideKeyboard + +hideKeyboard(): Promise<void> + +Hides the keyboard. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + + | Type | Description: | + | ---------------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + + +``` + KeyboardController.hideKeyboard(); +``` + +## TextInputClient + +In the following API examples, you must first use [inputStart](#inputStart) to obtain a **TextInputClient** instance, and then call the APIs using the obtained instance. + +### getForward + +getForward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<string> | Yes| Text returned.| + +- Example + ``` + TextInputClient.getForward(5,(text) =>{ + console.info("text = " + text); + }); + ``` + +### getForward + +getForward(length:number): Promise<string> + +Obtains the specific-length text before the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<string> | Text returned. | + +- Example + ``` + var text = TextInputClient.getForward(5); + console.info("text = " + text); + ``` + +### getBackward + +getBackward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<string> | Yes| Text returned.| + +- Example + ``` + TextInputClient.getBackward(5,(text)=>{ + console.info("text = " + text); + }); + ``` + +### getBackward + +getBackward(length:number): Promise<string> + +Obtains the specific-length text after the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<string> | Text returned. | + +- Example + ``` + var text = TextInputClient.getBackward(5); + console.info("text = " + text); + ``` + +### deleteForward + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + +- Example + ``` + TextInputClient.deleteForward(5,(isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` +### deleteForward + +deleteForward(length:number): Promise<boolean> + +Deletes the fixed-length text before the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + + - Example + ``` + var isSuccess = TextInputClient.deleteForward(5); + console.info("isSuccess = " + isSuccess); + ``` + +### deleteBackward + +deleteBackward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + + - Example + ``` + TextInputClient.deleteBackward(5, (isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### deleteBackward + +deleteBackward(length:number): Promise<boolean> + +Deletes the fixed-length text after the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | length | number | Yes| Text length.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.deleteBackward(5); + console.info("isSuccess = " + isSuccess); + ``` +### sendKeyFunction + +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void + +Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + + - Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | action | number | Yes| Edit box attribute.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + + - Example + ``` + TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### sendKeyFunction + +sendKeyFunction(action:number): Promise<boolean> + +Sets the Enter key to send the text to its target. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | action | number | Yes| Edit box attribute.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); + console.info("isSuccess = " + isSuccess); + ``` + +### insertText + +insertText(text:string, callback: AsyncCallback<boolean>): void + +Inserts text. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | text | string | Yes| Text to insert.| + | callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| + +- Example + ``` + TextInputClient.insertText("test", (isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` + +### insertText + +insertText(text:string): Promise<boolean> + +Inserts text. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | text | string | Yes| Text to insert.| + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<boolean> | Returns whether the operation is successful. | + +- Example + + ``` + var isSuccess = TextInputClient.insertText("test"); + console.info("isSuccess = " + isSuccess); + ``` + +### getEditorAttribute + +getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void + +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Parameters + | Name | Type | Mandatory | Description | + | ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | callback | AsyncCallback<[EditorAttribute](#EditorAttribute)> | Yes| Attribute of the edit box. | + +- Example + ``` + TextInputClient.getEditorAttribute((EditorAttribute)=>{ + }); + ``` + +### getEditorAttribute + +getEditorAttribute(): Promise<EditorAttribute> + +Obtains the attribute of the edit box. This API uses a promise to return the result. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +- Return value + | Type | Description | + | ------------------------------- | ------------------------------------------------------------ | + | Promise<[EditorAttribute](#EditorAttribute)> | Returns the attribute of the edit box. | + +- Example + ``` + var EditorAttribute = TextInputClient.getEditorAttribute(); + ``` + +## EditorAttribute + +Describes the attribute of the edit box. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name | Type| Readable| Writable| Description | +| ------------ | -------- | ---- | ---- | ------------------ | +| enterKeyType | number | Yes | No | Function attribute of the edit box.| +| inputPattern | number | Yes | No | Text attribute of the edit box.| + +## KeyEvent + +Describes the attribute of a key. + +**System capability**: SystemCapability.Miscservices.InputMethodFramework + +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ------------ | +| keyCode | number | Yes | No | Key value.| +| keyAction | number | Yes | No | Key status.| diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index b5cee97142e6e57dc15a967f0e99eea21eb05224..2bf1b68fd1699451c938e762a86691b7433a3553 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > - The APIs of this module are system APIs and cannot be called by third-party applications. @@ -31,30 +31,32 @@ Starts listening for global input events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** - | Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the input event. Currently, only **touch** events are supported. | -| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| type | string | Yes | Type of the input event. Currently, only **touch** events are supported.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | **Example** ``` -callback: function (value) { - if (checkEvent(value)) { +export default { + callback: function (value) { + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOn: function () { + console.info("InputMonitorJsTest---start---testOn"); + inputMonitor.on( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOn"); } -}, -testOn: function () { - console.info("InputMonitorJsTest---start---testOn"); - inputMonitor.on( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOn"); } ``` @@ -70,31 +72,33 @@ Stops listening for global input events. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** - | Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the input event. Currently, only **touch** events are supported. | -| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| type | string | Yes | Type of the input event. Currently, only **touch** events are supported.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | **Example** ``` -callback: function (value) { - if (checkEvent(value)) { +export default { + callback: function (value) { + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOff: function () { + console.info("InputMonitorJsTest---start---testOff"); + inputMonitor.off( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOff"); } -}, -testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); -} + } ``` @@ -105,38 +109,40 @@ Represents the class of the callback used to return the touch event. The value * ### (touchEvent: TouchEvent): Boolean -Represents the callback used to return the touch event. You need to define the name of the callback function in the correct format. Ensure that the input parameter is of the **TouchEvent** type, and the return value is of the **Boolean** type. +Represents the callback used to return the touch event. You need to define the name of the callback function in the correct format. Ensure that the input parameter is of the TouchEvent type, and the return value is of the Boolean type. **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** -| Parameter | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event.| **Return value** - | Type | Description | -| -------- | -------- | -| Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite. | +| Type | Description | +| ------- | -------------------------------------- | +| Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite.| **Example** ``` -callback: function (value) {// Implementation of the (touchEvent:TouchEvent): Boolean API. - if (checkEvent(value)) { +export default { + callback: function (value) { // Implementation of the (touchEvent:TouchEvent): Boolean API. + if (checkEvent(value)) { // The event meets the service requirement and is consumed. - return true; - } else { + return true; + } else { // The event does not meet the service requirement and is not consumed. - return false; + return false; + } + }, + testOff: function () { + console.info("InputMonitorJsTest---start---testOff"); + inputMonitor.off( + "touch", + this.callback + ); + console.info("InputMonitorJsTest---end---testOff"); } -}, -testOff: function () { - console.info("InputMonitorJsTest---start---testOff"); - inputMonitor.off( - "touch", - this.callback - ); - console.info("InputMonitorJsTest---end---testOff"); } ``` diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 8843ab1880e04594ebe4946acb4246fafa914eed..433672bb7d878d8c9bad142144a6eff7d38520b3 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,8 +1,8 @@ # Internationalization – intl > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> - The 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. +> > - This module contains standard i18n APIs, which are defined in ECMA 402. @@ -20,18 +20,18 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| language | string | Yes| No| Language associated with the locale, for example, **zh**.| -| script | string | Yes| No| Script type of the language, for example, **Hans**.| -| region | string | Yes| No| Region associated with the locale, for example, **CN**.| -| baseName | string | Yes| No| Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**.| -| caseFirst | string | Yes| No| Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes| No| Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes| No| Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes| No| Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| -| numberingSystem | string | Yes| No| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| numeric | boolean | Yes| No| Whether to apply special collation rules for numeric characters.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| language | string | Yes | No | Language associated with the locale, for example, **zh**. | +| script | string | Yes | No | Script type of the language, for example, **Hans**. | +| region | string | Yes | No | Region associated with the locale, for example, **CN**. | +| baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | +| caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | ### constructor8+ @@ -42,7 +42,7 @@ Creates a Locale object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var locale = new Intl.Locale(); ``` @@ -56,13 +56,13 @@ Creates a Locale object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string | Yes| A string containing locale information, including the language, optional script, and region.| - | options | LocaleOptions | No| Options for creating the **Locale** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------- | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| +| options | LocaleOptions | No | Options for creating the **Locale** object. | -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); ``` @@ -76,12 +76,12 @@ Converts locale information to a string. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | string | String containing locale information.| +**Return Value** +| Type | Description | +| ------ | ----------- | +| string | String containing locale information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.toString(); @@ -96,12 +96,12 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [Locale](#locale) | **Locale** object with the maximized information.| +**Return Value** +| Type | Description | +| ----------------- | ---------- | +| [Locale](#locale) | **Locale** object with the maximized information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.maximize(); @@ -116,12 +116,12 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [Locale](#locale) | **Locale** object with the minimized information.| +**Return Value** +| Type | Description | +| ----------------- | ---------- | +| [Locale](#locale) | **Locale** object with the minimized information.| -- Example +**Example** ``` var locale = new Intl.Locale("zh-CN"); locale.minimize(); @@ -134,14 +134,14 @@ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| calendar | string | Yes| Yes| Calendar for the locale. The calue can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes| Yes| Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes| Yes| Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| numeric | boolean | Yes| Yes| Whether to use the 12-hour clock.| -| caseFirst | string | Yes| Yes| Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| calendar | string | Yes | Yes | Calendar for the locale. The calue can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | +| caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| ## DateTimeFormat @@ -155,7 +155,7 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat(); ``` @@ -163,25 +163,25 @@ Creates a **DateTimeOptions** object for the specified locale. ### constructor -constructor(locale: string | Array, options?: DateTimeOptions) +constructor(locale: string | Array<string>, options?: DateTimeOptions) Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| - | options | [DateTimeOptions](#datetimeoptions) | No| Options for creating a **DateTimeFormat** object.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options | [DateTimeOptions](#datetimeoptions) | No | Options for creating a **DateTimeFormat** object. | -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` -- Example +**Example** ``` var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -195,17 +195,17 @@ Formats the specified date and time. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | date | Date | Yes| Date and time to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ---- | ---- | ------- | +| date | Date | Yes | Date and time to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | A string containing the formatted date and time.| +**Return Value** +| Type | Description | +| ------ | ------------ | +| string | A string containing the formatted date and time.| -- Example +**Example** ``` var date = new Date(2021, 11, 17, 3, 24, 0); var datefmt = new Intl.DateTimeFormat("en-GB"); @@ -221,18 +221,18 @@ Formats the specified date range. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | startDate | Date | Yes| Start date and time to be formatted.| - | endDate | Date | Yes| End date and time to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ---- | ---- | -------- | +| startDate | Date | Yes | Start date and time to be formatted.| +| endDate | Date | Yes | End date and time to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | A string containing the formatted date and time range.| +**Return Value** +| Type | Description | +| ------ | -------------- | +| string | A string containing the formatted date and time range.| -- Example +**Example** ``` var startDate = new Date(2021, 11, 17, 3, 24, 0); var endDate = new Date(2021, 11, 18, 3, 24, 0); @@ -249,12 +249,12 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| +**Return Value** +| Type | Description | +| ----------------------------------- | ----------------------------- | +| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.| -- Example +**Example** ``` var datefmt = new Intl.DateTimeFormat("en-GB"); datefmt.resolvedOptions(); @@ -267,27 +267,27 @@ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| No| Locale, for example, **zh-Hans-CN**.| -| dateStyle | string | Yes| Yes| Date display format. The value can be **long**, **short**, **medium**, or **full**.| -| timeStyle | string | Yes| Yes| Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes| Yes| Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| -| timeZone | string | Yes| Yes| Time zone represented by a valid IANA time zone ID.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| hour12 | boolean | Yes| Yes| Whether to use the 12-hour clock.| -| weekday | string | Yes| Yes| Workday display format. The value can be **long**, **short**, or **narrow**.| -| era | string | Yes| Yes| Era display format. The value can be **long**, **short**, or **narrow**.| -| year | string | Yes| Yes| Year display format. The value can be **numeric** or **2-digit**. | -| month | string | Yes| Yes| Month display format. The value can be any of the following: **numeric**, **2-digit**, **long**, **short**, **narrow**.| -| day | string | Yes| Yes| Day display format. The value can be **numeric** or **2-digit**.| -| hour | string | Yes| Yes| Hour display format. The value can be **numeric** or **2-digit**.| -| minute | string | Yes| Yes| Minute display format. The value can be **numeric** or **2-digit**.| -| second | string | Yes| Yes| Seconds display format. The value can be **numeric** or **2-digit**.| -| timeZoneName | string | Yes| Yes| Localized representation of a time zone name.| -| dayPeriod | string | Yes| Yes| Time period display format. The value can be **long**, **short**, or **narrow**.| -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| formatMatcher | string | Yes| Yes| Format matching algorithm. The value can be **basic** or **best fit**.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------- | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | +| dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| +| timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | +| weekday | string | Yes | Yes | Workday display format. The value can be **long**, **short**, or **narrow**.| +| era | string | Yes | Yes | Era display format. The value can be **long**, **short**, or **narrow**.| +| year | string | Yes | Yes | Year display format. The value can be **numeric** or **2-digit**. | +| month | string | Yes | Yes | Month display format. The value can be any of the following: **numeric**, **2-digit**, **long**, **short**, **narrow**.| +| day | string | Yes | Yes | Day display format. The value can be **numeric** or **2-digit**. | +| hour | string | Yes | Yes | Hour display format. The value can be **numeric** or **2-digit**. | +| minute | string | Yes | Yes | Minute display format. The value can be **numeric** or **2-digit**. | +| second | string | Yes | Yes | Seconds display format. The value can be **numeric** or **2-digit**. | +| timeZoneName | string | Yes | Yes | Localized representation of a time zone name. | +| dayPeriod | string | Yes | Yes | Time period display format. The value can be **long**, **short**, or **narrow**.| +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| formatMatcher | string | Yes | Yes | Format matching algorithm. The value can be **basic** or **best fit**.| ## NumberFormat @@ -301,7 +301,7 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(); ``` @@ -309,19 +309,19 @@ Creates a **NumberFormat** object for the specified locale. ### constructor -constructor(locale: string | Array, options?: NumberOptions) +constructor(locale: string | Array<string>, options?: NumberOptions) Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [NumberOptions](#numberoptions) | No| Options for creating a **NumberFormat** object.| +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options | [NumberOptions](#numberoptions) | No | Options for creating a **NumberFormat** object. | -- Example +**Example** ``` var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -335,18 +335,18 @@ Formats a number. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | number | number | Yes| Number to be formatted.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---- | +| number | number | Yes | Number to be formatted.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Formatted number.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Formatted number.| -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.format(1223); @@ -361,13 +361,13 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| +**Return Value** +| Type | Description | +| ------------------------------- | --------------------------- | +| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.| -- Example +**Example** ``` var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); numfmt.resolvedOptions(); @@ -380,27 +380,27 @@ Provides the device capability. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| No| Locale, for example, **zh-Hans-CN**.| -| currency | string | Yes| Yes| Currency unit, for example, **EUR**, **CNY**, or **USD**.| -| currencySign | string | Yes| Yes| Currency unit symbol. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| -| currencyDisplay | string | Yes| Yes| Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| -| unit | string | Yes| Yes| Unit name, for example, **meter**, **inch**, or **hectare**.| -| unitDisplay | string | Yes| Yes| Unit display format. The value can be **long**, **short**, or **medium**.| -| unitUsage | string | Yes| Yes| Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| -| signDisplay | string | Yes| Yes| Number sign display format. The value can be **auto**, **never**, always**, or **expectZero**.| -| compactDisplay | string | Yes| Yes| Compact display format. The value can be **long** or **short**.| -| notation | string | Yes| Yes| Number formatting specification. The value can be **standard**, **scientific**, engineering**, or **compact**.| -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| style | string | Yes| Yes| Number display format. The value can be **decimal**, **currency**, **percent**, or **unit**.| -| numberingSystem | string | Yes| Yes| Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| -| useGrouping | boolean | Yes| Yes| Whether to use grouping for display.| -| minimumIntegerDigits | number | Yes| Yes| Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**.| -| minimumFractionDigits | number | Yes| Yes| Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**.| -| maximumFractionDigits | number | Yes| Yes| Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**.| -| minimumSignificantDigits | number | Yes| Yes| Minimum number of the least significant digits. The value ranges from **1** to **21**.| -| maximumSignificantDigits | number | Yes| Yes| Maximum number of the least significant digits. The value ranges from **1** to **21**.| +| Name | Type | Readable | Writable | Description | +| ------------------------ | ------- | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | +| currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | +| currencySign | string | Yes | Yes | Currency unit symbol. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| +| currencyDisplay | string | Yes | Yes | Currency display mode. The value can be **symbol**, **narrowSymbol**, **code**, or **name**.| +| unit | string | Yes | Yes | Unit name, for example, **meter**, **inch**, or **hectare**. | +| unitDisplay | string | Yes | Yes | Unit display format. The value can be **long**, **short**, or **medium**.| +| unitUsage | string | Yes | Yes | Unit usage scenario. The value can be any of the following: **default**, **area-land-agricult**, **area-land-commercl**, **area-land-residntl**, **length-person**, **length-person-small**, **length-rainfall**, **length-road**, **length-road-small**, **length-snowfall**, **length-vehicle**, **length-visiblty**, **length-visiblty-small**, **length-person-informal**, **length-person-small-informal**, **length-road-informal**, **speed-road-travel**, **speed-wind**, **temperature-person**, **temperature-weather**, **volume-vehicle-fuel**.| +| signDisplay | string | Yes | Yes | Number sign display format. The value can be **auto**, **never**, **always**, or **expectZero**.| +| compactDisplay | string | Yes | Yes | Compact display format. The value can be **long** or **short**. | +| notation | string | Yes | Yes | Number formatting specification. The value can be **standard**, **scientific**, **engineering**, or **compact**.| +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| style | string | Yes | Yes | Number display format. The value can be **decimal**, **currency**, **percent**, or **unit**.| +| numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| +| useGrouping | boolean | Yes | Yes | Whether to use grouping for display. | +| minimumIntegerDigits | number | Yes | Yes | Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**. | +| minimumFractionDigits | number | Yes | Yes | Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**. | +| maximumFractionDigits | number | Yes | Yes | Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**. | +| minimumSignificantDigits | number | Yes | Yes | Minimum number of the least significant digits. The value ranges from **1** to **21**. | +| maximumSignificantDigits | number | Yes | Yes | Maximum number of the least significant digits. The value ranges from **1** to **21**. | ## Collator8+ @@ -414,7 +414,7 @@ Creates a Collator object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var collator = new Intl.Collator(); ``` @@ -422,20 +422,20 @@ Creates a Collator object. ### constructor8+ -constructor(locale: string | Array, options?: CollatorOptions) +constructor(locale: string | Array<string>, options?: CollatorOptions) Creates a Collator object. **System capability**: SystemCapability.Global.I18n -- Parameters +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| - | options | [CollatorOptions](#collatoroptions) | No| Options for creating a **Collator** object.| +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options | [CollatorOptions](#collatoroptions) | No | Options for creating a **Collator** object. | -- Example +**Example** ``` var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -449,18 +449,18 @@ Compares two strings based on the sorting policy of the **Collator** object. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | first | string | Yes| First string to compare.| - | second | string | Yes| Second string to compare.| +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------ | +| first | string | Yes | First string to compare. | +| second | string | Yes | Second string to compare.| -- Return value - | Type| Description| - | -------- | -------- | - | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| -- Example +**Example** ``` var collator = new Intl.Collator("zh-Hans"); collator.compare("first", "second"); @@ -475,12 +475,12 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| +**Return Value** +| Type | Description | +| ----------------------------------- | ----------------- | +| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.| -- Example +**Example** ``` var collator = new Intl.Collator("zh-Hans"); var options = collator.resolvedOptions(); @@ -493,15 +493,15 @@ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| usage | string | Yes| Yes| Whether the comparison is for sorting or for searching. The value can be **sort** or **search**.| -| sensitivity | string | Yes| Yes| Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| -| ignorePunctuation | boolean | Yes| Yes| Whether punctuation is ignored. The value can be **true** or **false**.| -| collation | string | Yes| Yes| Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| numeric | boolean | Yes| Yes| Whether numeric collation is used. The value can be **true** or **false**.| -| caseFirst | string | Yes| Yes| Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| +| Name | Type | Readable | Writable | Description | +| ----------------- | ------- | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | +| collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | +| caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| ## PluralRules8+ @@ -515,7 +515,7 @@ Create a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var pluralRules = new Intl.PluralRules(); ``` @@ -523,19 +523,19 @@ Create a **PluralRules** object. ### constructor8+ -constructor(locale: string | Array, options?: PluralRulesOptions) +constructor(locale: string | Array<string>, options?: PluralRulesOptions) Create a **PluralRules** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [PluralRulesOptions](#pluralrulesoptions) | No| Options for creating a **PluralRules** object.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options | [PluralRulesOptions](#pluralrulesoptions) | No | Options for creating a **PluralRules** object. | -- Example +**Example** ``` var pluralRules= new Intl.PluraRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -549,17 +549,17 @@ Obtains a string that represents the singular-plural type of the specified numbe **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | n | number | Yes| Number for which the singular-plural type is to be obtained.| +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------------ | +| n | number | Yes | Number for which the singular-plural type is to be obtained.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| +**Return Value** +| Type | Description | +| ------ | ---------------------------------------- | +| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| -- Example +**Example** ``` var pluralRules = new Intl.PluralRules("zh-Hans"); pluralRules.select(1); @@ -572,15 +572,15 @@ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| type | string | Yes| Yes| Sorting type. The value can be **cardinal** or **ordinal**.| -| minimumIntegerDigits | number | Yes| Yes| Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**.| -| minimumFractionDigits | number | Yes| Yes| Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**.| -| maximumFractionDigits | number | Yes| Yes| Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**.| -| minimumSignificantDigits | number | Yes| Yes| Minimum number of the least significant digits. The value ranges from **1** to **21**.| -| maximumSignificantDigits | number | Yes| Yes| Maximum number of the least significant digits. The value ranges from **1** to **21**.| +| Name | Type | Readable | Writable | Description | +| ------------------------ | ------ | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | +| minimumIntegerDigits | number | Yes | Yes | Minimum number of digits allowed in the integer part of a number. The value ranges from **1** to **21**. | +| minimumFractionDigits | number | Yes | Yes | Minimum number of digits in the fraction part of a number. The value ranges from **0** to **20**. | +| maximumFractionDigits | number | Yes | Yes | Maximum number of digits in the fraction part of a number. The value ranges from **1** to **21**. | +| minimumSignificantDigits | number | Yes | Yes | Minimum number of the least significant digits. The value ranges from **1** to **21**. | +| maximumSignificantDigits | number | Yes | Yes | Maximum number of the least significant digits. The value ranges from **1** to **21**. | ## RelativeTimeFormat8+ @@ -594,7 +594,7 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -602,19 +602,19 @@ Creates a **RelativeTimeFormat** object. ### constructor8+ -constructor(locale: string | Array, options?: RelativeTimeFormatInputOptions) +constructor(locale: string | Array<string>, options?: RelativeTimeFormatInputOptions) Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n Parameters -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string \| Array | Yes| A string containing locale information, including the language, optional script, and region.| -| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No| Options for creating a **RelativeTimeFormat** object.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions) | No | Options for creating a **RelativeTimeFormat** object. | -- Example +**Example** ``` var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -628,18 +628,18 @@ Formats the value and unit based on the specified locale and formatting options. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Value to format.| - | unit | string | Yes| Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| value | number | Yes | Value to format. | +| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -- Return value - | Type| Description| - | -------- | -------- | - | string | Relative time after formatting.| +**Return Value** +| Type | Description | +| ------ | ---------- | +| string | Relative time after formatting.| -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); relativetimefmt.format(3, "quarter") @@ -648,24 +648,24 @@ Formats the value and unit based on the specified locale and formatting options. ### formatToParts8+ -formatToParts(value: number, unit: string): Array +formatToParts(value: number, unit: string): Array<object> Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Value to format.| - | unit | string | Yes| Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| +**Parameters** +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| value | number | Yes | Value to format. | +| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -- Return value - | Type| Description| - | -------- | -------- | - | Array | An array of **RelativeTimeFormat** objects in parts.| +**Return Value** +| Type | Description | +| ------------------- | --------------------------- | +| Array<object> | An array of **RelativeTimeFormat** objects in parts.| -- Example +**Example** ``` var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); var parts = relativetimefmt.format(10, "seconds"); @@ -680,12 +680,12 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -- Return value - | Type| Description| - | -------- | -------- | - | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| +**Return Value** +| Type | Description | +| ---------------------------------------- | --------------------------------- | +| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.| -- Example +**Example** ``` var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); relativetimefmt.resolvedOptions(); @@ -698,11 +698,11 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| localeMatcher | string | Yes| Yes| Locale matching algorithm. The value can be **lookup** or **best fit**.| -| numeric | string | Yes| Yes| Format of the output message. The value can be **always** or **auto**.| -| style | string | Yes| Yes| Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| +| Name | Type | Readable | Writable | Description | +| ------------- | ------ | ---- | ---- | ---------------------------------------- | +| localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| +| numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | +| style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| ## RelativeTimeFormatResolvedOptions8+ @@ -711,9 +711,9 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| locale | string | Yes| Yes| A string containing locale information, including the language, optional script, and region.| -| numeric | string | Yes| Yes| Format of the output message. The value can be **always** or **auto**.| -| style | string | Yes| Yes| Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -| numberingSystem | string | Yes| Yes| Numbering system.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------ | ---- | ---- | ---------------------------------------- | +| locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | +| numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | +| style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| +| numberingSystem | string | Yes | Yes | Numbering system. | diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index b61e3e25c5c41e94056904e074669ad68428c117..063b77a636b193720237202185201e3bc9e5a19e 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -524,8 +524,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | LightWeightMap | No| Instance that invokes the **forEach** method.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index 8d604ed7accd8a3781a626bfb13bd4b26342c599..768ffc337f0cba9fce488dbfd78cbc93173271bf 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -279,7 +279,7 @@ Removes the entry at the specified position from this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the entry to remove.| +| index | number | Yes| Position index of the entry.| **Return value** @@ -428,7 +428,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key| T | No| Key of the entry that is currently traversed (same as **value**).| | set | LightWeightSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index c90867ac6d3308532060b0f4ce34b58cac5cc7bf..cebc8bbbf05902ef541166d8688964a9fbe0f1a7 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -176,7 +176,7 @@ let result = linkedList.get(2); ### getLastIndexOf -getLastIndexOf(element: T): number; +getLastIndexOf(element: T): number Obtains the index of the last occurrence of the specified entry in this container. @@ -404,11 +404,10 @@ let result = linkedList.removeLastFound(4); ``` ### clone -clone(): LinkedList<T> -Clones this container and returns a copy. +clone(): LinkedList<T> -The modification to the copy does not affect the original instance. +Clones this container and returns a copy. The modification to the copy does not affect the original instance. **Return value** @@ -428,6 +427,7 @@ let result = linkedList.clone(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void @@ -462,6 +462,7 @@ linkedList.forEach((value, index) => { ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -478,6 +479,7 @@ linkedList.clear(); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. @@ -507,6 +509,7 @@ let result = linkedList.set(2, "b"); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -575,7 +578,7 @@ linkedList.getLast(); ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<T>; +[Symbol.iterator]\(): IterableIterator<T> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 7c39d49ce7febeb2c27fcd532f993ea4ec2e5d37..ad87462656501d54e206b824c51b5555ec8b3e67 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -60,7 +60,7 @@ Adds an entry at the end of this container. **Example** ``` -let list = new List; +let list = new List(); let result = list.add("a"); let result1 = list.add(1); let b = [1, 2, 3]; @@ -160,7 +160,7 @@ Obtains the index of the last occurrence of the specified entry in this containe | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Entry to obtain.| **Return value** @@ -192,7 +192,7 @@ Obtains the index of the first occurrence of the specified entry in this contain | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| element | T | Yes| Entry to query.| +| element | T | Yes| Entry to obtain.| **Return value** @@ -310,6 +310,7 @@ let result = list.remove(2); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void @@ -347,6 +348,7 @@ list.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void @@ -382,6 +384,7 @@ list.forEach((value, index) => { ``` ### sort + sort(comparator: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -412,6 +415,7 @@ list.sort(a, (b => b - a)); ``` ### getSubList + getSubList(fromIndex: number, toIndex: number): List<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **List** instance. @@ -443,6 +447,7 @@ let result2 = list.subList(2, 6); ``` ### clear + clear(): void Clears this container and sets its length to **0**. @@ -459,6 +464,7 @@ list.clear(); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. @@ -489,6 +495,7 @@ list.set(2, "b"); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -511,6 +518,7 @@ let result = list.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -547,7 +555,7 @@ Obtains the first entry in this container. **Example** ``` -let list = new Vector(); +let list = new List(); list.add(2); list.add(4); list.add(5); @@ -570,7 +578,7 @@ Obtains the last entry in this container. **Example** ``` -let list = new Vector(); +let list = new List(); list.add(2); list.add(4); list.add(5); @@ -580,7 +588,7 @@ let result = list.getLast(); ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<T>; +[Symbol.iterator]\(): IterableIterator<T> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index 864ce3ecc2e4ff92feebd0079fb597d8d55ee264..e2d0aff5a5eec1f468b0511a08f1f593a9af3548 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,174 +1,69 @@ -# Console Logs +# Log -## Module to Import +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead. -No module is required. +## console.debug -## Required Permissions +debug(message: string): void -None +Prints debug logs. -## console.debug +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| -debug\(message: string\): void -Prints debug logs. +## console.log -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.log - -log\(message: string\): void +log(message: string): void Prints debug logs. -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.info - -info\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.info + +info(message: string): void Prints info-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.warn - -warn\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.warn + +warn(message: string): void Prints warn-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## console.error - -error\(message: string\): void +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## console.error + +error(message: string): void Prints error-level logs. -- Parameters - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print.

-
- - -## Example +- Parameters + | Name | Type | Mandatory | Description | + | ------- | ------ | ---- | ----------- | + | message | string | Yes | Text to print.| + + +## Example ``` export default { @@ -176,13 +71,11 @@ export default { var versionCode = 1; console.info('Hello World. The current version code is ' + versionCode); console.log(`versionCode: ${versionCode}`); - // The following is supported since API version 6. - console.log('versionCode:%d.', versionCode); + / / The following is supported since API version 6: console.log('versionCode:%d.', versionCode); } } ``` -Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. - -![](figures/log.png) +Switch to the HiLog window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to Info, and enter Hello World in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. +![en-us_image_0000001200913929](figures/en-us_image_0000001200913929.png) diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index ae07870d380fb69569ef860b469f865b2d3baad6..7fdf7692a1803ba6bae9f67023f7fe954daa12aa 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -10,7 +10,6 @@ This subsystem offers various media services covering audio and video, which pro - Audio playback ([AudioPlayer](#audioplayer)) - Video playback ([VideoPlayer](#videoplayer8)) - Audio recording ([AudioRecorder](#audiorecorder)) -- Video recording ([VideoRecorder](#videorecorder9)) The following capabilities will be provided in later versions: data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. @@ -122,7 +121,7 @@ Creates an **AudioRecorder** instance to control audio recording. **Example** ```js -let audiorecorder = media.createAudioRecorder(); +let audiorecorder = media.createAudioRecorder(); ``` ## MediaErrorCode8+ @@ -183,13 +182,13 @@ Enumerates the media description keys. | MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number. | | MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| | MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string. | -| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms. | -| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s. | -| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel. | -| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel. | -| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps. | +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms. | +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s. | +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel. | +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel. | +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| | MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number. | -| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz. | +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz. | ## BufferingInfoType8+ @@ -197,11 +196,11 @@ Enumerates the buffering event types. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Value | Description | -| ----------------- | ---- | -------------------------- | -| BUFFERING_START | 1 | Buffering starts. | -| BUFFERING_END | 2 | Buffering ends. | -| BUFFERING_PERCENT | 3 | Buffering progress, in percent. | +| Name | Value | Description | +| ----------------- | ---- | -------------------------------- | +| BUFFERING_START | 1 | Buffering starts. | +| BUFFERING_END | 2 | Buffering ends. | +| BUFFERING_PERCENT | 3 | Buffering progress, in percent. | | CACHED_DURATION | 4 | Cache duration, in milliseconds.| ## AudioPlayer @@ -216,7 +215,7 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. | +| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | currentTime | number | Yes | No | Current audio playback position. | | duration | number | Yes | No | Audio duration. | @@ -300,8 +299,8 @@ Seeks to the specified playback position. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| **Example** @@ -478,24 +477,24 @@ Subscribes to the audio playback events. ```js let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. - console.info('audio set source success'); + console.info('audio set source success'); audioPlayer.play(); // Start the playback and trigger the 'play' event callback. }); audioPlayer.on('play', () => { // Set the 'play' event callback. - console.info('audio play success'); + console.info('audio play success'); audioPlayer.seek(30000); // Call the seek() API and trigger the 'timeUpdate' event callback. }); audioPlayer.on('pause', () => { // Set the 'pause' event callback. - console.info('audio pause success'); + console.info('audio pause success'); audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('reset', () => { // Set the 'reset' event callback. - console.info('audio reset success'); + console.info('audio reset success'); audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (typeof(seekDoneTime) == "undefined") { + if (typeof(seekDoneTime) == "undefined") { console.info('audio seek fail'); return; } @@ -503,15 +502,15 @@ audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. }); audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. - console.info('audio volumeChange success'); + console.info('audio volumeChange success'); audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. }); audioPlayer.on('finish', () => { // Set the 'finish' event callback. - console.info('audio play finish'); + console.info('audio play finish'); audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); @@ -577,7 +576,7 @@ Subscribes to the audio playback error event. ```js audioPlayer.on('error', (error) => { // Set the error event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); @@ -610,7 +609,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 playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly. | +| 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 playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HLS network playback path (under development)
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | currentTime8+ | number | Yes | No | Current video playback position. | | duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode. | @@ -631,15 +630,15 @@ Sets **SurfaceId**. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | --------- | -------- | ---- | ------------------------- | | surfaceId | string | Yes | Surface ID to set. | -| callback | function | Yes | Callback used to set **SurfaceId**.| +| callback | function | Yes | Callback used to return the result.| **Example** ```js videoPlayer.setDisplaySurface(surfaceId, (err) => { - if (typeof (err) == 'undefined') { - console.info('setDisplaySurface success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setDisplaySurface success!'); + } else { console.info('setDisplaySurface fail!'); } }); @@ -663,7 +662,7 @@ Sets **SurfaceId**. This API uses a promise to return the result. | Type | Description | | ------------- | ------------------------------ | -| Promise | Promise used to set **SurfaceId**.| +| Promise | Promise used to return the result.| **Example** @@ -697,9 +696,9 @@ Prepares for video playback. This API uses a callback to return the result. ```js videoPlayer.prepare((err) => { - if (typeof (err) == 'undefined') { - console.info('prepare success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('prepare success!'); + } else { console.info('prepare fail!'); } }); @@ -751,9 +750,9 @@ Starts to play video resources. This API uses a callback to return the result. ```js videoPlayer.play((err) => { - if (typeof (err) == 'undefined') { - console.info('play success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('play success!'); + } else { console.info('play fail!'); } }); @@ -805,9 +804,9 @@ Pauses video playback. This API uses a callback to return the result. ```js videoPlayer.pause((err) => { - if (typeof (err) == 'undefined') { - console.info('pause success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('pause success!'); + } else { console.info('pause fail!'); } }); @@ -859,9 +858,9 @@ Stops video playback. This API uses a callback to return the result. ```js videoPlayer.stop((err) => { - if (typeof (err) == 'undefined') { - console.info('stop success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('stop success!'); + } else { console.info('stop fail!'); } }); @@ -913,9 +912,9 @@ Switches the video resource to be played. This API uses a callback to return the ```js videoPlayer.reset((err) => { - if (typeof (err) == 'undefined') { - console.info('reset success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('reset success!'); + } else { console.info('reset fail!'); } }); @@ -959,18 +958,18 @@ Seeks to the specified playback position. The next key frame at the specified po **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| callback | function | Yes | Callback used to return the result.| +| callback | function | Yes | Callback used to return the result. | **Example** ```js videoPlayer.seek((seekTime, err) => { - if (typeof (err) == 'undefined') { - console.info('seek success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { console.info('seek fail!'); } }); @@ -986,19 +985,19 @@ Seeks to the specified playback position. This API uses a callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | function | Yes | Callback used to return the result.| +| mode | [SeekMode](#seekmode8) | Yes | Seek mode. | +| callback | function | Yes | Callback used to return the result. | **Example** ```js videoPlayer.seek((seekTime, seekMode, err) => { - if (typeof (err) == 'undefined') { - console.info('seek success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('seek success!'); + } else { console.info('seek fail!'); } }); @@ -1014,10 +1013,10 @@ Seeks to the specified playback position. If **mode** is not specified, the next **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------- | ---- | ------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------------------------------ | | timeMs | number | Yes | Position to seek to, in milliseconds.| -| mode | [SeekMode](#seekmode8) | No | Seek mode. | +| mode | [SeekMode](#seekmode8) | No | Seek mode. | **Return value** @@ -1062,9 +1061,9 @@ Sets the volume. This API uses a callback to return the result. ```js videoPlayer.setVolume((vol, err) => { - if (typeof (err) == 'undefined') { - console.info('setVolume success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setVolume success!'); + } else { console.info('setVolume fail!'); } }); @@ -1122,9 +1121,9 @@ Releases the video playback resource. This API uses a callback to return the res ```js videoPlayer.release((err) => { - if (typeof (err) == 'undefined') { - console.info('release success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('release success!'); + } else { console.info('release fail!'); } }); @@ -1257,9 +1256,9 @@ Sets the video playback speed. This API uses a callback to return the result. ```js videoPlayer.setSpeed((speed:number, err) => { - if (typeof (err) == 'undefined') { - console.info('setSpeed success!'); - } else { + if (typeof (err) == 'undefined') { + console.info('setSpeed success!'); + } else { console.info('setSpeed fail!'); } }); @@ -1318,7 +1317,7 @@ Subscribes to the video playback completion event. ```js videoPlayer.on('playbackCompleted', () => { - console.info('playbackCompleted success!'); + console.info('playbackCompleted success!'); }); ``` @@ -1365,7 +1364,7 @@ Subscribes to the frame rendering start event. ```js videoPlayer.on('startRenderFrame', () => { - console.info('startRenderFrame success!'); + console.info('startRenderFrame success!'); }); ``` @@ -1412,7 +1411,7 @@ Subscribes to the video playback error event. ```js videoPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`video error called, errName is ${error.name}`); // Print the error name. + console.info(`video error called, errName is ${error.name}`); // Print the error name. console.info(`video error called, errCode is ${error.code}`); // Print the error code. console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); @@ -1656,7 +1655,7 @@ Subscribes to the audio recording events. **Example** ```js -let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. +let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { audioEncoder : media.AudioEncoder.AAC_LC, , audioEncodeBitRate : 22050, @@ -1666,34 +1665,34 @@ let audioRecorderConfig = { uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. location : { latitude : 30, longitude : 130}, } -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errMessage is ${error.message}`); }); -audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the 'start' event callback. + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); -audioRecorder.on('start', () => { // Set the 'start' event callback. +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the 'pause' event callback. +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the 'resume' event callback. +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the 'stop' event callback. +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the 'release' event callback. +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the 'reset' event callback. +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` ### on('error') @@ -1714,12 +1713,12 @@ Subscribes to the audio recording error event. **Example** ```js -audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. +audioRecorder.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. console.info(`audio error called, errCode is ${error.code}`); // Print the error code. console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig @@ -1736,11 +1735,14 @@ Describes audio recording configurations. | numberOfChannels | number | No | Number of audio channels. The default value is **2**. | | format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | | location | [Location](#location) | No | Geographical location of the recorded audio. | -| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| +| uri | string | Yes | Audio output URI. Supported: fd://xx (fd number)
![en-us_image_0000001164217678](figures/en-us_image_url.png)
The file must be created by the caller and granted with proper permissions.| | audioEncoderMime | [CodecMimeType](#codecmimetype8) | No | Audio encoding format. | -## AudioEncoder +## AudioEncoder(deprecated) + +> **NOTE** +> This API is deprecated since API version 8. You are advised to use [CodecMimeType](#codecmimetype8) instead. Enumerates the audio encoding formats. @@ -1748,14 +1750,17 @@ Enumerates the audio encoding formats. | Name | Default Value| Description | | ------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default audio encoding format, which is Adaptive Multi Rate-Narrow Band Speech Codec (AMR-NB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_NB | 1 | AMR-NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet.| +| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| | AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| -## AudioOutputFormat +## AudioOutputFormat(deprecated) + +> **NOTE** +> This API is deprecated since API version 8. You are advised to use [ContainerFormatType ](#containerformattype8) instead. Enumerates the audio output formats. @@ -1763,10 +1768,10 @@ Enumerates the audio output formats. | Name | Default Value| Description | | -------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encapsulation format, which is MPEG-4.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet.| | MPEG_4 | 2 | MPEG-4. | -| AMR_NB | 3 | AMR_NB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| -| AMR_WB | 4 | AMR_WB.
This API is merely defined in OpenHarmony 3.1 Release and cannot be used currently. It can be used in OpenHarmony 3.1 MR.| +| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet.| +| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet.| | AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| ## ContainerFormatType8+ @@ -1777,7 +1782,7 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MP4.| +| CFT_MPEG_4 | "mp4" | Video container format MPEG-4 .| | CFT_MPEG_4A | "m4a" | Audio container format M4A.| ## Location diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index b741802e7e2fac86802a5b6b041c72448e48b93f..e1136262786911403a2e2f7f9cfc9a9cd19f72f2 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -5,22 +5,22 @@ ## Modules to Import ``` -import mediaLibrary from '@ohos.multimedia.medialibrary'; +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; ``` -## mediaLibrary.getMediaLibrary +## mediaLibrary.getMediaLibrary8+ getMediaLibrary(context: Context): MediaLibrary -Obtains a **MediaLibrary** instance, which is used to access and modify personal data of users. +Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Context of the ability. This parameter is optional for API version 7 and earlier versions, but mandatory for API version 8 and later versions.| +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| context | Context | Yes | Context of the ability.| **Return value** @@ -36,9 +36,31 @@ import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() var media = mediaLibrary.getMediaLibrary(context); ``` +## mediaLibrary.getMediaLibrary + +getMediaLibrary(): MediaLibrary + +Obtains a **MediaLibrary** instance, which is used to access and modify personal media data such as audios, videos, images, and documents. + +> **Note**: This API is no longer maintained since API version 8. You are advised to use [mediaLibrary.getMediaLibrary8+](#medialibrarygetmedialibrary8) instead. + +**System capability**: SystemCapability.Multimedia.MediaLibrary.Core + +**Return value** + +| Type | Description | +| ----------------------------- | :--------- | +| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| + +**Example** + +```js +var media = mediaLibrary.getMediaLibrary(); +``` + ## MediaLibrary -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void @@ -51,10 +73,10 @@ Obtains file assets (also called files). This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult8)> | Yes | Asynchronous callback of **FetchFileResult**.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | --------------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Asynchronous callback of **FetchFileResult**.| **Example** @@ -76,7 +98,7 @@ mediaLibrary.getFileAssets(imagesfetchOp, (error, fetchFileResult) => { } }); ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions): Promise<FetchFileResult> @@ -88,15 +110,15 @@ Obtains file assets. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------ | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files.| **Return value** -| Type | Description | -| ------------------------------------ | ------- | -| [FetchFileResult](#fetchfileresult8) | Result set of the file retrieval operation.| +| Type | Description | +| ------------------------------------ | -------------- | +| [FetchFileResult](#fetchfileresult7) | Result set of the file retrieval operation.| **Example** @@ -171,12 +193,12 @@ Creates a media asset. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | --------------------------------------- | ---- | ---------------------------------------- | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | Display file name. | -| relativePath | string | Yes | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.| -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Asynchronous callback for **FileAsset**. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype8) | Yes | Media type. | +| displayName | string | Yes | Display file name. | +| relativePath | string | Yes | Path for storing the file. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the paths for storing different types of files.| +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Asynchronous callback for **FileAsset**. | **Example** @@ -208,17 +230,17 @@ Creates a media asset. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------ | ----------------------- | ---- | ---------------------------------------- | -| mediaType | [MediaType](#mediatype) | Yes | Media type. | -| displayName | string | Yes | Display file name. | -| relativePath | string | Yes | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.| +| Name | Type | Mandatory| Description | +| ------------ | ------------------------ | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype8) | Yes | Media type. | +| displayName | string | Yes | Display file name. | +| relativePath | string | Yes | Relative path. You can use [getPublicDirectory](#getpublicdirectory8) to obtain the relative path of the level-1 directory of different types of media files.| **Return value** -| Type | Description | -| ------------------------ | ------------- | -| [FileAsset](#fileasset8) | Media data (FileAsset).| +| Type | Description | +| ------------------------ | ----------------- | +| [FileAsset](#fileasset7) | Media data (FileAsset).| **Example** @@ -246,10 +268,10 @@ Obtains a public directory. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | ---- | ----------------- | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | -| callback | AsyncCallback<string> | Yes | Callback used to return the public directory.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------- | +| type | [DirectoryType](#directorytype8) | Yes | Type of the public directory. | +| callback | AsyncCallback<string> | Yes | Callback used to return the public directory.| **Example** @@ -274,15 +296,15 @@ Obtains a public directory. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------------------------------- | ---- | ------ | -| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ------------ | +| type | [DirectoryType](#directorytype8) | Yes | Type of the public directory.| **Return value** -| Type | Description | -| --------------- | -------- | -| Promise | Promise used to return the public directory.| +| Type | Description | +| ---------------- | ---------------- | +| Promise\ | Promise used to return the public directory.| **Example** @@ -298,7 +320,7 @@ async function example() { } ``` -### getAlbums8+ +### getAlbums7+ getAlbums(options: MediaFetchOptions, callback: AsyncCallback): void @@ -310,10 +332,10 @@ Obtains the albums. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ---------------- | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the albums. | -| callback | AsyncCallback<Array<[Album](#album8)>> | Yes | Callback used to return the albums.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | --------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<Array<[Album](#album7)>> | Yes | Callback used to return the albums.| **Example** @@ -333,7 +355,7 @@ mediaLibrary.getAlbums(AlbumNoArgsfetchOp, (err, albumList) => { }) ``` -### getAlbums8+ +### getAlbums7+ getAlbums(options: MediaFetchOptions): Promise @@ -345,15 +367,15 @@ Obtains the albums. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the albums.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | ------------ | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the albums.| **Return value** -| Type | Description | -| -------------------------------- | --------- | -| Promise> | Promise used to return the albums.| +| Type | Description | +| -------------------------------- | ------------- | +| Promise> | Promise used to return the albums.| **Example** @@ -690,7 +712,7 @@ mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => { ``` -## FileAsset8+ +## FileAsset7+ Provides APIs for encapsulating file asset attributes. @@ -698,29 +720,29 @@ Provides APIs for encapsulating file asset attributes. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Description | -| ------------ | ----------------------- | ---- | ---- | --------------------------------------- | -| id | number | Yes | No | File asset ID. | -| uri | string | Yes | No | File asset URI, for example, dataability:///media/image/2.| -| mimeType | string | Yes | No | Extended file attributes. | -| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | -| displayName | string | Yes | Yes | Display file name, including the file name extension. | -| title | string | Yes | Yes | Title in the file. | -| relativePath | string | Yes | Yes | Relative public directory of the file. | -| parent | number | Yes | No | Parent directory ID. | -| size | number | Yes | No | File size, in bytes. | -| dateAdded | number | Yes | No | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| dateModified | number | Yes | No | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| dateTaken | number | Yes | No | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | -| artist | string | Yes | No | Artist of the file. | -| audioAlbum | string | Yes | No | Audio album. | -| width | number | Yes | No | Image width, in pixels. | -| height | number | Yes | No | Image height, in pixels. | -| orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees). | -| duration | number | Yes | No | Duration, in seconds. | -| albumId | number | Yes | No | ID of the album to which the file belongs. | -| albumUri | string | Yes | No | URI of the album to which the file belongs. | -| albumName | string | Yes | No | Name of the album to which the file belongs. | +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | +| id | number | Yes | No | File asset ID. | +| uri | string | Yes | No | File asset URI, for example, dataability:///media/image/2. | +| mimeType | string | Yes | No | Extended file attributes. | +| mediaType8+ | [MediaType](#mediatype8) | Yes | No | Media type. | +| displayName | string | Yes | Yes | Display file name, including the file name extension. | +| title | string | Yes | Yes | Title in the file. | +| relativePath8+ | string | Yes | Yes | Relative public directory of the file. | +| parent8+ | number | Yes | No | Parent directory ID. | +| size | number | Yes | No | File size, in bytes. | +| dateAdded | number | Yes | No | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | +| dateModified | number | Yes | No | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | +| dateTaken | number | Yes | No | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| artist8+ | string | Yes | No | Artist of the file. | +| audioAlbum8+ | string | Yes | No | Audio album. | +| width | number | Yes | No | Image width, in pixels. | +| height | number | Yes | No | Image height, in pixels. | +| orientation | number | Yes | Yes | Image display direction (clockwise rotation angle, for example, 0, 90, or 180, in degrees).| +| duration8+ | number | Yes | No | Duration, in seconds. | +| albumId | number | Yes | No | ID of the album to which the file belongs. | +| albumUri8+ | string | Yes | No | URI of the album to which the file belongs. | +| albumName | string | Yes | No | Name of the album to which the file belongs. | ### isDirectory8+ @@ -946,7 +968,7 @@ close(fd: number, callback: AsyncCallback<void>): void Closes this file asset. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.READ_MEDIA ('r' enabled) and ohos.permission.WRITE_MEDIA ('w' enabled) +**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -987,7 +1009,7 @@ close(fd: number): Promise<void> Closes this file asset. This API uses a promise to return the result. -**Required permissions**: ohos.permission.READ_MEDIA ('r' enabled) and ohos.permission.WRITE_MEDIA ('w' enabled) +**Required permissions**: ohos.permission.READ_MEDIA (when **mode** is set to **r**) and ohos.permission.WRITE_MEDIA (when **mode** is set to **w**) **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1127,15 +1149,19 @@ Obtains the thumbnail of this file asset, with the thumbnail size passed. This A async function example() { let imageType = mediaLibrary.MediaType.IMAGE; let getImageOp = { - selections: fileKeyObj.MEDIA_TYPE + '= ?', - selectionArgs: [imageType.toString()], - order: fileKeyObj.DATE_ADDED + " DESC", - extendArgs: "", + 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.getThumbnail(size, (err, pixelmap) => { + asset.getThumbnail(size) + .then((pixelmap) => { console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }) + .catch((err) => { + console.info('mediaLibraryTest : getThumbnail fail'+ err); }); } ``` @@ -1460,11 +1486,11 @@ async function example() { } ``` -## FetchFileResult8+ +## FetchFileResult7+ Implements the result set of the file retrieval operation. -### getCount8+ +### getCount7+ getCount(): number @@ -1493,7 +1519,7 @@ async function example() { } ``` -### isAfterLast8+ +### isAfterLast7+ isAfterLast(): boolean @@ -1536,7 +1562,7 @@ async function example() { } ``` -### close8+ +### close7+ close(): void @@ -1560,7 +1586,7 @@ async function example() { } ``` -### getFirstObject8+ +### getFirstObject7+ getFirstObject(callback: AsyncCallback<FileAsset>): void @@ -1570,9 +1596,9 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the first file asset.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the first file asset.| **Example** @@ -1596,7 +1622,7 @@ async function example() { } ``` -### getFirstObject8+ +### getFirstObject7+ getFirstObject(): Promise<FileAsset> @@ -1606,9 +1632,9 @@ Obtains the first file asset in the result set. This API uses a promise to retur **Return value** -| Type | Description | -| --------------------------------------- | -------------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the file asset.| +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the file asset.| **Example** @@ -1630,7 +1656,7 @@ async function example() { } ``` -### getNextObject8+ +### getNextObject7+ getNextObject(callback: AsyncCallback<FileAsset>): void @@ -1642,9 +1668,9 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | ------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the next file asset.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ----------------------------------------- | +| callbacke | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the next file asset.| **Example** @@ -1668,7 +1694,7 @@ async function example() { } ``` -### getNextObject8+ +### getNextObject7+ getNextObject(): Promise<FileAsset> @@ -1680,9 +1706,9 @@ Obtains the next file asset in the result set. This API uses a promise to return **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1702,7 +1728,7 @@ async function example() { } ``` -### getLastObject8+ +### getLastObject7+ getLastObject(callback: AsyncCallback<FileAsset>): void @@ -1712,9 +1738,9 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the last file asset.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.| **Example** @@ -1738,7 +1764,7 @@ async function example() { } ``` -### getLastObject8+ +### getLastObject7+ getLastObject(): Promise<FileAsset> @@ -1748,9 +1774,9 @@ Obtains the last file asset in the result set. This API uses a promise to return **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1768,7 +1794,7 @@ async function example() { } ``` -### getPositionObject8+ +### getPositionObject7+ getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void @@ -1781,7 +1807,7 @@ Obtains a file asset with the specified index in the result set. This API uses a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------ | | index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | -| callback | AsyncCallback<[FileAsset](#fileasset8)> | Yes | Callback used to return the last file asset.| +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the last file asset.| **Example** @@ -1805,7 +1831,7 @@ async function example() { } ``` -### getPositionObject8+ +### getPositionObject7+ getPositionObject(index: number): Promise<FileAsset> @@ -1823,9 +1849,9 @@ Obtains a file asset with the specified index in the result set. This API uses a **Return value** -| Type | Description | -| --------------------------------------- | ------------- | -| Promise<[FileAsset](#fileasset8)> | Promise used to return the next file asset.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset7)> | Promise used to return the next file asset.| **Example** @@ -1849,7 +1875,7 @@ async function example() { } ``` -### getAllObject8+ +### getAllObject7+ getAllObject(callback: AsyncCallback<Array<FileAsset>>): void @@ -1863,7 +1889,7 @@ Obtains all the file assets in the result set. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| callback | AsyncCallback> | Yes | Callback used to return the file assets.| +| callback | AsyncCallback> | Yes | Callback used to return the file assets.| **Example** @@ -1887,7 +1913,7 @@ async function example() { } ``` -### getAllObject8+ +### getAllObject7+ getAllObject(): Promise<Array<FileAsset>> @@ -1897,9 +1923,9 @@ Obtains all the file assets in the result set. This API uses a promise to return **Return value** -| Type | Description | -| ---------------------------------------- | --------------- | -| Promise> | Promise used to return the file assets.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise> | Promise used to return the file assets.| **Example** @@ -1917,7 +1943,7 @@ async function example() { } ``` -## Album8+ +## Album7+ Provides APIs to implement a physical album. @@ -1927,13 +1953,13 @@ Provides APIs to implement a physical album. | Name | Type | Readable | Writable | Description | | ------------ | ------ | ---- | ---- | ------- | -| albumId | number | Yes | No | Album ID. | -| albumName | string | Yes | Yes | Album name. | -| albumUri | string | Yes | No | Album URI. | +| albumId | number | Yes | No | Album ID. | +| albumName | string | Yes | Yes | Album name. | +| albumUri8+ | string | Yes | No | Album URI. | | dateModified | number | Yes | No | Date when the album was modified. | -| count | number | Yes | No | Number of files in the album.| -| relativePath | string | Yes | No | Relative path of the album. | -| coverUri | string | Yes | No | URI of the cover file of the album.| +| count8+ | number | Yes | No | Number of files in the album.| +| relativePath8+ | string | Yes | No | Relative path of the album. | +| coverUri8+ | string | Yes | No | URI of the cover file of the album.| ### commitModify8+ @@ -1947,9 +1973,9 @@ Commits the modification of the album attributes to the database. This API uses **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----- | -| callback | AsyncCallback<void> | Yes | Void callback.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Void callback.| **Example** @@ -2007,7 +2033,7 @@ async function example() { } ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void @@ -2019,10 +2045,10 @@ Obtains the file assets in this album. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | Yes | Options for fetching the files. | -| callback | AsyncCallback<[FetchFileResult](#fetchfileresult8)> | Yes | Callback used to return the file assets.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult7)> | Yes | Callback used to return the file assets.| **Example** @@ -2041,7 +2067,7 @@ async function example() { } ``` -### getFileAssets8+ +### getFileAssets7+ getFileAssets(options?: MediaFetchOptions): Promise<FetchFileResult> @@ -2053,15 +2079,15 @@ Obtains the file assets in this album. This API uses a promise to return the res **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ------ | -| options | [MediaFetchOptions](#mediafetchoptions8) | No | Options for fetching the files.| +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| options | [MediaFetchOptions](#mediafetchoptions7) | No | Options for fetching the files.| **Return value** -| Type | Description | -| ---------------------------------------- | ------------------- | -| Promise<[FetchFileResult](#fetchfileresult8)> | Promise used to return the file assets.| +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult7)> | Promise used to return the file assets.| **Example** @@ -2087,105 +2113,101 @@ Describes information about a registered device. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Description | -| ---------- | ---------- | ---- | ---- | --------- | -| deviceName | string | Yes | No | Name of the registered device. | -| networkId | string | Yes | No | Network ID of the registered device.| -| deviceType | DeviceType | Yes | No | Type of the registered device. | -| isOnline | boolean | Yes | No | Whether the registered device is online. | +| Name | Type | Readable| Writable| Description | +| ---------- | -------------------------- | ---- | ---- | ---------------- | +| deviceName | string | Yes | No | Name of the registered device. | +| networkId | string | Yes | No | Network ID of the registered device.| +| deviceType | [DeviceType](#devicetype8) | Yes | No | Type of the registered device. | +| isOnline | boolean | Yes | No | Whether the registered device is online. | -MediaType ---------- +## MediaType8+ Enumerates media types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ----- | ---- | ---- | -| FILE | 0 | File. | -| IMAGE | 1 | Image. | -| VIDEO | 2 | Video. | -| AUDIO | 3 | Audio. | +| Name | Default Value| Description| +| ----- | ------ | ---- | +| FILE | 1 | File.| +| IMAGE | 3 | Image.| +| VIDEO | 4 | Video.| +| AUDIO | 5 | Audio.| -FileKey -------- +## FileKey8+ Enumerates key file information. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------- | ------------------- | -------------------------------- | -| ID | file_id | File ID. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | Display file name. | -| PARENT | parent | Parent directory ID. | -| MIME_TYPE | mime_type | Extended file attributes. | -| MEDIA_TYPE | media_type | Media type. | -| SIZE | size | File size, in bytes. | -| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | -| TITLE | title | Title in the file. | -| ARTIST | artist | Artist of the file. | -| AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in seconds. | -| WIDTH | width | Image width, in pixels. | -| HEIGHT | height | Image height, in pixels. | +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| ID | file_id | File ID. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | Display file name. | +| PARENT | parent | Parent directory ID. | +| MIME_TYPE | mime_type | Extended file attributes. | +| MEDIA_TYPE | media_type | Media type. | +| SIZE | size | File size, in bytes. | +| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| TITLE | title | Title in the file. | +| ARTIST | artist | Artist of the file. | +| AUDIOALBUM | audio_album | Audio album. | +| DURATION | duration | Duration, in seconds. | +| WIDTH | width | Image width, in pixels. | +| HEIGHT | height | Image height, in pixels. | | ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| -| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | -| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | +| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | +| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | -DirectoryType -------------- +## DirectoryType8+ Enumerates directory types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------- | ---- | ------------ | -| DIR_CAMERA | 0 | Directory of camera files.| -| DIR_VIDEO | 1 | Directory of video files. | -| DIR_IMAGE | 2 | Directory of image files. | -| DIR_AUDIO | 3 | Directory of audio files. | -| DIR_DOCUMENTS | 4 | Directory of documents. | -| DIR_DOWNLOAD | 5 | Download directory. | +| Name | Default Value| Description | +| ------------- | ------ | ------------------ | +| DIR_CAMERA | 0 | Directory of camera files.| +| DIR_VIDEO | 1 | Directory of video files. | +| DIR_IMAGE | 2 | Directory of image files. | +| DIR_AUDIO | 3 | Directory of audio files. | +| DIR_DOCUMENTS | 4 | Directory of documents. | +| DIR_DOWNLOAD | 5 | Download directory. | -DeviceType ------------ +## DeviceType8+ Enumerates device types. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Default Value | Description | -| ------------ | ---- | ----- | -| TYPE_UNKNOWN | 0 | Unknown.| -| TYPE_LAPTOP | 1 | Laptop.| -| TYPE_PHONE | 2 | Phone. | -| TYPE_TABLET | 3 | Tablet. | -| TYPE_WATCH | 4 | Smart watch. | -| TYPE_CAR | 5 | Vehicle-mounted device. | -| TYPE_TV | 6 | TV. | +| Name | Default Value| Description | +| ------------ | ------ | ---------- | +| TYPE_UNKNOWN | 0 | Unknown.| +| TYPE_LAPTOP | 1 | Laptop.| +| TYPE_PHONE | 2 | Phone. | +| TYPE_TABLET | 3 | Tablet. | +| TYPE_WATCH | 4 | Smart watch. | +| TYPE_CAR | 5 | Vehicle-mounted device. | +| TYPE_TV | 6 | TV. | -## MediaFetchOptions8+ +## MediaFetchOptions7+ Describes options for fetching media files. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core -| Name | Type | Readable | Writable | Mandatory | Description | -| ------------- | ------------------- | ---- | ---- | ---- | ---------------------------------------- | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey) 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](#filekey) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| -| uri | string | Yes | Yes | No | File URI. | -| networkId | string | Yes | Yes | No | Network ID of the registered device. | -| extendArgs | string | Yes | Yes | No | Extended parameters for fetching the files. Currently, no extended parameters are available. | +| Name | Type | Readable| Writable| Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| 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()], | +| order8+ | 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 + " AESC"
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. | ## Size8+ diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md new file mode 100644 index 0000000000000000000000000000000000000000..7cb3263efc4800810a185bf908ae98fef33808ec --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -0,0 +1,145 @@ +# Media Query + +> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** +> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import mediaquery from '@ohos.mediaquery' +``` + + +## Required Permissions + +None. + + +## mediaquery.matchMediaSync + +matchMediaSync(condition: string): MediaQueryListener + +Sets the media query criteria and returns the corresponding listening handle. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | condition | string | Yes| Matching condition of a media event.| + +- Return value + | Type| Description| + | -------- | -------- | + | MediaQueryListener | Listening handle to a media event, which is used to register or unregister the listening callback.| + +- Example + ``` + listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + ``` + + +## MediaQueryListener + +Media query handle, including the first query result when the handle is applied for. + + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| matches | boolean | Yes| No| Whether the match condition is met.| +| media | string | Yes| No| Matching condition of a media event.| + + +### on + +on(type: 'change', callback: Callback<MediaQueryResult>): void + +Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Must enter the string **change**.| + | callback | Callback<MediaQueryResult> | Yes| Callback registered with media query.| + +- Example + For details, see [off Example](#off). + + +### off + +off(type: 'change', callback?: Callback<MediaQueryResult>): void + +Unregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | boolean | Yes| Must enter the string **change**.| + | callback | Callback<MediaQueryResult> | No| Callback to be unregistered. If the default value is used, all callbacks of the handle are unregistered.| + +- Example + ``` + import mediaquery from '@ohos.mediaquery' + + listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. + function onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + // do something here + } else { + // do something here + } + } + this.listener.on('change', this.onPortrait) // Registration callback. + this.listener.off('change', this.onPortrait) // Deregistration callback. + ``` + + +## MediaQueryResult + + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| matches | boolean | Yes| No| Whether the match condition is met.| +| media | string | Yes| No| Matching condition of a media event.| + + +### Example + +``` +import mediaquery from '@ohos.mediaquery' + +let portraitFunc = null + +@Entry +@Component +struct MediaQueryExample { + @State color: string = '#DB7093' + @State text: string = 'Portrait' + listener = mediaquery.matchMediaSync('(orientation: landscape)') + + onPortrait(mediaQueryResult) { + if (mediaQueryResult.matches) { + this.color = '#FFD700' + this.text = 'Landscape' + } else { + this.color = '#DB7093' + this.text = 'Portrait' + } + } + + aboutToAppear() { + portraitFunc = this.onPortrait.bind(this) //bind current js instance + this.listener.on('change', portraitFunc) + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(this.text).fontSize(24).fontColor(this.color) + } + .width('100%').height('100%') + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index 05cd4970141c802aa4577dd02b5b86aafd1603f8..a36fc053da29747df95dcab84468288cd7421acc 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -1,8 +1,8 @@ # missionManager -> **NOTE** -> The initial APIs of this module are supported since API version 8. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. Provides mission management. You can use the APIs to lock, unlock, and clear missions, and switch a mission to the foreground. @@ -18,7 +18,7 @@ import missionManager from '@ohos.application.missionManager' ## missionManager.registerMissionListener -function registerMissionListener(listener: MissionListener): number; +registerMissionListener(listener: MissionListener): number; Registers a listener to observe the mission status. @@ -53,7 +53,7 @@ Registers a listener to observe the mission status. ## missionManager.unregisterMissionListener -function unregisterMissionListener(listenerId: number, callback: AsyncCallback<void>): void; +unregisterMissionListener(listenerId: number, callback: AsyncCallback<void>): void; Unregisters a mission status listener. This API uses an asynchronous callback to return the result. @@ -86,7 +86,7 @@ Unregisters a mission status listener. This API uses an asynchronous callback to ## missionManager.unregisterMissionListener -function unregisterMissionListener(listenerId: number): Promise<void>; +unregisterMissionListener(listenerId: number): Promise<void>; Unregisters a mission status listener. This API uses a promise to return the result. @@ -98,6 +98,12 @@ Unregisters a mission status listener. This API uses a promise to return the res | -------- | -------- | -------- | -------- | | listenerId | number | Yes| Index of the mission status listener to unregister. Each listener has a unique index, which is returned by **registerMissionListener**.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js @@ -110,7 +116,7 @@ Unregisters a mission status listener. This API uses a promise to return the res console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); - await missionManager.unregisterMissionListener(listenerid).catch(function (err){ + missionManager.unregisterMissionListener(listenerid).catch(function (err){ console.log(err); }); ``` @@ -118,7 +124,7 @@ Unregisters a mission status listener. This API uses a promise to return the res ## missionManager.getMissionInfo -function getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; +getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; Obtains the information of a given mission. This API uses an asynchronous callback to return the result. @@ -130,7 +136,7 @@ Obtains the information of a given mission. This API uses an asynchronous callba | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<MissionInfo> | Yes| Callback used to return the mission information obtained.| + | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| **Example** @@ -145,13 +151,13 @@ Obtains the information of a given mission. This API uses an asynchronous callba console.log("mission.timestamp = " + mission.timestamp); console.log("mission.label = " + mission.label); console.log("mission.iconPath = " + mission.iconPath); - } + }); ``` ## missionManager.getMissionInfo -function getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; +getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; Obtains the information of a given mission. This API uses a promise to return the result. @@ -168,14 +174,14 @@ Obtains the information of a given mission. This API uses a promise to return th | Type| Description| | -------- | -------- | - | [MissionInfo](js-apis-application-MissionInfo.md) | Promise used to return the mission information obtained.| + | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var mission = await missionManager.getMissionInfo("", id).catch(function (err){ + var mission = missionManager.getMissionInfo("", id).catch(function (err){ console.log(err); }); ``` @@ -183,7 +189,7 @@ Obtains the information of a given mission. This API uses a promise to return th ## missionManager.getMissionInfos -function getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; +getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; Obtains information of all missions. This API uses an asynchronous callback to return the result. @@ -195,7 +201,7 @@ Obtains information of all missions. This API uses an asynchronous callback to r | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | numMax | number | Yes| Maximum number of missions whose information can be obtained.| - | callback | AsyncCallback<Array<[MissionInfo](js-apis-application-MissionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| + | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| **Example** @@ -212,7 +218,7 @@ Obtains information of all missions. This API uses an asynchronous callback to r ## missionManager.getMissionInfos -function getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; +getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; Obtains information of all missions. This API uses a promise to return the result. @@ -229,14 +235,14 @@ Obtains information of all missions. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Array<MissionInfo> | Promise used to return the array of mission information obtained.| + | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); ``` @@ -244,7 +250,7 @@ Obtains information of all missions. This API uses a promise to return the resul ## missionManager.getMissionSnapShot -function getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; +getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. @@ -279,7 +285,7 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback ## missionManager.getMissionSnapShot -function getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; +getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; Obtains the snapshot of a given mission. This API uses a promise to return the result. @@ -296,20 +302,20 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Type| Description| | -------- | -------- | - | MissionSnapshot | Promise used to return the snapshot information obtained.| + | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - var snapshot = await missionManager.getMissionSnapShot("", id).catch(function (err){ + var snapshot = missionManager.getMissionSnapShot("", id).catch(function (err){ console.log(err); }); ``` @@ -317,7 +323,7 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r ## missionManager.lockMission -function lockMission(missionId: number, callback: AsyncCallback<void>): void; +lockMission(missionId: number, callback: AsyncCallback<void>): void; Locks a given mission. This API uses an asynchronous callback to return the result. @@ -350,7 +356,7 @@ Locks a given mission. This API uses an asynchronous callback to return the resu ## missionManager.lockMission -function lockMission(missionId: number): Promise<void>; +lockMission(missionId: number): Promise<void>; Locks a given mission. This API uses a promise to return the result. @@ -362,19 +368,25 @@ Locks a given mission. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.lockMission(id).catch(function (err){ + missionManager.lockMission(id).catch(function (err){ console.log(err); }); ``` @@ -382,7 +394,7 @@ Locks a given mission. This API uses a promise to return the result. ## missionManager.unlockMission -function unlockMission(missionId: number, callback: AsyncCallback<void>): void; +unlockMission(missionId: number, callback: AsyncCallback<void>): void; Unlocks a given mission. This API uses an asynchronous callback to return the result. @@ -390,9 +402,10 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | missionId | number | Yes| Mission ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -414,7 +427,7 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re ## missionManager.unlockMission -function unlockMission(missionId: number): Promise<void>; +unlockMission(missionId: number): Promise<void>; Unlocks a given mission. This API uses a promise to return the result. @@ -426,22 +439,28 @@ Unlocks a given mission. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.lockMission(id).catch(function (err){ + missionManager.lockMission(id).catch(function (err){ console.log(err); }); - await missionManager.unlockMission(id).catch(function (err){ + missionManager.unlockMission(id).catch(function (err){ console.log(err); }); ``` @@ -449,7 +468,7 @@ Unlocks a given mission. This API uses a promise to return the result. ## missionManager.clearMission -function clearMission(missionId: number, callback: AsyncCallback<void>): void; +clearMission(missionId: number, callback: AsyncCallback<void>): void; Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. @@ -482,7 +501,7 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy ## missionManager.clearMission -function clearMission(missionId: number): Promise<void>; +clearMission(missionId: number): Promise<void>; Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. @@ -494,19 +513,25 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.clearMission(id).catch(function (err){ + missionManager.clearMission(id).catch(function (err){ console.log(err); }); ``` @@ -514,7 +539,7 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom ## missionManager.clearAllMissions -function clearAllMissions(callback: AsyncCallback<void>): void; +clearAllMissions(callback: AsyncCallback<void>): void; Clears all unlocked missions. This API uses an asynchronous callback to return the result. @@ -533,17 +558,23 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t ## missionManager.clearAllMissions -function clearAllMissions(): Promise<void>; +clearAllMissions(): Promise<void>; Clears all unlocked missions. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - await missionManager.clearAllMissions().catch(function (err){ + missionManager.clearAllMissions().catch(function (err){ console.log(err); }); ``` @@ -551,7 +582,7 @@ Clears all unlocked missions. This API uses a promise to return the result. ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; +moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. @@ -584,7 +615,7 @@ Switches a given mission to the foreground. This API uses an asynchronous callba ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; +moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; Switches a given mission to the foreground, with the startup parameters for the switch specified, such as the window mode and device ID. This API uses an asynchronous callback to return the result. @@ -618,9 +649,9 @@ Switches a given mission to the foreground, with the startup parameters for the ## missionManager.moveMissionToFront -function moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; +moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; -Switches a given mission to the foreground. This API uses a promise to return the result. +Switches a given mission to the foreground, with the startup parameters for the switch specified, such as the window mode and device ID. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -631,19 +662,42 @@ Switches a given mission to the foreground. This API uses a promise to return th | missionId | number | Yes| Mission ID.| | options | StartOptions | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js import missionManager from '@ohos.application.missionManager' - var allMissions = await missionManager.getMissionInfos("", 10).catch(function (err){ + var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ console.log(err); }); console.log("size = " + allMissions.length); console.log("missions = " + JSON.stringify(allMissions)); var id = allMissions[0].missionId; - await missionManager.moveMissionToFront(id).catch(function (err){ + missionManager.moveMissionToFront(id).catch(function (err){ console.log(err); }); ``` + +## MissionInfo + +Describes the mission information. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-featureAbility.md#want) | Yes| Yes| **Want** information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission is continuable.| diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index c0d9c297f77b71cff69ee91d920e0721ea93725d..bd4404ebc0f7c9e74a5e67dd302b6f867089ccf6 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -684,83 +684,14 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | ------ | ------ | ------------------------- | | netId | number | Network ID. The value must be greater than or equal to 100.| -### bindSocket - -bindSocket(socketParam: TCPSocket | UDPSocket, callback: AsyncCallback<void>): void - -Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | ---------------- | -| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - -``` -// Bind the TCPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let tcpSocket = socket.constructTCPSocketInstance() - netHandle.bindSocket(tcpSocket, (function (error) { - console.log(JSON.stringify(error)) - })) -}) -// Bind the UDPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let udpSocket = socket.constructUDPSocketInstance() - netHandle.bindSocket(udpSocket, (function (error) { - console.log(JSON.stringify(error)) - })) -}) -``` - - -### bindSocket - -bindSocket(socketParam: TCPSocket | UDPSocket): Promise<void> - -Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses a promise to return the result. - -**System capability**: SystemCapability.Communication.NetManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| socketParam | TCPSocket \| UDPSocket | Yes | **TCPSocket** or **UDPSocket** object.| - -**Return Value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -``` -// Bind the TCPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let tcpSocket = socket.constructTCPSocketInstance() - netHandle.bindSocket(tcpSocket).then(function () { - console.log("bind socket success") - }) -}) -// Bind the UDPSocket object. -connection.getDefaultNet().then(function (netHandle) { - let udpSocket = socket.constructUDPSocketInstance() - netHandle.bindSocket(udpSocket).then(function () { - console.log("bind socket success") - }) -}) -``` - ### getAddressesByName getAddressesByName(host: string, callback: AsyncCallback\>): void Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -788,6 +719,8 @@ getAddressesByName(host: string): Promise\> Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -819,6 +752,8 @@ getAddressByName(host: string, callback: AsyncCallback\): void Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -846,6 +781,8 @@ getAddressByName(host: string): Promise\ Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result. +**Required permission**: ohos.permission.GET_NETWORK_INFO + **System capability**: SystemCapability.Communication.NetManager.Core **Parameters** @@ -893,7 +830,7 @@ Defines the network capability set. | linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.| | linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.| | networkCap | Array<[NetCap](#netcap)> | Network capability. | -| bearerTypes | Array<[NetBearType](#netbearType)> | Network type. | +| bearerTypes | Array<[NetBearType](#netbeartype)> | Network type. | ## NetCap @@ -971,4 +908,4 @@ Defines the network address. | ------- | ------ | ------------------------------ | | address | string | Network address. | | family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| -| port | number | Port number. The value ranges from **0** to **65535**. | +| port | number | Port number. The value ranges from **0** to **65535**. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 14f043f8b325b4a4c20aca3a4686879e99d6213d..2760d6c9cb83edb56537d1b022e87ae25eb338dd 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,10 +1,7 @@ -# Notification Module - - -## Required Permissions - -None +# Notification +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,152 +9,22 @@ None import Notification from '@ohos.notification'; ``` -## System Capabilities - -```js -SystemCapability.Notification.Notification -``` - -## Notification.publish(request: NotificationRequest, callback: AsyncCallback\) - -- Functionality - - Publishes a notification. This method uses a callback to return the result. - -- Parameters - - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------------------------- | -| request | Read-only| NotificationRequest | Yes| Notification to publish.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| - -- NotificationRequest - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------------- | -------- | --------------------------------------------- | ---- | -------------------------- | -| content | Readable and writable| NotificationContent | Yes| Notification content.| -| id | Readable and writable| number | No| Notification ID.| -| slotType | Readable and writable| SlotType | No| Notification slot type.| -| isOngoing | Readable and writable| boolean | No| Whether the notification is an ongoing notification.| -| isUnremovable | Readable and writable| boolean | No| Whether the notification can be removed.| -| deliveryTime | Readable and writable| number | No| Time when the notification is sent.| -| tapDismissed | Readable and writable| boolean | No| Whether the notification can be automatically cleared.| -| autoDeletedTime | Readable and writable| number | No| Time when the notification is automatically cleared.| -| wantAgent | Readable and writable| WantAgent | No| **WantAgent** object to which the notification will be redirected after being clicked.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extended parameter.| -| color | Readable and writable| number | No| Background color of the notification.| -| colorEnabled | Readable and writable| boolean | No| Whether the notification background color is enabled.| -| isAlertOnce | Readable and writable| boolean | No| Whether the notification triggers an alert only once.| -| isStopwatch | Readable and writable| boolean | No| Whether to display the stopwatch.| -| isCountDown | Readable and writable| boolean | No| Whether to display the countdown time.| -| isFloatingIcon | Readable and writable| boolean | No| Whether the notification is displayed as a floating icon.| -| label | Readable and writable| string | No| Notification label.| -| badgeIconStyle | Readable and writable| number | No| Notification badge type.| -| showDeliveryTime | Readable and writable| boolean | No| Whether to display the time when the notification is delivered.| -| actionButtons | Readable and writable| Array\ | No| Buttons in the notification. Up to two buttons are allowed.| -| smallIcon | Readable and writable| PixelMap | No| Small notification icon.| -| largeIcon | Readable and writable| PixelMap | No| Large notification icon.| -| creatorBundleName | Read-only| string | No| Name of the bundle that creates the notification.| -| creatorUid | Read-only| number | No| UID of the notification creator.| -| creatorPid | Read-only| number | No| PID of the notification creator.| -| hashCode | Read-only| string | No| Unique ID of the notification.| -| classification | Readable and writable| string | No| Notification category.| -| groupName | Readable and writable| string | No| Notification group name.| -| template8+ | Readable and writable| [NotificationTemplate](#notificationtemplate) | No| Notification template.| - -NotificationContent +## Notification.publish -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | ---------------------------- | ---- | ------------------ | -| contentType | Readable and writable| ContentType | Yes| Notification content type.| -| normal | Readable and writable| NotificationBasicContent | No| Normal text.| -| longText | Readable and writable| NotificationLongTextContent | No| Long text.| -| multiLine | Readable and writable| NotificationMultiLineContent | No| Multi-line text.| -| picture | Readable and writable| NotificationPictureContent | No| Picture-attached.| +publish(request: NotificationRequest, callback: AsyncCallback\): void -- ContentType +Publishes a notification. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Description| -| --------------------------------- | -------- | ----------- | ---------------- | -| NOTIFICATION_CONTENT_BASIC_TEXT | Read-only| ContentType | Normal text notification.| -| NOTIFICATION_CONTENT_LONG_TEXT | Read-only| ContentType | Long text notification.| -| NOTIFICATION_CONTENT_PICTURE | Read-only| ContentType | Picture-attached notification.| -| NOTIFICATION_CONTENT_CONVERSATION | Read-only| ContentType | Conversation notification.| -| NOTIFICATION_CONTENT_MULTILINE | Read-only| ContentType | Multi-line text notification.| +**System capability**: SystemCapability.Notification.Notification -- NotificationBasicContent +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------ | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | -- NotificationLongTextContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------ | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| longText | Readable and writable| string | Yes| Long text content of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| - -- NotificationMultiLineContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | --------------- | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| longTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| -| lines | Readable and writable| Array\ | Yes| Multi-line content.| - -- NotificationPictureContent - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | -------------- | ---- | -------------------------------- | -| title | Readable and writable| string | Yes| Notification title.| -| text | Readable and writable| string | Yes| Notification content.| -| additionalText | Readable and writable| string | Yes| Additional information of the notification.| -| briefText | Readable and writable| string | Yes| Brief text of the notification.| -| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| -| picture | Readable and writable| image.PixelMap | Yes| Picture included in the notification.| - -- SlotType - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------------- | -------- | -------- | ---- | -------- | -| SOCIAL_COMMUNICATION | Read-only| SlotType | No| Notification slot for social communication.| -| SERVICE_INFORMATION | Read-only| SlotType | No| Notification slot for service information.| -| CONTENT_INFORMATION | Read-only| SlotType | No| Notification slot for content consultation.| -| OTHER_TYPES | Read-only| SlotType | No| Notification slot for other purposes.| - -- NotificationActionButton - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ------------------------- | -| title | Readable and writable| string | Yes| Button title.| -| wantAgent | Readable and writable| wantAgent | Yes| **WantAgent** of the button.| -| extras | Readable and writable| Array\ | No| Extra information of the button.| -| icon | Readable and writable| image.PixelMap | No| Button icon.| -| userInput | Readable and writable| NotificationUserInput | No| User input object.| - -- NotificationUserInput - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------ | ---- | ----------------------------- | -| inputKey | Readable and writable| string | Yes| Key to identify the user input.| - - -- Return value - - void - -- Example +**Example** ```js // publish callback @@ -168,7 +35,7 @@ function publishCallback(err) { var notificationRequest = { id: 1, content: { - contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -181,24 +48,22 @@ Notification.publish(notificationRequest, publishCallback) -## Notification.publish(request: NotificationRequest) - -- Functionality +## Notification.publish - Publishes a notification. This method uses a promise to return the result. +publish(request: NotificationRequest): Promise\ -- Return value +Publishes a notification. This API uses a promise to return the result. - Promise\ +**System capability**: SystemCapability.Notification.Notification -- Example +**Example** ```js // NotificationRequest object var notificationRequest = { notificationId: 1, content: { - contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "test_title", text: "test_text", @@ -206,33 +71,107 @@ var notificationRequest = { } } } -Notification.publish(notificationRequest).then((void) => { +Notification.publish(notificationRequest).then(() => { console.info("==========================>publishCallback=======================>"); }); ``` +## Notification.publish8+ + +publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void + +Publishes a notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| userId | Yes | No |number | Yes | ID of the user who receives the notification. | +| callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +// publish callback +function publishCallback(err) { + console.info("==========================>publishCallback=======================>"); +} +// ID of the user who receives the notification. +var userId = 1 +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest, userId, publishCallback); +``` + +## Notification.publish8+ + +publish(request: NotificationRequest, userId: number): Promise\ + +Publishes a notification. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| userId | Yes | No |number | Yes | ID of the user who receives the notification. | + +**Example** + +```js +var notificationRequest = { + notificationId: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +var userId = 1 +Notification.publish(notificationRequest, userId).then(() => { + console.info("==========================>publishCallback=======================>"); +}); +``` -## Notification.cancel(id: number, label: string, callback: AsyncCallback\) -- Functionality +## Notification.cancel - Cancels a notification with the specified ID and label. This method uses a callback to return the result. +cancel(id: number, label: string, callback: AsyncCallback\): void -- Parameters +Cancels a notification with the specified ID and label. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| id | Read-only| number | Yes| Notification ID.| -| label | Read-only| string | Yes| Notification label.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | --- | ---- | --------------------- | ---- | -------------------- | +| id | Yes | No | number | Yes | Notification ID. | +| label | Yes | No | string | Yes | Notification label. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js // cancel callback @@ -244,51 +183,47 @@ Notification.cancel(0, "label", cancelCallback) -## Notification.cancel(id: number, label? : string) - -- Functionality +## Notification.cancel - Cancels a notification with the specified ID and label. This method uses a promise to return the result. +cancel(id: number, label?: string): Promise\ -- Parameters +Cancels a notification with the specified ID and label. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------ | ---- | -------- | -| id | Read-only| number | Yes| Notification ID.| -| label | Read-only| string | No| Notification label.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | --- | ---- | ------ | ---- | -------- | +| id | Yes | No | number | Yes | Notification ID. | +| label | Yes | No | string | No | Notification label.| -- Example +**Example** ```js -Notification.cancel(0).then((void) => { +Notification.cancel(0).then(() => { console.info("==========================>cancelCallback=======================>"); }); ``` -## Notification.cancel(id: number, callback: AsyncCallback\) +## Notification.cancel -- Functionality +cancel(id: number, callback: AsyncCallback\): void - Cancels a notification with the specified ID. This method uses a callback to return the result. +Cancels a notification with the specified ID. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| id | Read-only| number | Yes| Notification ID.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| id | Yes | No | number | Yes | Notification ID. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js // cancel callback @@ -300,92 +235,66 @@ Notification.cancel(0, cancelCallback) -## Notification.cancelAll(callback: AsyncCallback\) - -- Functionality +## Notification.cancelAll - Cancels all notifications. This method uses a callback to return the result. +cancelAll(callback: AsyncCallback\): void -- Parameters +Cancels all notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js // cancel callback -function cancelAllback(err) { - console.info("==========================>cancelAllback=======================>"); +function cancelAllCallback(err) { + console.info("==========================>cancelAllCallback=======================>"); } -Notification.cancelAll(cancelCallback) +Notification.cancelAll(cancelAllCallback) ``` -## Notification.cancelAll() - -- Functionality - - Cancels all notifications. This method uses a promise to return the result. +## Notification.cancelAll -- Parameters +cancelAll(): Promise\ - None +Cancels all notifications. This API uses a promise to return the result. -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ - -- Example +**Example** ```js -Notification.cancelAll().then((void) => { - console.info("==========================>cancelAllback=======================>"); +Notification.cancelAll().then(() => { + console.info("==========================>cancelAllCallback=======================>"); }); ``` -## Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\) - -- Functionality - - Adds a notification slot. This method uses a callback to return the result. - -- Parameters +## Notification.addSlot -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +addSlot(slot: NotificationSlot, callback: AsyncCallback\): void -- NotificationSlot +Adds a notification slot. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------------- | -------- | --------------- | ---- | ------------------------------------------ | -| type | Readable and writable| SlotType | Yes| Notification slot type.| -| level | Readable and writable| number | No| Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Readable and writable| string | No| Description of the notification slot.| -| badgeFlag | Readable and writable| boolean | No| Whether to display the badge.| -| bypassDnd | Readable and writable| boolean | No| Whether to bypass the system do-not-disturb (DND) setting.| -| lockscreenVisibility | Readable and writable| boolean | No| How the notification is displayed on the locked screen.| -| vibrationEnabled | Readable and writable| boolean | No| Whether vibration is enabled for the notification.| -| sound | Readable and writable| string | No| Notification sound.| -| lightEnabled | Readable and writable| boolean | No| Whether light is enabled for the notification.| -| lightColor | Readable and writable| number | No| Notification light color.| -| vibrationValues | Readable and writable| Array\ | No| Notification vibration mode.| +**System capability**: SystemCapability.Notification.Notification -* Return values +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -* Example +**Example** ```js // addSlot callback @@ -401,54 +310,50 @@ Notification.addSlot(notificationSlot, addSlotCallBack) -## Notification.addSlot(slot: NotificationSlot) +## Notification.addSlot -- Functionality +addSlot(slot: NotificationSlot): Promise\ - Adds a notification slot. This method uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ---------------- | ---- | -------------------- | -| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | ---------------- | ---- | -------------------- | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| - Promise\ - -- Example +**Example** ```js // NotificationSlot object var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -Notification.addSlot(notificationSlot).then((void) => { +Notification.addSlot(notificationSlot).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.addSlot(type: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.addSlot - Adds a notification slot. This method uses a callback to return the result. +addSlot(type: SlotType, callback: AsyncCallback\): void -- Parameters +Adds a notification slot. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------- | -| type | Read-only| SlotType | Yes| Type of the notification slot to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // addSlot callback @@ -460,50 +365,46 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack -## Notification.addSlot(type: SlotType) +## Notification.addSlot -- Functionality +addSlot(type: SlotType): Promise\ - Adds a notification slot. This method uses a promise to return the result. +Adds a notification slot. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | -------- | ---- | ---------------------- | -| type | Read-only| SlotType | Yes| Type of the notification slot to add.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | -------- | ---- | ---------------------- | +| type | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot to add.| - Promise\ - -- Example +**Example** ```js -Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then((void) => { +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.addSlots(slots: Array\, callback: AsyncCallback\) - -- Functionality +## Notification.addSlots - Adds multiple notification slots. This method uses a callback to return the result. +addSlots(slots: Array\, callback: AsyncCallback\): void -- Parameters +Adds multiple notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------- | ---- | ------------------------ | -| slots | Read-only| Array\ | Yes| Notification slots to add.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------- | ---- | ------------------------ | +| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // addSlots callback @@ -515,31 +416,29 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } // NotificationSlotArray object -var notificationSlotArray = new Array(); -notificationSlotArray[0] = notificationSlot; +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray, addSlotsCallBack) ``` -## Notification.addSlots(slots: Array\) +## Notification.addSlots -- Functionality +addSlots(slots: Array\): Promise\ - Adds multiple notification slots. This method uses a promise to return the result. +Adds multiple notification slots. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------------------------- | ---- | ------------------------ | -| slots | Read-only| Array\ | Yes| Notification slots to add.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | ---- | --- | ------------------------- | ---- | ------------------------ | +| slots | Yes | No | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| - Promise\ - -- Example +**Example** ```js // NotificationSlot object @@ -547,34 +446,32 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } // NotificationSlotArray object -var notificationSlotArray = new Array(); -notificationSlotArray[0] = notificationSlot; +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; -Notification.addSlots(notificationSlotArray).then((void) => { +Notification.addSlots(notificationSlotArray).then(() => { console.info("==========================>addSlotCallback=======================>"); }); ``` -## Notification.getSlot(slotType: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.getSlot - Obtains a notification slot of the specified type. This method uses a callback to return the result. +getSlot(slotType: SlotType, callback: AsyncCallback\): void -- Parameters +Obtains a notification slot of the specified type. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | -- Example +**Example** ```js // getSlot callback @@ -587,23 +484,27 @@ Notification.getSlot(slotType, getSlotCallback) -## Notification.getSlot(slotType) +## Notification.getSlot -- Functionality +getSlot(slotType: SlotType): Promise\ - Obtains a notification slot of the specified type. This method uses a promise to return the result. +Obtains a notification slot of the specified type. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | -| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| - Promise\ +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; @@ -614,23 +515,21 @@ Notification.getSlot(slotType).then((data) => { -## Notification.getSlots(callback: AsyncCallback>) - -- Functionality +## Notification.getSlots - Obtains all notification slots. This method uses a callback to return the result. +getSlots(callback: AsyncCallback>): void -- Parameters +Obtains all notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result.| -- Example +**Example** ```js // getSlots callback @@ -642,21 +541,21 @@ Notification.getSlots(getSlotsCallback) -## Notification.getSlots() +## Notification.getSlots -- Functionality +getSlots(): Promise\> - Obtains all notification slots of the current application. This method uses a promise to return the result. +Obtains all notification slots of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getSlots().then((data) => { @@ -666,24 +565,22 @@ Notification.getSlots().then((data) => { -## Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\) - -- Functionality +## Notification.removeSlot - Removes a notification slot of the specified type. This method uses a callback to return the result. +removeSlot(slotType: SlotType, callback: AsyncCallback\): void -- Parameters +Removes a notification slot of the specified type. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ----------------------------------------------------------- | -| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result. | -- Example +**Example** ```js // removeSlot callback @@ -696,50 +593,46 @@ Notification.removeSlot(slotType,removeSlotCallback) -## Notification.removeSlot(slotType: SlotType) +## Notification.removeSlot -- Functionality +removeSlot(slotType: SlotType): Promise\ - Removes a notification slot of the specified type. This method uses a promise to return the result. +Removes a notification slot of the specified type. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | -| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | -------- | ---- | ----------------------------------------------------------- | +| slotType | Yes | No | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| - Promise\ - -- Example +**Example** ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; -Notification.removeSlot(slotType).then((void) => { +Notification.removeSlot(slotType).then(() => { console.info("==========================>removeSlotCallback=======================>"); }); ``` -## Notification.removeAllSlots(callback: AsyncCallback\) - -- Functionality +## Notification.removeAllSlots - Removes all notification slots. This method uses a callback to return the result. +removeAllSlots(callback: AsyncCallback\): void -- Parameters +Removes all notification slots. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeAllCallBack(err) { @@ -750,111 +643,41 @@ Notification.removeAllSlots(removeAllCallBack) -## Notification.removeAllSlots() +## Notification.removeAllSlots -- Functionality +removeAllSlots(): Promise\ - Removes all notification slots. This method uses a promise to return the result. +Removes all notification slots. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None - -- Return value - - Promise\ - -- Example +**Example** ```js -Notification.removeAllSlots().then((void) => { +Notification.removeAllSlots().then(() => { console.info("==========================>removeAllCallBack=======================>"); }); ``` -## Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\) - -- Functionality +## Notification.subscribe - Subscribes to a notification with the subscription information specified. This method uses a callback to return the result. +subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void -- Parameters +Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------- | ---- | ---------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| info | Read-only| NotificationSubscribeInfo | Yes| Subscription information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- NotificationSubscriber +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------------------------------------------------------------ | -------- | -------- | ---- | -------------------------- | -| onConsume?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for receiving notifications.| -| onCancel?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for canceling notifications.| -| onUpdate?:(data: NotificationSortingMap) | Readable and writable| function | No| Callback for notification sorting updates.| -| onConnect?:() | Readable and writable| function | No| Callback for subscription.| -| onDisconnect?:() | Readable and writable| function | No| Callback for unsubscription.| -| onDestroy?:() | Readable and writable| function | No| Callback for service destruction.| -| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) | Readable and writable| function | No| Callback for DND time setting updates.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ------------------------- | ---- | ---------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Subscription information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- SubscribeCallbackData - -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | ---------------------- | ---- | -------- | -| request | Read-only| NotificationRequest | Yes| Notification content.| -| sortingMap | Read-only| NotificationSortingMap | No| Notification sorting information.| -| reason | Read-only| number | No| Reason for deletion.| -| sound | Read-only| string | No| Sound used for notification.| -| vibrationValues | Read-only| Array\ | No| Vibration used for notification.| - -- NotificationSortingMap - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------------------------------------ | ---- | ---------------- | -| sortings | Read-only| {[key: string]: NotificationSorting} | Yes| Array of notification sorting information.| -| sortedHashCode | Read-only| Array\ | Yes| Array of unique notification IDs.| - -- NotificationSorting - -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------- | ---- | ------------ | -| slot | Read-only| NotificationSlot | Yes| Notification slot.| -| hashCode | Read-only| string | Yes| Unique ID of the notification.| -| ranking | Read-only| number | Yes| Notification sequence number.| - -- DoNotDisturbType - - -| Name| Readable/Writable| Type| Description| -| ------------ | -------- | --------------------- | ---------------------------------------- | -| TYPE_NONE | Read-only| enum DoNotDisturbType | Non-DND.| -| TYPE_ONCE | Read-only| enum DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute)| -| TYPE_DAILY | Read-only| enum DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute)| -| TYPE_CLEARLY | Read-only| enum DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute)| - -- DoNotDisturbDate - -| Name| Readable/Writable| Type| Description| -| ----- | -------- | ---------------- | ------------------------ | -| type | Readable and writable| DoNotDisturbType | DND time type.| -| begin | Readable and writable| Date | DND start time.| -| end | Readable and writable| Date | DND end time.| - -- NotificationSubscribeInfo - -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | --------------- | ---- | ------------------------------- | -| bundleNames | Readable and writable| Array\ | No| Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Readable and writable| number | No| User whose notifications are to be subscribed to.| - -- Return value - - void - -- Example +**Example** ```js // subscribe callback @@ -875,24 +698,22 @@ Notification.subscribe(subscriber, info, subscribeCallback); -## Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) - -- Functionality +## Notification.subscribe - Subscribes to a notification. This method uses a callback to return the result. +subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -- Parameters +Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | ---------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | ---------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function subscribeCallback(err) { @@ -909,24 +730,22 @@ Notification.subscribe(subscriber, subscribeCallback); -## Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) +## Notification.subscribe -- Functionality +subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise\ - Subscribes to a notification with the subscription information specified. This method uses a promise to return the result. +Subscribes to a notification with the subscription information specified. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------- | ---- | ------------ | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| info | Read-only| NotificationSubscribeInfo | No| Subscription information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ------------------------- | ---- | ------------ | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| info | Yes | No | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Subscription information. | - Promise\ - -- Example +**Example** ```js function onConsumeCallback(err, data) { @@ -935,31 +754,29 @@ function onConsumeCallback(err, data) { var subscriber = { onConsume: onConsumeCallback }; -Notification.subscribe(subscriber).then((void) => { +Notification.subscribe(subscriber).then(() => { console.info("==========================>subscribeCallback=======================>"); }); ``` -## Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) - -- Functionality +## Notification.unsubscribe - Unsubscribes from a notification. This method uses a callback to return the result. +unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -- Parameters +Unsubscribes from a notification. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | -------------------- | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | -------------------- | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function unsubscribeCallback(err) { @@ -976,23 +793,21 @@ Notification.unsubscribe(subscriber, unsubscribeCallback); -## Notification.unsubscribe(subscriber: NotificationSubscriber) +## Notification.unsubscribe -- Functionality +unsubscribe(subscriber: NotificationSubscriber): Promise\ - Unsubscribes from a notification. This method uses a promise to return the result. +Unsubscribes from a notification. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ---------------------- | ---- | ------------ | -| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------- | ---- | --- | ---------------------- | ---- | ------------ | +| subscriber | Yes | No | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| - Promise\ - -- Example +**Example** ```js function onConsumeCallback(err, data) { @@ -1001,133 +816,125 @@ function onConsumeCallback(err, data) { var subscriber = { onConsume: onConsumeCallback }; -Notification.unsubscribe(subscriber).then((void) => { +Notification.unsubscribe(subscriber).then(() => { console.info("==========================>unsubscribeCallback=======================>"); }); ``` -## Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) - -- Functionality +## Notification.enableNotification - Sets whether to enable notification for a specified bundle. This method uses a callback to return the result. +enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -- Parameters +Sets whether to enable notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to enable notification.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- BundleOption +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------ | ---- | ------ | -| bundle | Readable and writable| string | Yes| Bundle name.| -| uid | Readable and writable| number | No| User ID.| -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function enableNotificationCallback(err) { console.info("==========================>enableNotificationCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.enableNotification(bundle, false, enableNotificationCallback); ``` -## Notification.enableNotification(bundle: BundleOption, enable: boolean) - -- Functionality +## Notification.enableNotification - Sets whether to enable notification for a specified bundle. This method uses a promise to return the result. +enableNotification(bundle: BundleOption, enable: boolean): Promise\ -- Parameters +Sets whether to enable notification for a specified bundle. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to enable notification.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | Yes | No | boolean | Yes | Whether to enable notification. | -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } -Notification.enableNotification(bundle, false).then((void) => { +Notification.enableNotification(bundle, false).then(() => { console.info("==========================>enableNotificationCallback=======================>"); }); ``` -## Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\) +## Notification.isNotificationEnabled -- Functionality +isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void - Checks whether notification is enabled for a specified bundle. This method uses a callback to return the result. +Checks whether notification is enabled for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function isNotificationEnabledCallback(err, data) { console.info("==========================>isNotificationEnabledCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); ``` -## Notification.isNotificationEnabled(bundle: BundleOption) +## Notification.isNotificationEnabled + +isNotificationEnabled(bundle: BundleOption): Promise\ -- Functionality +Checks whether notification is enabled for a specified bundle. This API uses a promise to return the result. - Checks whether notification is enabled for a specified bundle. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -- Return value +**Return value** - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { console.info("==========================>isNotificationEnabledCallback=======================>"); @@ -1136,23 +943,21 @@ Notification.isNotificationEnabled(bundle).then((data) => { -## Notification.isNotificationEnabled(callback: AsyncCallback\) - -- Functionality +## Notification.isNotificationEnabled - Checks whether notification is enabled for the current application. This method uses a callback to return the result. +isNotificationEnabled(callback: AsyncCallback\): void -- Parameters +Checks whether notification is enabled for this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function isNotificationEnabledCallback(err, data) { @@ -1164,21 +969,27 @@ Notification.isNotificationEnabled(isNotificationEnabledCallback); -## Notification.isNotificationEnabled() +## Notification.isNotificationEnabled -- Functionality +isNotificationEnabled(): Promise\ - Checks whether notification is enabled for the current application. This method uses a promise to return the result. +Checks whether notification is enabled for this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise\ +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js Notification.isNotificationEnabled().then((data) => { @@ -1188,120 +999,118 @@ Notification.isNotificationEnabled().then((data) => { -## Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) +## Notification.displayBadge -- Functionality +displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void - Sets whether to display the badge in notifications for a specified bundle. This method uses a callback to return the result. +Sets whether to enable the notification badge for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to display the badge.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| enable | Yes | No | boolean | Yes | Whether to enable notification. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function displayBadgeCallback(err) { console.info("==========================>displayBadgeCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.displayBadge(bundle, false, displayBadgeCallback); ``` -## Notification.displayBadge(bundle: BundleOption, enable: boolean) - -- Functionality +## Notification.displayBadge - Sets whether to display the badge in notifications for a specified bundle. This method uses a promise to return the result. +displayBadge(bundle: BundleOption, enable: boolean): Promise\ -- Parameters +Sets the notification slot for a specified bundle. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| enable | Read-only| boolean | Yes| Whether to display the badge.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| enable | Yes | No | boolean | Yes | Whether to enable notification. | -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } -Notification.displayBadge(bundle, false).then((void) => { +Notification.displayBadge(bundle, false).then(() => { console.info("==========================>displayBadgeCallback=======================>"); }); ``` -## Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\) +## Notification.isBadgeDisplayed -- Functionality +isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void - Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a callback to return the result. +Checks whether the notification badge is enabled for a specified bundle. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------ | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ------------------------ | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function isBadgeDisplayedCallback(err, data) { console.info("==========================>isBadgeDisplayedCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); ``` -## Notification.isBadgeDisplayed(bundle: BundleOption) +## Notification.isBadgeDisplayed + +isBadgeDisplayed(bundle: BundleOption): Promise\ -- Functionality +Checks whether the notification badge is enabled for a specified bundle. This API uses a promise to return the result. - Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| -- Return value +**Return value** - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { console.info("==========================>isBadgeDisplayedCallback=======================>"); @@ -1310,32 +1119,30 @@ Notification.isBadgeDisplayed(bundle).then((data) => { -## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\) - -- Functionality +## Notification.setSlotByBundle - Sets a notification slot for a specified bundle. This method uses a callback to return the result. +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void -- Parameters +Sets the notification slot for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| slot | Read-only| NotificationSlot | Yes| Notification slot.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function setSlotByBundleCallback(err) { console.info("==========================>setSlotByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION @@ -1345,91 +1152,91 @@ Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); -## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) +## Notification.setSlotByBundle -- Functionality +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ - Sets a notification slot for a specified bundle. This method uses a promise to return the result. +Sets the notification slot for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| slot| Read-only| NotificationSlot| Yes| Notification slot.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Whether to enable notification. | - Promise\ - -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } -Notification.displayBadge(bundle, notificationSlot).then((void) => { +Notification.displayBadge(bundle, notificationSlot).then(() => { console.info("==========================>setSlotByBundleCallback=======================>"); }); ``` -## Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>) - -- Functionality +## Notification.getSlotsByBundle - Obtains the notification slots of a specified bundle. This method uses a callback to return the result. +getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void -- Parameters +Obtains the notification slots of a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------------------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------------------------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| -- Example +**Example** ```js function getSlotsByBundleCallback(err, data) { console.info("==========================>getSlotsByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); ``` -## Notification.getSlotsByBundle(bundle: BundleOption) +## Notification.getSlotsByBundle -- Functionality +getSlotsByBundle(bundle: BundleOption): Promise> - Obtains the notification slots of a specified bundle. This method uses a promise to return the result. +Obtains the notification slots of a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise> +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise> | Promise used to return the result.| + +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { console.info("==========================>getSlotsByBundleCallback=======================>"); @@ -1438,58 +1245,60 @@ Notification.getSlotsByBundle(bundle).then((data) => { -## Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\) - -- Functionality +## Notification.getSlotNumByBundle - Obtains the number of notification slots of a specified bundle. This method uses a callback to return the result. +getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void -- Parameters +Obtains the number of notification slots of a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------- | ---- | ---------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------- | ---- | ---------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function getSlotNumByBundle(err, data) { console.info("==========================>getSlotNumByBundleCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); ``` -## Notification.getSlotNumByBundle(bundle: BundleOption) +## Notification.getSlotNumByBundle -- Functionality +getSlotNumByBundle(bundle: BundleOption): Promise\ - Obtains the number of notification slots of a specified bundle. This method uses a promise to return the result. +Obtains the number of notification slots of a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| - Promise\ +**Return value** -- Example +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { console.info("==========================>getSlotNumByBundleCallback=======================>"); @@ -1498,101 +1307,88 @@ Notification.getSlotNumByBundle(bundle).then((data) => { -## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\) - -- Functionality +## Notification.remove - Removes a notification for a specified bundle. This method uses a callback to return the result. +remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\): void -- Parameters +Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | --------------------- | ---- | -------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| notificationKey | Read-only| NotificationKey | Yes| Notification key.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- NotificationKey +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | ------ | ---- | -------- | -| id | Readable and writable| number | Yes| Notification ID.| -| label | Readable and writable| string | No| Notification label.| +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | ----------------------------------- | ---- | -------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Return value - - void - -- Example +**Example** ```js function removeCallback(err) { console.info("==========================>removeCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationKey = { - id: 0; - label: "label"; + id: 0, + label: "label", } Notification.remove(bundle, notificationKey, removeCallback); ``` -## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) +## Notification.remove -- Functionality +remove(bundle: BundleOption, notificationKey: NotificationKey): Promise\ - Removes a notification for a specified bundle. This method uses a promise to return the result. +Removes a notification for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------------- | -------- | --------------- | ---- | ---------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| notificationKey | Read-only| NotificationKey | Yes| Notification key.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | --------------- | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information.| +| notificationKey | Yes | No | [NotificationKey](#notificationkey) | Yes | Notification key. | - Promise\ - -- Example +**Example** ```js var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } var notificationKey = { - id: 0; - label: "label"; + id: 0, + label: "label", } -Notification.remove(bundle, notificationKey).then((void) => { +Notification.remove(bundle, notificationKey).then(() => { console.info("==========================>removeCallback=======================>"); }); ``` -## Notification.remove(hashCode: string, callback: AsyncCallback\) - -- Functionality +## Notification.remove - Removes a notification. This method uses a callback to return the result. +remove(hashCode: string, callback: AsyncCallback\): void -- Parameters +Removes a notification for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| hashCode | Read-only| string | Yes| Unique notification ID.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| hashCode | Yes | No | string | Yes | Unique notification ID. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeCallback(err) { @@ -1604,80 +1400,74 @@ Notification.remove(hashCode, removeCallback); -## Notification.remove(hashCode: string) +## Notification.remove -- Functionality +remove(hashCode: string): Promise\ - Removes a notification. This method uses a promise to return the result. +Removes a notification for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------- | ---- | ---------- | -| hashCode | Read-only| string | Yes| Unique notification ID.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------- | ---- | ---------- | +| hashCode | Yes | No | string | Yes | Unique notification ID.| - Promise\ - -- Example +**Example** ```js -Notification.remove(hashCode).then((void) => { +Notification.remove(hashCode).then(() => { console.info("==========================>removeCallback=======================>"); }); ``` -## Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\) - -- Functionality +## Notification.removeAll - Removes all notifications for a specified bundle. This method uses a callback to return the result. +removeAll(bundle: BundleOption, callback: AsyncCallback\): void -- Parameters +Removes all notifications for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeAllCallback(err) { console.info("==========================>removeAllCallback=======================>"); } var bundle = { - bundle: "bundleName1"; + bundle: "bundleName1", } Notification.removeAll(bundle, removeAllCallback); ``` -## Notification.removeAll(callback: AsyncCallback\) +## Notification.removeAll -- Functionality +removeAll(callback: AsyncCallback\): void - Removes all notifications. This method uses a callback to return the result. +Removes all notifications. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | -------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| - void - -- Example +**Example** ```js function removeAllCallback(err) { @@ -1689,49 +1479,97 @@ Notification.removeAll(removeAllCallback); -## Notification.removeAll(bundle?: BundleOption) - -- Functionality +## Notification.removeAll - Removes all notifications for a specified bundle. This method uses a promise to return the result. +removeAll(bundle?: BundleOption): Promise\ -- Parameters +Removes all notifications for a specified user. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ------ | -------- | ------------ | ---- | ---------- | -| bundle | Read-only| BundleOption | No| Bundle information.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | No | Bundle information.| -- Example +**Example** ```js -Notification.removeAll().then((void) => { +Notification.removeAll().then(() => { console.info("==========================>removeAllCallback=======================>"); }); ``` +## Notification.removeAll8+ +removeAll(userId: number, callback: AsyncCallback\): void -## Notification.getAllActiveNotifications(callback: AsyncCallback>) +Removes all notifications for a specified user. This API uses an asynchronous callback to return the result. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains all active notifications. This method uses a callback to return the result. +**Parameters** -- Parameters +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| userId | Yes | No | number | Yes | ID of the user who receives the notification.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------------------------- | ---- | -------------------- | -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**Example** -- Return value +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} + +var userId = 1 + +Notification.removeAll(userId, removeAllCallback); +``` + +## Notification.removeAll8+ + +removeAll(userId: number): Promise\ + +Removes all notifications for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------------ | ---- | ---------- | +| userId | Yes | No | number | Yes | ID of the user who receives the notification.| + +**Example** + +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} + +var userId = 1 + +Notification.removeAll(userId, removeAllCallback); +``` + + +## Notification.getAllActiveNotifications - void +getAllActiveNotifications(callback: AsyncCallback>): void -- Example +Obtains all active notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------------------------------ | ---- | -------------------- | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| + +**Example** ```js function getAllActiveNotificationsCallback(err, data) { @@ -1743,21 +1581,21 @@ Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); -## Notification.getAllActiveNotifications() +## Notification.getAllActiveNotifications -- Functionality +getAllActiveNotifications(): Promise\\> - Obtains all active notifications. This method uses a promise to return the result. +Obtains all active notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getAllActiveNotifications().then((data) => { @@ -1767,23 +1605,21 @@ Notification.getAllActiveNotifications().then((data) => { -## Notification.getActiveNotificationCount(callback: AsyncCallback\) - -- Functionality +## Notification.getActiveNotificationCount - Obtains the number of active notifications. This method uses a callback to return the result. +getActiveNotificationCount(callback: AsyncCallback\): void -- Parameters +Obtains the number of active notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ---------------------- | ---- | ---------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ---------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function getActiveNotificationCountCallback(err, data) { @@ -1795,21 +1631,21 @@ Notification.getActiveNotificationCount(getActiveNotificationCountCallback); -## Notification.getActiveNotificationCount() +## Notification.getActiveNotificationCount -- Functionality +getActiveNotificationCount(): Promise\ - Obtains the number of active notifications. This method uses a promise to return the result. +Obtains the number of active notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| - Promise\ - -- Example +**Example** ```js Notification.getActiveNotificationCount().then((data) => { @@ -1819,23 +1655,21 @@ Notification.getActiveNotificationCount().then((data) => { -## Notification.getActiveNotifications(callback: AsyncCallback>) - -- Functionality +## Notification.getActiveNotifications - Obtains active notifications of the current application. This method uses a callback to return the result. +getActiveNotifications(callback: AsyncCallback>): void -- Parameters +Obtains active notifications of this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------------------ | +| callback | Yes | No | AsyncCallback> | Yes | Callback used to return the result.| -- Example +**Example** ```js function getActiveNotificationsCallback(err, data) { @@ -1847,21 +1681,21 @@ Notification.getActiveNotifications(getActiveNotificationsCallback); -## Notification.getActiveNotifications() +## Notification.getActiveNotifications -- Functionality +getActiveNotifications(): Promise\\> - Obtains active notifications. This method uses a promise to return the result. +Obtains active notifications of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| - Promise\\> - -- Example +**Example** ```js Notification.getActiveNotifications().then((data) => { @@ -1871,24 +1705,22 @@ Notification.getActiveNotifications().then((data) => { -## Notification.cancelGroup(groupName: string, callback: AsyncCallback\) - -- Functionality +## Notification.cancelGroup8+ - Cancels a notification group of the current application. This method uses a callback to return the result. +cancelGroup(groupName: string, callback: AsyncCallback\): void -- Parameters +Cancels a notification group of this application. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ---------------------------- | -| groupName | Read-only| string | Yes| Name of the notification group to cancel.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| groupName | Yes | No | string | Yes | Name of the notification group. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function cancelGroupCallback(err) { @@ -1902,23 +1734,21 @@ Notification.cancelGroup(groupName, cancelGroupCallback); -## Notification.cancelGroup(groupName: string) +## Notification.cancelGroup8+ -- Functionality +cancelGroup(groupName: string): Promise\ - Cancels a notification group of the current application. This method uses a promise to return the result. +Cancels a notification group of this application. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | ------ | ---- | -------------- | -| groupName | Read-only| string | Yes| Name of the notification group to cancel.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | ------ | ---- | -------------- | +| groupName | Yes | No | string | Yes | Name of the notification group.| - Promise\ - -- Example +**Example** ```js var groupName = "GroupName"; @@ -1929,25 +1759,23 @@ Notification.cancelGroup(groupName).then(() => { -## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\) - -- Functionality +## Notification.removeGroupByBundle8+ - Removes a notification group for a specified bundle. This method uses a callback to return the result. +removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void -- Parameters +Removes a notification group for a specified bundle. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | --------------------- | ---- | ---------------------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| groupName | Read-only| string | Yes| Name of the notification group to remove.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | --------------------- | ---- | ---------------------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | Yes | No | string | Yes | Name of the notification group. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function removeGroupByBundleCallback(err) { @@ -1962,24 +1790,22 @@ Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCal -## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) +## Notification.removeGroupByBundle8+ -- Functionality +removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ - Removes a notification group for a specified bundle. This method uses a promise to return the result. +Removes a notification group for a specified bundle. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| --------- | -------- | ------------ | ---- | -------------- | -| bundle | Read-only| BundleOption | Yes| Bundle information.| -| groupName | Read-only| string | Yes| Name of the notification group to remove.| +**Parameters** -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | ---- | --- | ------------ | ---- | -------------- | +| bundle | Yes | No | [BundleOption](#bundleoption) | Yes | Bundle information. | +| groupName | Yes | No | string | Yes | Name of the notification group.| - Promise\ - -- Example +**Example** ```js var bundleOption = {bundle: "Bundle"}; @@ -1991,24 +1817,22 @@ Notification.removeGroupByBundle(bundleOption, groupName).then(() => { -## Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\) - -- Functionality +## Notification.setDoNotDisturbDate8+ - Sets the DND time. This method uses a callback to return the result. +setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void -- Parameters +Sets the DND time. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ---------------------- | -| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```js function setDoNotDisturbDateCallback(err) { @@ -2016,7 +1840,7 @@ function setDoNotDisturbDateCallback(err) { } var doNotDisturbDate = { - type: notification.DoNotDisturbType.TYPE_ONCE, + type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) } @@ -2026,27 +1850,25 @@ Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); -## Notification.setDoNotDisturbDate(date: DoNotDisturbDate) +## Notification.setDoNotDisturbDate8+ -- Functionality +setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ - Sets the DND time. This method uses a promise to return the result. +Sets the DND time. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ---------------- | ---- | -------------- | -| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| +**Parameters** -- Return value +| Name| Readable| Writable| Type | Mandatory| Description | +| ---- | ---- | --- | ---------------- | ---- | -------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| - Promise\ - -- Example +**Example** ```js var doNotDisturbDate = { - type: notification.DoNotDisturbType.TYPE_ONCE, + type: Notification.DoNotDisturbType.TYPE_ONCE, begin: new Date(), end: new Date(2021, 11, 15, 18, 0) } @@ -2056,24 +1878,89 @@ Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { ``` +## Notification.setDoNotDisturbDate8+ + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback\): void + +Sets the DND time for a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------- | ---- | ---------------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | +| userId | Yes | No | number | Yes | User ID.| +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +function setDoNotDisturbDateCallback(err) { + console.info("==========================>setDoNotDisturbDateCallback=======================>"); +} + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); +``` + + + +## Notification.setDoNotDisturbDate8+ + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ + +Sets the DND time for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification -## Notification.getDoNotDisturbDate(callback: AsyncCallback\) +**Parameters** -- Functionality +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ---------------- | ---- | -------------- | +| date | Yes | No | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| +| userId | Yes | No | number | Yes | User ID.| - Obtains the DND time. This method uses a callback to return the result. +**Example** -- Parameters +```js +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { + console.info("==========================>setDoNotDisturbDatePromise=======================>"); +}); +``` + + +## Notification.getDoNotDisturbDate8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------------------- | ---- | ---------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +getDoNotDisturbDate(callback: AsyncCallback\): void -- Return value +Obtains the DND time. This API uses an asynchronous callback to return the result. - void +**System capability**: SystemCapability.Notification.Notification -- Example +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| + +**Example** ```js function getDoNotDisturbDateCallback(err,data) { @@ -2085,21 +1972,21 @@ Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); -## Notification.getDoNotDisturbDate() +## Notification.getDoNotDisturbDate8+ -- Functionality +getDoNotDisturbDate(): Promise\ - Obtains the DND time. This method uses a promise to return the result. +Obtains the DND time. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| - Promise\ - -- Example +**Example** ```js Notification.getDoNotDisturbDate().then((data) => { @@ -2108,24 +1995,81 @@ Notification.getDoNotDisturbDate().then((data) => { ``` +## Notification.getDoNotDisturbDate8+ + +getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void + +Obtains the DND time of a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| callback | Yes | No | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate8)\> | Yes | Callback used to return the result.| +| userId | Yes | No | number | Yes | User ID.| + +**Example** + +```js +function getDoNotDisturbDateCallback(err,data) { + console.info("==========================>getDoNotDisturbDateCallback=======================>"); +} + +var userId = 1 + +Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); +``` + + + +## Notification.getDoNotDisturbDate8+ -## Notification.supportDoNotDisturbMode(callback: AsyncCallback\) +getDoNotDisturbDate(userId: number): Promise\ -- Functionality +Obtains the DND time of a specified user. This API uses a promise to return the result. - Checks whether the DND mode is supported. This method uses a callback to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ------------------------ | ---- | -------------------------------- | -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | --------------------------------- | ---- | ---------------------- | +| userId | Yes | No | number | Yes | User ID.| -- Return value +**Return value** - void +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| -- Example +**Example** + +```js +var userId = 1 + +Notification.getDoNotDisturbDate(userId).then((data) => { + console.info("==========================>getDoNotDisturbDatePromise=======================>"); +}); +``` + + +## Notification.supportDoNotDisturbMode8+ + +supportDoNotDisturbMode(callback: AsyncCallback\): void + +Checks whether the DND mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------ | ---- | -------------------------------- | +| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** ```js function supportDoNotDisturbModeCallback(err,data) { @@ -2137,21 +2081,21 @@ Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); -## Notification.supportDoNotDisturbMode() +## Notification.supportDoNotDisturbMode8+ -- Functionality +supportDoNotDisturbMode(): Promise\ - Checks whether the DND mode is supported. This method uses a promise to return the result. +Checks whether the DND mode is supported. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification - None +**Return value** -- Return value - - Promise\ +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| -- Example +**Example** ```js Notification.supportDoNotDisturbMode().then((data) => { @@ -2161,20 +2105,22 @@ Notification.supportDoNotDisturbMode().then((data) => { -## Notification.isSupportTemplate +## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string, callback: AsyncCallback\): void -Checks whether a specified template exists. This method uses a callback to return the result. +Checks whether a specified template exists. This API uses an asynchronous callback to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Type| Mandatory| Description| +**Parameters** + +| Name | Type | Mandatory| Description | | ------------ | ------------------------ | ---- | -------------------------- | -| templateName | string | Yes| Template name.| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| templateName | string | Yes | Template name. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** ```javascript var templateName = 'process'; @@ -2187,25 +2133,27 @@ Notification.isSupportTemplate(templateName, isSupportTemplateCallback); -## Notification.isSupportTemplate +## Notification.isSupportTemplate8+ isSupportTemplate(templateName: string): Promise\ -Checks whether a specified template exists. This method uses a promise to return the result. +Checks whether a specified template exists. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification -| Name| Type| Mandatory| Description| +**Parameters** + +| Name | Type | Mandatory| Description | | ------------ | ------ | ---- | -------- | -| templateName | string | Yes| Name| +| templateName | string | Yes | Template name.| -- Return value +**Return value** -| Type| Description| +| Type | Description | | ------------------ | --------------- | | Promise\ | Promise used to return the result.| -- Example +**Example** ```javascript var templateName = 'process'; @@ -2217,974 +2165,961 @@ Notification.isSupportTemplate(templateName).then((data) => { -## NotificationTemplate +## Notification.requestEnableNotification8+ -Describes the template information. +requestEnableNotification(callback: AsyncCallback\): void -| Name| Type| Readable| Writable| Description| -| ---- | ---------------------- | ---- | ---- | -------- | -| name | string | Yes| Yes| Template name.| -| data | {[key:string]: Object} | Yes| Yes| Template data.| +Requests notification to be enabled for this application. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Notification.Notification +**Parameters** -## WantAgent APIs +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -## Modules to Import +**Example** -```js -import WantAgent from '@ohos.wantAgent'; +```javascript +function requestEnabledNotificationCallback() { + console.log('------------- requestEnabledNotification --------------'); +}; + +Notification.requestEnabledNotification(requestEnabledNotificationCallback); ``` -## WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\) -- Functionality - Obtains a **WantAgent** object. This method uses a callback to return the result. +## Notification.requestEnableNotification8+ -- Parameters +requestEnableNotification(): Promise\ +Requests notification to be enabled for this application. This API uses a promise to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | -------------------------- | ---- | ----------------------- | -| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- WantAgentInfo +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------------- | -------- | ------------------------------- | ---- | ---------------------- | -| wants | Readable and writable| Array\ | Yes| Array of all **Want** objects.| -| operationType | Readable and writable| wantAgent.OperationType | Yes| Type of the operation specified in a **Want** object.| -| requestCode | Readable and writable| number | Yes| Request code defined by the user.| -| wantAgentFlags | Readable and writable| Array | No| Array of flags for using the **WantAgent** object.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| +```javascript +Notification.requestEnableNotification() + .then(() => { + console.info("requestEnableNotification "); + }); +``` -- - WantAgentFlags +## Notification.enableDistributed8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| ------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| ONE_TIME_FLAG | Read-only| enum | No| The **WantAgent** object can be used only once.| -| NO_BUILD_FLAG | Read-only| enum | No| The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned.| -| CANCEL_PRESENT_FLAG | Read-only| enum | No| The existing **WantAgent** object should be canceled before a new object is generated.| -| UPDATE_PRESENT_FLAG | Read-only| enum | No| Extra data of the existing **WantAgent** object is replaced with that of the new object.| -| CONSTANT_FLAG | Read-only| enum | No| The **WantAgent** object is immutable.| +enableDistributed(enable: boolean, callback: AsyncCallback\): void -- OperationType +Sets whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------------- | -------- | ---- | ---- | ----------------------- | -| UNKNOWN_TYPE | Read-only| enum | No| Unknown operation.| -| START_ABILITY | Read-only| enum | No| Starts an ability with a UI.| -| START_ABILITIES | Read-only| enum | No| Starts multiple abilities with a UI.| -| START_SERVICE | Read-only| enum | No| Starts an ability without a UI.| -| SEND_COMMON_EVENT | Read-only| enum | No| Sends a common event.| +**System capability**: SystemCapability.Notification.Notification -- Return value +**Parameters** - void +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -- Example +**Example** -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +```javascript +function enabledNotificationCallback() { + console.log('----------- enableDistributed ------------'); +}; -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +var enable = true -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +Notification.enableDistributed(enable, enabledNotificationCallback); ``` -## WantAgent.getWantAgent(info: WantAgentInfo): Promise\ +## Notification.enableDistributed8+ -- Functionality +enableDistributed(enable: boolean): Promise\ - Obtains a **WantAgent** object. This method uses a promise to return the result. +Sets whether this device supports distributed notifications. This API uses a promise to return the result. -- Parameters +**System capability**: SystemCapability.Notification.Notification +**Parameters** -| Name| Readable/Writable| Type| Mandatory| Description| -| ---- | -------- | ------------- | ---- | ------------- | -| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| -- Return value +**Example** - Promise\ +```javascript +var enable = true -- Example +Notification.enableDistributed(enable) + .then(() => { + console.log('-------- enableDistributed ----------'); + }); +``` -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +## Notification.isDistributedEnabled8+ -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); -}); -``` +isDistributedEnabled(callback: AsyncCallback\): void +Obtains whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Notification.Notification -## WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\) +**Parameters** -- Functionality +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| - Obtains the bundle name of a **WantAgent** object. This method uses a callback to return the result. +**Example** -- Parameters +```javascript +function isDistributedEnabledCallback() { + console.log('----------- isDistributedEnabled ------------'); +}; +Notification.enableDistributed(isDistributedEnabledCallback); +``` -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ----------------------- | ---- | --------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| -- Return value - void +## Notification.isDistributedEnabled8+ -- Example +isDistributedEnabled(): Promise\ -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Obtains whether this device supports distributed notifications. This API uses a promise to return the result. -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +**Return value** -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +| Type | Description | +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| -// getBundleName callback -function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); -} -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +**Example** + +```javascript +Notification.isDistributedEnabled() + .then((data) => { + console.log('-------- isDistributedEnabled ----------'); + }); ``` +## Notification.enableDistributedByBundle8+ -## WantAgent.getBundleName(agent: WantAgent): Promise\ +enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -- Functionality +Sets whether an application supports distributed notifications based on the bundle. This API uses an asynchronous callback to return the result. - Obtains the bundle name of a **WantAgent** object. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| +**Example** -- Return value +```javascript +function enableDistributedByBundleCallback() { + console.log('----------- enableDistributedByBundle ------------'); +}; - Promise\ +var bundle = { + bundle: "bundleName1", +} -- Example +var enable = true -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundleCallback); +``` -// WantAgent object -var wantAgent; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] + +## Notification.enableDistributedByBundle8+ + +bundleenableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise + +Sets whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| enable | boolean | Yes | Whether the device supports distributed notifications. | + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", } -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var enable = true -WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); -}); +Notification.enableDistributedByBundle(bundle, enable) + .then(() => { + console.log('-------- enableDistributedByBundle ----------'); + }); ``` +## Notification.isDistributedEnabledByBundle8+ +isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\): void -## WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\) +Obtains whether an application supports distributed notifications based on the bundle. This API uses an asynchronous callback to return the result. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains the user ID of a **WantAgent** object. This method uses a callback to return the result. +**Parameters** -- Parameters +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | ----------------------- | ---- | ----------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +```javascript +function isDistributedEnabledByBundleCallback(data) { + console.log('----------- isDistributedEnabledByBundle ------------', data); +}; -- Return value +var bundle = { + bundle: "bundleName1", +} - void +Notification.enableDistributedByBundle(bundle, isDistributedEnabledByBundleCallback); +``` -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgent object -var wantAgent; +## Notification.isDistributedEnabledByBundle8+ -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +isDistributedEnabledByBundle(bundle: BundleOption): Promise\ -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +Obtains whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. -// getUid callback -function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", } -WantAgent.getUid(wantAgent, getUidCallback) + +Notification.isDistributedEnabledByBundle(bundle) + .then((data) => { + console.log('-------- isDistributedEnabledByBundle ----------', data); + }); ``` +## Notification.getDeviceRemindType8+ -## WantAgent.getUid(agent: WantAgent): Promise\ +getDeviceRemindType(callback: AsyncCallback\): void -- Functionality +Obtains the notification reminder type. This API uses an asynchronous callback to return the result. - Obtains the user ID of a **WantAgent** object. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype8)\> | Yes | Callback used to return the result.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| +**Example** -- Return value +```javascript +function getDeviceRemindTypeCallback(data) { + console.log('----------- getDeviceRemindType ------------', data); +}; - Promise\ +Notification.getDeviceRemindType(getDeviceRemindTypeCallback); +``` -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; -// WantAgent object -var wantAgent; +## Notification.getDeviceRemindType8+ -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +getDeviceRemindType(): Promise\ -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +Obtains the notification reminder type. This API uses a promise to return the result. -WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); -}); +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\<[DeviceRemindType](#deviceremindtype8)\> | Promise used to return the result.| + +**Example** + +```javascript +Notification.getDeviceRemindType() + .then((data) => { + console.log('-------- getDeviceRemindType ----------', data); + }); ``` +## NotificationSubscriber + +### onConsume + +onConsume?:(data: [SubscribeCallbackData](#subscribecallbackdata)) +Callback for receiving notifications. -## WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\) +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -- Functionality +function onConsumeCallback(data) { + console.info('===> onConsume in test'); + let req = data.request; + console.info('===> onConsume callback req.id:' + req.id); + let wantAgent = data.wantAgent; + wantAgent .getWant(wantAgent) + .then((data1) => { + console.log('===> getWant success want:' + JSON.stringfy(data1)); + }) + .catch((err) => { + console.error('===> getWant failed because' + JSON.stringfy(err)); + }); + console.info('===> onConsume callback req.wantAgent:' + JSON.stringfy(req.wantAgent)); +}; - Obtains the want in a **WantAgent** object. This method uses a callback to return the result. +var subscriber = { + onConsume: onConsumeCallback +}; -- Parameters +Notification.subscribe(subscriber, subscribeCallback); +``` +### onCancel -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | ------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) -- Return value +Callback for removing notifications. - void +**System capability**: SystemCapability.Notification.Notification -- Example +**Parameters** -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| -// WantAgent object -var wantAgent; +**Example** -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); } else { - console.info('----getWantAgent failed!----'); + console.info("subscribeCallback"); } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentWantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +function onCancelCallback(data) { + console.info('===> onCancel in test'); + let req = data.request; + console.info('===> onCancel callback req.id:' + req.id); } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +var subscriber = { + onCancel: onCancelCallback +}; -// getWant callback -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) +Notification.subscribe(subscriber, subscribeCallback); ``` +### onUpdate +onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) -## WantAgent.getWant(agent: WantAgent): Promise\ +Callback for notification sorting updates. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Obtains the want in a **WantAgent** object. This method uses a promise to return the result. +**Parameters** -- Parameters +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Notification information returned.| +**Example** -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object.| +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -- Return value +function onUpdateCallback() { + console.info('===> onUpdate in test'); +} - Promise\ +var subscriber = { + onUpdate: onUpdateCallback +}; -- Example +Notification.subscribe(subscriber, subscribeCallback); +``` -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +### onConnect -// WantAgent object -var wantAgent; +onConnect?:void -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +Callback for subscription. + +**System capability**: SystemCapability.Notification.Notification + +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); } -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var subscriber = { + onConnect: onConnectCallback +}; -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); -}); +Notification.subscribe(subscriber, subscribeCallback); ``` +### onDisconnect +onDisconnect?:void -## WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\) +Callback for unsubscription. -- Functionality +**System capability**: SystemCapability.Notification.Notification - Cancels a **WantAgent** object. This method uses a callback to return the result. +**Example** -- Parameters +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; +function onDisconnectCallback() { + console.info('===> onDisconnect in test'); +} -| Name| Readable/Writable| Type| Mandatory| Description| -| -------- | -------- | --------------------- | ---- | --------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +var subscriber = { + onDisconnect: onDisconnectCallback +}; -- Return value +Notification.subscribe(subscriber, subscribeCallback); +``` - void +### onDestroy -- Example +onDestroy?:void -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +Callback for service disconnection. -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; +**Example** + +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); } else { - console.info('----getWantAgent failed!----'); + console.info("subscribeCallback"); } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +function onDestroyCallback() { + console.info('===> onDestroy in test'); } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +var subscriber = { + onDestroy: onDestroyCallback +}; -// cancel callback -function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); -} -WantAgent.cancel(wantAgent, cancelCallback) +Notification.subscribe(subscriber, subscribeCallback); ``` +### onDoNotDisturbDateChange8+ + +onDoNotDisturbDateChange?:(mode: Notification.[DoNotDisturbDate](#donotdisturbdate8)) + +Callback for DND time setting updates. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| mode | Notification.[DoNotDisturbDate](#donotdisturbdate8) | Yes| DND time setting updates.| + +**Example** +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; +function onDoNotDisturbDateChangeCallback() { + console.info('===> onDoNotDisturbDateChange in test'); +} -## WantAgent.cancel(agent: WantAgent): Promise\ +var subscriber = { + onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback +}; -- Functionality +Notification.subscribe(subscriber, subscribeCallback); +``` - Cancels a **WantAgent** object. This method uses a promise to return the result. -- Parameters +### onEnabledNotificationChanged8+ +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) -| Name| Readable/Writable| Type| Mandatory| Description| -| ----- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| +Listens for the notification enable status changes. This API uses an asynchronous callback to return the result. -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ +**Parameters** -- Example +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata8)\> | Yes| Callback used to return the result.| -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +**Example** -// WantAgent object -var wantAgent; +```javascript +function subscribeCallback(err) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +function onEnabledNotificationChangedCallback(err, callbackData) { + if (err.code) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("bundle: ", callbackData.bundle); + console.info("uid: ", callbackData.uid); + console.info("enable: ", callbackData.enable); + } +}; -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); +var subscriber = { + onEnabledNotificationChanged: onEnabledNotificationChangedCallback +}; -WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); -}); +Notification.subscribe(subscriber, subscribeCallback); ``` +## SubscribeCallbackData +**System capability**: SystemCapability.Notification.Notification -## WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------- | ---- | --- | ------------------------------------------------- | ---- | -------- | +| request | Yes | No | [NotificationRequest](#notificationrequest) | Yes | Notification content.| +| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | No | Notification sorting information.| +| reason | Yes | No | number | No | Reason for deletion.| +| sound | Yes | No | string | No | Sound used for notification.| +| vibrationValues | Yes | No | Array\ | No | Vibration used for notification.| -- Functionality - Triggers a **WantAgent** object. This method uses a callback to return the result. +## EnabledNotificationCallbackData8+ -- Parameters +**System capability**: SystemCapability.Notification.Notification +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------- | ---- | ---------------- | +| bundle | Yes | No | string | Yes | Bundle name of the application. | +| uid | Yes | No | number | Yes | UID of the application. | +| enable | Yes | No | boolean | Yes | Notification enable status of the application.| -| Name| Readable/Writable| Type| Mandatory| Description| -| ----------- | -------- | ----------------------------- | ---- | ------------------------------- | -| agent | Read-only| WantAgent | Yes| **WantAgent** object to trigger.| -| triggerInfo | Read-only| TriggerInfo | Yes| **TriggerInfo** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| -- TriggerInfo +## DoNotDisturbDate8+ -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | -------------------- | ---- | ----------- | -| code | Readable and writable| number | Yes| Result code.| -| want | Readable and writable| Want | No| Want.| -| permission | Readable and writable| string | No| Permission.| -| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| +**System capability**: SystemCapability.Notification.Notification -- Return value +| Name | Readable| Writable| Type | Description | +| ----- | ---- | --- | ------------------------------------- | ------------------------ | +| type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| +| begin | Yes | No | Date | DND start time.| +| end | Yes | No | Date | DND end time.| - void -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## DoNotDisturbType8+ -// WantAgent object -var wantAgent; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +| Name | Value | Description | +| ------------ | ---------------- | ------------------------------------------ | +| TYPE_NONE | DoNotDisturbType | Non-DND. | +| TYPE_ONCE | DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute).| +| TYPE_DAILY | DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute).| +| TYPE_CLEARLY | DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute). | -//Trigger callback -function triggerCallback(err, data) { - console.info("==========================>triggerCallback=======================>"); -} -var triggerInfo = { - code:0 -} -WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) -``` +## ContentType +**System capability**: SystemCapability.Notification.Notification +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| NOTIFICATION_CONTENT_BASIC_TEXT | ContentType | Normal text notification. | +| NOTIFICATION_CONTENT_LONG_TEXT | ContentType | Long text notification. | +| NOTIFICATION_CONTENT_PICTURE | ContentType | Picture-attached notification. | +| NOTIFICATION_CONTENT_CONVERSATION | ContentType | Conversation notification. | +| NOTIFICATION_CONTENT_MULTILINE | ContentType | Multi-line text notification.| -## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\) +## SlotLevel -- Functionality +**System capability**: SystemCapability.Notification.Notification - Checks whether two **WantAgent** objects are equal. This method uses a callback to return the result. +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| LEVEL_NONE | 0 | The notification feature is disabled. | +| LEVEL_MIN | 1 | The notification feature is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| +| LEVEL_LOW | 2 | The notification feature is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| +| LEVEL_DEFAULT | 3 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| +| LEVEL_HIGH | 4 | The notification feature is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| -- Parameters +## BundleOption -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | ------------------------ | ---- | --------------------------------------- | -| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| -| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| -| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| +**System capability**: SystemCapability.Notification.Notification -- Return value +| Name | Readable| Writable| Type | Mandatory| Description | +| ------ | ---- | --- | ------ | ---- | ------ | +| bundle | Yes | Yes | string | Yes | Bundle name. | +| uid | Yes | Yes | number | No | User ID.| - void -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## NotificationKey -// WantAgent object -var wantAgent1; -var wantAgent2; +**System capability**: SystemCapability.Notification.Notification -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent1 = data; - wantAgent2 = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +| Name | Readable| Writable| Type | Mandatory| Description | +| ----- | ---- | --- | ------ | ---- | -------- | +| id | Yes | Yes | number | Yes | Notification ID. | +| label | Yes | Yes | string | No | Notification label.| -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) -// equal callback -function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); -} -WantAgent.equal(wantAgent1, wantAgent2, equalCallback) -``` +## SlotType +**System capability**: SystemCapability.Notification.Notification +| Name | Value | Description | +| -------------------- | -------- | ---------- | +| UNKNOWN_TYPE | SlotType | Unknown type.| +| SOCIAL_COMMUNICATION | SlotType | Notification slot for social communication.| +| SERVICE_INFORMATION | SlotType | Notification slot for service information.| +| CONTENT_INFORMATION | SlotType | Notification slot for content consultation.| +| OTHER_TYPES | SlotType | Notification slot for other purposes.| -## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -- Functionality +## NotificationActionButton - Checks whether two **WantAgent** objects are equal. This method uses a promise to return the result. +**System capability**: SystemCapability.Notification.Notification -- Parameters +| Name | Readable| Writable| Type | Mandatory| Description | +| --------- | --- | ---- | ----------------------------------------------- | ---- | ------------------------- | +| title | Yes | Yes | string | Yes | Button title. | +| wantAgent | Yes | Yes | WantAgent | Yes | **WantAgent** of the button.| +| extras | Yes | Yes | { [key: string]: any } | No | Extra information of the button. | -| Name| Readable/Writable| Type| Mandatory| Description| -| ---------- | -------- | --------- | ---- | ------------- | -| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| -| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| +## NotificationBasicContent -- Return value +**System capability**: SystemCapability.Notification.Notification - Promise\ +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | ---- | ------ | ---- | ---------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| -- Example -```js -import WantAgent from '@ohos.wantAgent'; -import { OperationType, WantAgentFlags } from '@ohos.wantagent'; +## NotificationLongTextContent -// WantAgent object -var wantAgent1; -var wantAgent2; +**System capability**: SystemCapability.Notification.Notification -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] -} +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | ------ | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| longText | Yes | Yes | string | Yes | Long text of the notification. | +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent1 = data; - wantAgent2 = data; -}); -WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); -}); -``` +## NotificationMultiLineContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | --- | --- | --------------- | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| longTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | +| lines | Yes | Yes | Array\ | Yes | Multi-line text of the notification. | + + +## NotificationPictureContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | -------------- | ---- | -------------------------------- | +| title | Yes | Yes | string | Yes | Notification title. | +| text | Yes | Yes | string | Yes | Notification content. | +| additionalText | Yes | Yes | string | No | Additional information of the notification.| +| briefText | Yes | Yes | string | Yes | Brief text of the notification.| +| expandedTitle | Yes | Yes | string | Yes | Title of the notification in the expanded state. | +| picture | Yes | Yes | image.PixelMap | Yes | Picture attached to the notification. | + + +## NotificationContent + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ----------- | ---- | --- | ------------------------------------------------------------ | ---- | ------------------ | +| contentType | Yes | Yes | [ContentType](#contenttype) | Yes | Notification content type. | +| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | No | Normal text. | +| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | No | Long text.| +| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | No | Multi-line text. | +| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | No | Picture-attached. | + + +## NotificationFlagStatus8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Value | Description | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | The default flag is used. | +| TYPE_OPEN | 1 | The notification flag is enabled. | +| TYPE_CLOSE | 2 | The notification flag is disabled. | + + +## NotificationFlags8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------------- | ---- | ---- | ---------------------- | ---- | --------------------------------- | +| soundEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | Yes | No | NotificationFlagStatus | No | Whether to enable vibration for the notification. | + + +## NotificationRequest + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| --------------------- | ---- | --- | --------------------------------------------- | ---- | -------------------------- | +| content | Yes | Yes | [NotificationContent](#notificationcontent) | Yes | Notification content. | +| id | Yes | Yes | number | No | Notification ID. | +| slotType | Yes | Yes | [SlotType](#slottype) | No | Slot type. | +| isOngoing | Yes | Yes | boolean | No | Whether the notification is an ongoing notification. | +| isUnremovable | Yes | Yes | boolean | No | Whether the notification can be removed. | +| deliveryTime | Yes | Yes | number | No | Time when the notification is sent. | +| tapDismissed | Yes | Yes | boolean | No | Whether the notification is automatically cleared. | +| autoDeletedTime | Yes | Yes | number | No | Time when the notification is automatically cleared. | +| wantAgent | Yes | Yes | WantAgent | No | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | Yes | Yes | {[key: string]: any} | No | Extended parameters. | +| color | Yes | Yes | number | No | Background color of the notification. | +| colorEnabled | Yes | Yes | boolean | No | Whether the notification background color is enabled. | +| isAlertOnce | Yes | Yes | boolean | No | Whether the notification triggers an alert only once.| +| isStopwatch | Yes | Yes | boolean | No | Whether to display the stopwatch. | +| isCountDown | Yes | Yes | boolean | No | Whether to display the countdown time. | +| isFloatingIcon | Yes | Yes | boolean | No | Whether the notification is displayed as a floating icon. | +| label | Yes | Yes | string | No | Notification label. | +| badgeIconStyle | Yes | Yes | number | No | Notification badge type. | +| showDeliveryTime | Yes | Yes | boolean | No | Whether to display the time when the notification is delivered. | +| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | No | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | Yes | Yes | PixelMap | No | Small notification icon. | +| largeIcon | Yes | Yes | PixelMap | No | Large notification icon. | +| creatorBundleName | Yes | No | string | No | Name of the bundle that creates the notification. | +| creatorUid | Yes | No | number | No | UID used for creating the notification. | +| creatorPid | Yes | No | number | No | PID used for creating the notification. | +| creatorUserId8+| Yes | No | number | No | ID of the user who creates a notification. | +| hashCode | Yes | No | string | No | Unique ID of the notification. | +| classification | Yes | Yes | string | No | Notification category. | +| groupName8+| Yes | Yes | string | No | Group notification name. | +| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | No | Notification template. | +| isRemoveAllowed8+ | Yes | No | boolean | No | Whether the notification can be removed. | +| source8+ | Yes | No | number | No | Notification source. | +| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | No | Option of distributed notification. | +| deviceId8+ | Yes | No | string | No | Device ID of the notification source. | +| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | No | Notification flags. | + + +## DistributedOptions8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ---------------------- | ---- | ---- | -------------- | ---- | ---------------------------------- | +| isDistributed | Yes | Yes | boolean | No | Whether the notification is a distributed notification. | +| supportDisplayDevices | Yes | Yes | Array\ | Yes | Types of the devices to which the notification can be synchronized. | +| supportOperateDevices | Yes | Yes | Array\ | No | Devices on which notification can be enabled. | +| remindType | Yes | No | number | No | Notification reminder type. | + + +## NotificationSlot + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------------- | ---- | --- | --------------------- | ---- | ------------------------------------------ | +| type | Yes | Yes | [SlotType](#slottype) | Yes | Slot type. | +| level | Yes | Yes | number | No | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | Yes | Yes | string | No | Notification slot description. | +| badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. | +| bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. | +| lockscreenVisibility | Yes | Yes | boolean | No | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | +| sound | Yes | Yes | string | No | Notification alert tone. | +| lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | +| lightColor | Yes | Yes | number | No | Indicator color of the notification. | +| vibrationValues | Yes | Yes | Array\ | No | Vibration mode of the notification. | + + +## NotificationSorting + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | ---- | --- | ------------------------------------- | ---- | ------------ | +| slot | Yes | No | [NotificationSlot](#notificationslot) | Yes | Notification slot content.| +| hashCode | Yes | No | string | Yes | Unique ID of the notification.| +| ranking | Yes | No | number | Yes | Notification sequence number.| + + +## NotificationSortingMap + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------------- | ---- | --- | ------------------------------------------------------------ | ---- | ---------------- | +| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | Array of notification sorting information.| +| sortedHashCode | Yes | No | Array\ | Yes | Array of unique notification IDs.| + + +## NotificationSubscribeInfo + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| ----------- | --- | ---- | --------------- | ---- | ------------------------------- | +| bundleNames | Yes | Yes | Array\ | No | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | Yes | Yes | number | No | User whose notifications are to be subscribed to. | + + +## NotificationTemplate8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name| Type | Readable| Writable| Description | +| ---- | ---------------------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Template name.| +| data | {[key:string]: Object} | Yes | Yes | Template data.| + + +## NotificationUserInput8+ + +**System capability**: SystemCapability.Notification.Notification + +| Name | Readable| Writable| Type | Mandatory| Description | +| -------- | --- | ---- | ------ | ---- | ----------------------------- | +| inputKey | Yes | Yes | string | Yes | Key to identify the user input.| + +## DeviceRemindType8+ +**System capability**: SystemCapability.Notification.Notification -#### +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| IDLE_DONOT_REMIND | 0 | The device is not in use. No notification is required. | +| IDLE_REMIND | 1 | The device is not in use. | +| ACTIVE_DONOT_REMIND | 2 | The device is in use. No notification is required. | +| ACTIVE_REMIND | 3 | The device is in use. | diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index cc75cd19bc78261d14039bfb813abb6f3d85f3e3..29d9e85a234e0817b29645ac6daed24d8d5eb8cf 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -278,7 +278,7 @@ Registers an observer for connection status change events of the cellular data l | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** @@ -303,7 +303,7 @@ Registers an observer for connection status change events of the cellular data l | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | Yes | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** @@ -331,7 +331,7 @@ Unregisters the observer for connection status change events of the cellular dat | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Connection status change event of the cellular data link. | -| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectState), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| +| callback | Callback\<{ state: [DataConnectState](js-apis-telephony-data.md#dataconnectstate), network: [RatType](js-apis-radio.md#radiotechnology) }\> | No | Callback used to return the result. For details, see [DataConnectState](js-apis-telephony-data.md#dataconnectstate) and [RadioTechnology](js-apis-radio.md#radiotechnology).| **Example** diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 6de662feea1f67cba1ef42f86eb294af29c47cea..de757b71b485830c58890547591a99fad14bca9c 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -29,6 +29,7 @@ Obtains an **AccountManager** instance. ``` ## OsAccountType + Enumerates OS account types. **System capability**: SystemCapability.Account.OsAccount @@ -51,6 +52,8 @@ Activates an OS account. This method uses an asynchronous callback to return the This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION + **System capability**: SystemCapability.Account.OsAccount **Parameters** @@ -488,7 +491,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean,callback: AsyncCallback<void>): void -Sets or removes constraints for an OS account. +Sets or removes constraints for an OS account. This method uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -519,7 +522,7 @@ This is a system API and cannot be called by third-party applications. setOsAccountConstraints(localId: number, constraints: Array<string>, enable: boolean): Promise<void> -Sets or removes constraints for an OS account. +Sets or removes constraints for an OS account. This method uses a promise to return the result. This is a system API and cannot be called by third-party applications. @@ -1737,16 +1740,17 @@ This is a system API and cannot be called by third-party applications. ``` ## OsAccountInfo + Defines information about an OS account. **System capability**: SystemCapability.Account.OsAccount -| Name | Type | Mandatory| Description | -| ----------------- | ------------------------------------------------------------ | ---- | --------------------------------- | -| localId | number | Yes | ID of the target OS account. | -| localName | string | Yes | OS account name. | -| type | [OsAccountType](#osaccounttype) | Yes | OS account type. | -| constraints | Array<string> | No | [Constraints](#constraints) on the OS account.| +| Name | Type | Mandatory| Description | +| ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------- | +| localId | number | Yes | ID of the target OS account. | +| localName | string | Yes | OS account name. | +| type | [OsAccountType](#osaccounttype) | Yes | OS account type. | +| constraints | Array<string> | No | [Constraints](#constraints) on the OS account.| | isVerified8+ | boolean | Yes | Whether the OS account is verified. | | photo8+ | string | No | Profile photo of the OS account. | | createTime8+ | number | Yes | Time when the OS account was created. | @@ -1754,17 +1758,18 @@ Defines information about an OS account. | serialNumber8+ | number | Yes | SN of the OS account. | | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | -| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | +| distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | | domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | ## DomainAccountInfo8+ + Domain account information. **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------- | -| domain | string | Yes | Domain name. | +| domain | string | Yes | Domain name. | | accountName | string | Yes | Domain account name.| ## Constraints @@ -1801,8 +1806,8 @@ Domain account information. | constraint.control.apps | A user is not allowed to modify apps in **Settings** or the boot module.| | constraint.physical.media | A user is not allowed to mount external physical media.| | constraint.microphone | A user is not allowed to use microphones.| -| constraint.microphone.unmute | A user is not allowed to adjust the microphone volume.| -| constraint.volume.adjust | A user is not allowed to adjust the device's global volume.| +| constraint.microphone.unmute | A user is not allowed to unmute the microphone.| +| constraint.volume.adjust | A user is not allowed to adjust the volume.| | constraint.calls.outgoing | A user is not allowed to make outgoing calls.| | constraint.sms.use | A user is not allowed to send or receive SMS messages.| | constraint.fun | A user is not allowed to have entertainment.| @@ -1820,7 +1825,7 @@ Domain account information. | constraint.os.account.set.icon | A user is not allowed to change their icon.| | constraint.wallpaper.set | A user is not allowed to set a wallpaper.| | constraint.oem.unlock | A user is not allowed to enable OEM unlock.| -| constraint.device.unmute | A user is not allowed to mute the device's global volume.| +| constraint.device.unmute | A user is not allowed to unmute the device.| | constraint.password.unified | The managed profile is not allowed to have unified lock screen challenge with the primary user.| | constraint.autofill | A user is not allowed to use the autofill service.| | constraint.content.capture | Capturing the content of a user's screen is prohibited.| diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-particleAbility.md index e4499fb3d240aacc00c29f920e657b9e5433a8c6..7955a810d33f3b6e9cfe23d6c939c1a83bae92c4 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-particleAbility.md @@ -17,7 +17,7 @@ import particleAbility from '@ohos.ability.particleAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts a particle ability. This API uses an asynchronous callback to return the result. +Starts a Particle ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -26,7 +26,7 @@ Starts a particle ability. This API uses an asynchronous callback to return the | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -58,9 +58,9 @@ particleAbility.startAbility( ## particleAbility.startAbility -startAbility(parameter: StartAbilityParameter): Promise; +startAbility(parameter: StartAbilityParameter): Promise\; -Starts a particle ability. This API uses a promise to return the result. +Starts a Particle ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -69,7 +69,7 @@ Starts a particle ability. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| **Return value** @@ -107,7 +107,7 @@ particleAbility.startAbility( terminateSelf(callback: AsyncCallback\): void -Terminates this particle ability. This API uses an asynchronous callback to return the result. +Terminates this Particle ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -134,7 +134,7 @@ particleAbility.terminateSelf( terminateSelf(): Promise\ -Terminates this particle ability. This API uses a promise to return the result. +Terminates this Particle ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -188,7 +188,9 @@ particleAbility.acquireDataAbilityHelper(uri) startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void; -Requests a continuous task from the system. This API uses an asynchronous callback to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses an asynchronous callback to return the result. You are advised to use the new API [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8). + +**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -250,9 +252,11 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { startBackgroundRunning(id: number, request: NotificationRequest): Promise<void> +**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING + **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -Requests a continuous task from the system. This API uses a promise to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8-1). **Parameters** @@ -313,7 +317,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { cancelBackgroundRunning(callback: AsyncCallback<void>): void; -Requests to cancel a continuous task from the system. This API uses an asynchronous callback to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests to cancel a continuous task from the system. This API uses an asynchronous callback to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -344,7 +348,7 @@ particleAbility.cancelBackgroundRunning(callback); cancelBackgroundRunning(): Promise<void>; -Requests to cancel a continuous task from the system. This API uses a promise to return the result. (This method is of API 7 and will be deprecated. Use the counterpart in API 8.) +Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -380,9 +384,20 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](#want) | Yes | Service ability to connect.| +| request | [Want](js-apis-featureAbility.md#want) | Yes | Service ability to connect.| | options | ConnectOptions | Yes | Callback used to return the result. | + +ConnectOptions + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Readable/Writable| Type | Mandatory | Description | +| ------------ | ---- | -------- | ---- | ------------------------- | +| onConnect | Read only | function | Yes | Callback invoked when the connection is successful. | +| onDisconnect | Read only | function | Yes | Callback invoked when the connection fails. | +| onFailed | Read only | function | Yes | Callback invoked when **connectAbility** fails to be called.| + **Example** ```js @@ -509,11 +524,8 @@ function onConnectCallback(element, remote){ Enumerates error codes. +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + | Name | Value | Description | | ----------------------------- | ---- | ------------------------------------------------------------ | -| INVALID_PARAMETER | -1 | Invalid parameter.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| - - - - - +| INVALID_PARAMETER | -1 | Invalid parameter.| diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md deleted file mode 100644 index 20f6b7859945481356f504b2bc8b64b41cdd58ff..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ /dev/null @@ -1,17 +0,0 @@ -# PermissionRequestResult - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Provides the permission request result. - - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - - | Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| No| Permissions requested.| -| authResults | Array<number> | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 5e847795d004d2fabb0acdf3fc28d7231b0cc9a2..ad79f05458fa5426b6cef9f0ab2e459726e030ed 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -115,7 +115,7 @@ let result = plainArray.get(1); ### getIndexOfKey -getIndexOfKey(key: number): number; +getIndexOfKey(key: number): number Obtains the index of the first occurrence of an entry with the specified key in this container. @@ -143,7 +143,7 @@ let result = plainArray.getIndexOfKey("sdfs"); ### getIndexOfValue -getIndexOfValue(value: T): number; +getIndexOfValue(value: T): number Obtains the index of the first occurrence of an entry with the specified value in this container. @@ -171,7 +171,7 @@ let result = plainArray.getIndexOfValue("sddfhf"); ### getKeyAt -getKeyAt(index: number): number; +getKeyAt(index: number): number Obtains the key of the entry at the specified position in this container. @@ -238,7 +238,7 @@ Clones this container and returns a copy. The modification to the copy does not **Example** ``` -let plainArray = new ArrayList(); +let plainArray = new PlainArray(); plainArray.add(1, "sddfhf"); plainArray.add(2, "sffdfhf"); let newPlainArray = plainArray.clone(); @@ -416,7 +416,7 @@ plainArray.clear(); ### forEach -forEach(callbackfn: (value?: T, index?: number, PlainArray?: PlainArray) => void, thisArg?: Object): void +forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -431,8 +431,8 @@ callbackfn | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Value of the entry that is currently traversed.| -| index | number | Yes| Key of the entry that is currently traversed.| -| plainArray | PlainArray | No| Instance that invokes the **forEach** API.| +| index | number | No| Key of the entry that is currently traversed.| +| PlainArray | PlainArray<T>| No| Instance that invokes the **forEach** API.| **Example** @@ -456,7 +456,7 @@ Obtains an iterator, each item of which is a JavaScript object. | Type| Description| | -------- | -------- | -| IterableIterator<[number, T]> | Iterator obtained.| +| IterableIterator<[number, T]> | Iterator obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index d3e6377b84992a2ba21a0ed8d5e544fe80058068..ca7e76cf6defcf233d399b4c0b5c9e5a8d588299 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -12,7 +12,7 @@ The Power Manager module provides APIs for rebooting and shutting down the syste import power from '@ohos.power'; ``` -## System Capabilities +## System Capability SystemCapability.PowerManager.PowerManager.Core @@ -25,7 +25,7 @@ Shuts down the system. This is a system API and cannot be called by third-party applications. -**Required permission:** ohos.permission.SHUTDOWN +**Required permission**: ohos.permission.REBOOT **Parameters** @@ -45,9 +45,9 @@ console.info('power_shutdown_device_test success') rebootDevice(reason: string): void -Restarts the device. +Reboots the system. -**Required permission:** ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_UPDATER (to reboot and enter the updater mode) +**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) **Parameters** @@ -71,7 +71,7 @@ Checks the screen status of the current device. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| @@ -94,10 +94,10 @@ isScreenOn(): Promise<boolean> Checks the screen status of the current device. -**Return Value** +**Return value** | Type | Description | | ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to asynchronously obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Promise<boolean> | Promise used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-processrunninginfo.md index 5306bc6697e98fd3f749953a795077dd5d02a2ec..29d055c83fc1e408404a3d91c81ea0ab090a6258 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-processrunninginfo.md @@ -1,7 +1,7 @@ # ProcessRunningInfo > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Provides process running information. diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..3b4523f4f2e3d85ba3f53cf41ce4aa719d777526 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -0,0 +1,272 @@ +# Prompt + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **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 + +``` +import prompt from '@ohos.prompt' +``` +## Required Permissions + +None. + +## prompt.showToast + +showToast(options: ShowToastOptions): void + +Shows the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| + +**Example** + ``` + export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } + } + ``` +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | -------------- | ---- | ---------------------------------------- | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom | <length> | No | Distance between the toast border and the bottom of the screen. | + +## prompt.showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Example** + + ``` + export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ], + }) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) + } + } + ``` + +## prompt.showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void + +Shows a dialog box. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Example** + ``` + export default { + callback(err, data) { + if(err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }, + showDialog() { + prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ] + }, this.callback); + } + } + ``` + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| message | string | No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| + +## ShowDialogSuccessResponse + +Describes the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Description | +| ----- | ------ | ------------------- | +| index | number | Index of the selected button in the array.| + + +## prompt.showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + + +**Example** + ``` + export default { + callback(err, data) { + if(err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }, + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }, this.callback) + } + } + ``` + +## prompt.showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| + +**Return value** +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Example** + ``` + export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) + } + } + ``` +## ActionMenuOptions + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| buttons | Array | Yes | Array of menu items. The array structure is **{text:'button', color: '\#666666'}**. One to six items are supported. If there are more than six items, extra items will not be displayed.| + +## ActionMenuSuccessResponse + +Describes the action menu response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------------------ | +| index | number | No | Index of the selected button in the array, starting from **0**.| diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 543dcf5ea8664993511256b4f41a4e859bba0327..b773be32727a995718493a767655b8445f984919 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -117,6 +117,7 @@ let result = queue.getFirst(); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 86090ef47d9add9dba3d2c0836e76b8d7f6ab989..468091db605fd24ac24887c126238cea264c3a52 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -173,7 +173,7 @@ Obtains the network selection mode of the SIM card in the specified slot. This A | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[NetworkSelectionMode](#networkselectionMode)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[NetworkSelectionMode](#networkselectionmode)\> | Yes | Callback used to return the result. | **Example** @@ -622,7 +622,7 @@ Defines the network registration status. | isRoaming | boolean | Whether the user is roaming.| | regState | [RegState](#regstate) | Network registration status of the device.| | cfgTech8+ | [RadioTechnology](#radiotechnology) | RAT of the device.| -| nsaState | [NsaState](#nsaState) | NSA network registration status of the device.| +| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.| | isCaActive | boolean | CA status.| | isEmergency | boolean | Whether only emergency calls are allowed.| diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index da7f0ae7bbac41be20f73b958f92317756e4de1e..8d8b442bcfdfff03f6b1e4214c1033b1061fb00c 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -11,30 +11,28 @@ import reminderAgent from'@ohos.reminderAgent'; ``` -## Required Permissions - -ohos.permission.PUBLISH_AGENT_REMINDER - - ## reminderAgent.publishReminder publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void Publishes an agent-powered reminder. This API uses an asynchronous callback to return the result. -- System capability +**Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent + +**Parameters** -- Parameters | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| -- Example +**Example** ``` - export default { data: {timer: { + export default { + data: { + timer: { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } @@ -53,23 +51,23 @@ publishReminder(reminderReq: ReminderRequest): Promise<number> Publishes an agent-powered reminder. This API uses a promise callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the published reminder's ID.| -- Example +**Example** ``` - export default { data: {timer: { + export default { + data: + {timer: { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } @@ -89,22 +87,21 @@ cancelReminder(reminderId: number, callback: AsyncCallback<void>): void Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { - cancel() { reminderAgent.cancelReminder(1, (err, data) => { + cancel() { + reminderAgent.cancelReminder(1, (err, data) => { console.log("do next"); }); } @@ -118,23 +115,21 @@ cancelReminder(reminderId: number): Promise<void> Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { @@ -153,17 +148,15 @@ getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| -- Example +**Example** ``` reminderAgent.getValidReminders((err, reminders) => { @@ -198,20 +191,18 @@ getValidReminders(): Promise<Array<ReminderRequest>> Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| -- Example +**Example** ``` -reminderAgent.getValidReminders().then((reminders) => { +reminderAgent.getValidReminders().then((reminders) => { for (let i = 0; i < reminders.length; i++) { console.log("getValidReminders = " + reminders[i]); console.log("getValidReminders, reminderType = " + reminders[i].reminderType); @@ -243,20 +234,18 @@ cancelAllReminders(callback: AsyncCallback<void>): void Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` -reminderAgent.cancelAllReminders((err, data) =>{ +reminderAgent.cancelAllReminders((err, data) =>{ console.log("do next")}) ``` @@ -267,17 +256,15 @@ cancelAllReminders(): Promise<void> Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` reminderAgent.cancelAllReminders().then(() => { @@ -291,18 +278,16 @@ addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>) Adds a reminder notification slot. This API uses an asynchronous callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { data: { mySlot: { @@ -324,23 +309,21 @@ addNotificationSlot(slot: NotificationSlot): Promise<void> Adds a reminder notification slot. This API uses a promise to return the result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Reminder notification slot to add.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { data: { mySlot: { @@ -362,18 +345,16 @@ removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback& Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. -- System capability - - SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| | callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| -- Example +**Example** ``` export default { @@ -391,23 +372,21 @@ removeNotificationSlot(slotType: notification.SlotType): Promise<void> Removes a notification slot of a specified type. This API uses a promise to return the result. -- System capability +**System capability**: SystemCapability.Notification.ReminderAgent - SystemCapability.Notification.ReminderAgent - -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| -- Return value +**Return value** | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| -- Example +**Example** ``` export default { @@ -423,7 +402,7 @@ export default { Enumerates button types. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Default Value| Description| | -------- | -------- | -------- | @@ -435,7 +414,7 @@ Enumerates button types. Enumerates reminder types. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Default Value| Description| | -------- | -------- | -------- | @@ -448,7 +427,7 @@ Enumerates reminder types. Defines a button displayed in the reminder notification. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -460,7 +439,7 @@ Defines a button displayed in the reminder notification. Sets the package and ability that are redirected to when the reminder notification is clicked. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -472,7 +451,7 @@ Sets the package and ability that are redirected to when the reminder notificati Sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -484,7 +463,7 @@ Sets the name of the target package and ability to start automatically when the Defines the reminder to publish. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -509,7 +488,7 @@ ReminderRequestCalendar extends ReminderRequest Defines a reminder for a calendar event. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -524,9 +503,9 @@ ReminderRequestAlarm extends ReminderRequest Defines a reminder for an alarm. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent -| Name| Type| Mandatory| Description:| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| @@ -539,7 +518,7 @@ ReminderRequestTimer extends ReminderRequest Defines a reminder for a scheduled timer. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -550,7 +529,7 @@ Defines a reminder for a scheduled timer. Sets the time information for a calendar reminder. -- **System capability**: SystemCapability.Notification.ReminderAgent +**System capability**: SystemCapability.Notification.ReminderAgent | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index e5e05092630126119a870b5e8e430d62abaac43b..19572a3c963ceb80761f3b5961d7323615efa1c0 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -19,9 +19,9 @@ Obtains the **ResourceManager** object of this application. This method uses a c **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------- | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| **Example** ``` @@ -50,10 +50,10 @@ Obtains the **ResourceManager** object of an application. This method uses an as **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | --------- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application. | -| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained. | +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------- | +| bundleName | string | Yes | Bundle name of the target application. | +| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the **ResourceManager** object obtained.| **Example** ``` @@ -71,9 +71,9 @@ Obtains the **ResourceManager** object of this application. This method uses a p **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained. | +| Type | Description | +| ---------------------------------------- | ----------------- | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| **Example** ``` @@ -100,14 +100,14 @@ Obtains the **ResourceManager** object of an application. This method uses a pro **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | --------- | -------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| bundleName | string | Yes | Bundle name of the target application.| **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained. | +| Type | Description | +| ---------------------------------------- | ------------------ | +| Promise<[ResourceManager](#resourcemanager)> | Promise used to return the **ResourceManager** object obtained.| **Example** ``` @@ -125,10 +125,10 @@ Enumerates the screen directions. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------------- | ------------- | ----------- | -| DIRECTION_VERTICAL | 0 | Portrait | -| DIRECTION_HORIZONTAL | 1 | Landscape | +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DIRECTION_VERTICAL | 0 | Portrait | +| DIRECTION_HORIZONTAL | 1 | Landscape | ## DeviceType @@ -137,14 +137,14 @@ Enumerates the device types. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------------- | ------------- | ------------- | -| DEVICE_TYPE_PHONE | 0x00 | Mobile phone. | -| DEVICE_TYPE_TABLET | 0x01 | Tablet. | -| DEVICE_TYPE_CAR | 0x02 | Automobile. | -| DEVICE_TYPE_PC | 0x03 | Computer. | -| DEVICE_TYPE_TV | 0x04 | TV. | -| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | +| Name | Default Value | Description | +| -------------------- | ---- | ---- | +| DEVICE_TYPE_PHONE | 0x00 | Mobile phone. | +| DEVICE_TYPE_TABLET | 0x01 | Tablet. | +| DEVICE_TYPE_CAR | 0x02 | Automobile. | +| DEVICE_TYPE_PC | 0x03 | Computer. | +| DEVICE_TYPE_TV | 0x04 | TV. | +| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. | ## ScreenDensity @@ -153,14 +153,14 @@ Enumerates the screen density types. **System capability**: SystemCapability.Global.ResourceManager -| Name | Default Value | Description | -| -------------- | ------------- | ---------------------------------------- | -| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI). | -| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI). | -| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI). | -| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI). | -| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI). | -| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). | +| Name | Default Value | Description | +| -------------- | ---- | ---------- | +| SCREEN_SDPI | 120 | Screen density with small-scale dots per inch (SDPI). | +| SCREEN_MDPI | 160 | Screen density with medium-scale dots per inch (MDPI). | +| SCREEN_LDPI | 240 | Screen density with large-scale dots per inch (LDPI). | +| SCREEN_XLDPI | 320 | Screen density with extra-large-scale dots per inch (XLDPI). | +| SCREEN_XXLDPI | 480 | Screen density with extra-extra-large-scale dots per inch (XXLDPI). | +| SCREEN_XXXLDPI | 640 | Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).| ## Configuration @@ -170,10 +170,10 @@ Defines the device configuration. **System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Readable | Writable | Description | -| --------- | ----------------------- | -------- | -------- | ------------------------------- | -| direction | [Direction](#direction) | Yes | No | Screen direction of the device. | -| locale | string | Yes | No | Current system language. | +| Name | Type | Readable | Writable | Description | +| --------- | ----------------------- | ---- | ---- | -------- | +| direction | [Direction](#direction) | Yes | No | Screen direction of the device.| +| locale | string | Yes | No | Current system language. | ## DeviceCapability @@ -183,10 +183,10 @@ Defines the device capability. **System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Readable | Writable | Description | -| ------------- | ------------------------------- | -------- | -------- | ----------------------------- | -| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | +| Name | Type | Readable | Writable | Description | +| ------------- | ------------------------------- | ---- | ---- | -------- | +| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.| +| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. | ## RawFileDescriptor8+ @@ -194,11 +194,11 @@ Defines the device capability. Defines the descriptor information of the raw file.
**System capability**: SystemCapability.Global.ResourceManager -| Name | Type | Description | -| ------ | ------ | ---------------------------------------- | -| fd | number | Descriptor of a raw file. | -| offset | number | Offset to the start position of the raw file. | -| length | number | Length of the raw file. | +| Name | Type | Description | +| ------ | ------ | ------------------ | +| fd | number | Descriptor of a raw file.| +| offset | number | Offset to the start position of the raw file. | +| length | number | Length of the raw file. | ## ResourceManager @@ -220,10 +220,10 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the string obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the string obtained.| **Example** ``` @@ -248,14 +248,14 @@ Obtains the string corresponding to the specified resource ID. This method uses **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the string obtained. | +| Type | Description | +| --------------------- | ----------- | +| Promise<string> | Promise used to return the string obtained.| **Example** ``` @@ -278,10 +278,10 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the obtained array of strings. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------- | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the obtained array of strings.| **Example** ``` @@ -306,14 +306,14 @@ Obtains the array of strings corresponding to the specified resource ID. This me **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ---------------------------------- | ---------------------------------------- | -| Promise<Array<string>> | Promise used to return the array of strings obtained. | +| Type | Description | +| ---------------------------------- | ------------- | +| Promise<Array<string>> | Promise used to return the array of strings obtained.| **Example** ``` @@ -336,10 +336,10 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the content of the media file obtained. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the content of the media file obtained.| **Example** ``` @@ -364,14 +364,14 @@ Obtains the content of the media file corresponding to the specified resource ID **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| ------------------------- | ---------------------------------------- | -| Promise<Uint8Array> | Promise used to return the content of the media file obtained. | +| Type | Description | +| ------------------------- | -------------- | +| Promise<Uint8Array> | Promise used to return the content of the media file obtained.| **Example** ``` @@ -394,10 +394,10 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| callback | AsyncCallback<string> | Yes | Callback used to return the Base64 code of the image obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------ | +| resId | number | Yes | Resource ID. | +| callback | AsyncCallback<string> | Yes | Callback used to return the Base64 code of the image obtained.| **Example** ``` @@ -422,14 +422,14 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ------------ | -| resId | number | Yes | Resource ID. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the Base64 code of the image obtained. | +| Type | Description | +| --------------------- | -------------------- | +| Promise<string> | Promise used to return the Base64 code of the image obtained.| **Example** ``` @@ -452,9 +452,9 @@ Obtains the device configuration. This method uses an asynchronous callback to r **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the obtained device configuration. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------- | +| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the obtained device configuration.| **Example** ``` @@ -479,9 +479,9 @@ Obtains the device configuration. This method uses a promise to return the resul **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[Configuration](#configuration)> | Promise used to return the device configuration. | +| Type | Description | +| ---------------------------------------- | ---------------- | +| Promise<[Configuration](#configuration)> | Promise used to return the device configuration.| **Example** ``` @@ -504,9 +504,9 @@ Obtains the device capability. This method uses an asynchronous callback to retu **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the obtained device capability. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the obtained device capability.| **Example** ``` @@ -531,9 +531,9 @@ Obtains the device capability. This method uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability. | +| Type | Description | +| ---------------------------------------- | ------------------- | +| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the obtained device capability.| **Example** ``` @@ -556,11 +556,11 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number that determines the plural or singular form. | -| callback | AsyncCallback<string> | Yes | Callback used to return the singular-plural string obtained. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ------------------------------- | +| resId | number | Yes | Resource ID. | +| num | number | Yes | Number that determines the plural or singular form. | +| callback | AsyncCallback<string> | Yes | Callback used to return the singular-plural string obtained.| **Example** ``` @@ -585,15 +585,15 @@ Obtains the specified number of singular-plural strings corresponding to the spe **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | --------- | ---------------------------------------- | -| resId | number | Yes | Resource ID. | -| num | number | Yes | Number that determines the plural or singular form. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----- | +| resId | number | Yes | Resource ID.| +| num | number | Yes | Number that determines the plural or singular form. | **Return value** -| Type | Description | -| --------------------- | ---------------------------------------- | -| Promise<string> | Promise used to return the singular-plural string obtained. | +| Type | Description | +| --------------------- | ------------------------- | +| Promise<string> | Promise used to return the singular-plural string obtained.| **Example** ``` @@ -615,10 +615,10 @@ Obtains the content of the raw file in the specified path. This method uses an a **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ---------------------------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the raw file content, in byte arrays. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ----------------------- | +| path | string | Yes | Path of the raw file. | +| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the raw file content, in byte arrays.| **Example** ``` @@ -642,14 +642,14 @@ Obtains the content of the raw file in the specified path. This method uses a pr **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | --------------------- | -| path | string | Yes | Path of the raw file. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| path | string | Yes | Path of the raw file.| **Return value** -| Type | Description | -| ------------------------- | ---------------------------------------- | -| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays. | +| Type | Description | +| ------------------------- | ----------- | +| Promise<Uint8Array> | Promise used to return the raw file content, in byte arrays.| **Example** ``` @@ -671,10 +671,10 @@ Obtains the descriptor of the raw file in the specified path. This method uses a **System capability**: SystemCapability.Global.ResourceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ---------------------------------------- | -| path | string | Yes | Path of the raw file. | -| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8+ ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. + +## Modules to Import + +``` +import router from '@ohos.router' +``` + +## Required Permissions + +None. + +## router.push + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Page routing parameters.| + + +**Example** + ``` + // Current page + export default { + pushPage() { + router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } + } + ``` + ``` + // routerpage2 page + export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } + } + ``` + + +## router.replace + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Description of the new page.| + +**Example** + ``` + // Current page + export default { + replacePage() { + router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + ``` + + ``` + // detail page + export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } + } + ``` + +## router.back + +back(options?: RouterOptions ): void + +Returns to the previous page or a specified page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [RouterOptions](#routeroptions) | Yes| Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.| + +**Example** + ``` + // index page + export default { + indexPushPage() { + router.push({ + url: 'pages/detail/detail', + }); + } + } + ``` + + ``` + // detail page + export default { + detailPushPage() { + router.push({ + url: 'pages/mall/mall', + }); + } + } + ``` + + ``` + // Navigate from the mall page to the detail page through router.back(). + export default { + mallBackPage() { + router.back(); + } + } + ``` + + ``` + // Navigate from the detail page to the index page through router.back(). + export default { + defaultBack() { + router.back(); + } + } + ``` + + ``` + // Return to the detail page through router.back(). + export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } + } + ``` + +## router.clear + +clear(): void + +Clears all historical pages in the stack and retains only the current page at the top of the stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + ``` + export default { + clearPage() { + router.clear(); + } + } + ``` + +## router.getLength + +getLength(): string + +Obtains the number of pages in the current stack. + +**Return value** + | Type| Description| + | -------- | -------- | + | string | Number of pages in the stack. The maximum value is **32**.| + +**Example** + ``` + export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } + } + ``` + +## router.getState + +getState(): RouterState + +Obtains state information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| [RouterState](#routerstate) | Page routing state.| +## RouterState +Describes the page routing state. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + | Name| Type| Description| + | -------- | -------- | -------- | + | index | number | Index of the current page in the stack.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The index starts from 1 from the bottom to the top of the stack.| + | name | string | Name of the current page, that is, the file name.| + | path | string | Path of the current page.| + +**Example** + ``` + export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } + } + ``` + +## router.enableAlertBeforeBackPage + +enableAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [EnableAlertOptions](#enablealertoptions) | Yes| Description of the dialog box.| + +**Example** + + ``` + export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` +## EnableAlertOptions + +Describes the confirm dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| message | string | Yes| Content displayed in the confirm dialog box.| + +## router.disableAlertBeforeBackPage + +disableAlertBeforeBackPage(): void + +Disables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + ``` + export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage(); + } + } + ``` + +## router.getParams + +getParams(): Object + +Obtains the parameters passed from the page that initiates redirection to the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| Object | Parameters passed from the page that initiates redirection to the current page.| + +**Example** + +- Web-like example + ``` + // Current page + export default { + pushPage() { + router.push({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + ``` + ``` + // detail page + export default { + onInit() { + console.info('showData1:' + router.getParams().data1); + } + } + ``` + +- Declarative example + + ``` + // Navigate to the target page through router.push with the params parameter carried. + import router from '@ohos.router' + + @Entry + @Component + struct Index { + async routePage() { + let options = { + url: 'pages/second', + params: { + text: 'This is the value on the first page.', + data: { + array: [12, 45, 78] + }, + } + } + try { + await router.push(options) + } catch (err) { + console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`) + } + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('This is the first page.') + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { + this.routePage() + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ``` + // Receive the transferred parameters on the second page. + import router from '@ohos.router' + + @Entry + @Component + struct Second { + private content: string = "This is the second page." + @State text: string = router.getParams().text + @State data: any = router.getParams().data + @State secondData : string = '' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text(`${this.content}`) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Text(this.text) + .fontSize(30) + .onClick(()=>{ + this.secondData = (this.data.array[1]).toString() + }) + .margin({top:20}) + Text('Value from the first page '+'' + this.secondData) + .fontSize(20) + .margin({top:20}) + .backgroundColor('red') + } + .width('100%') + .height('100%') + } + } + ``` + +## RouterOptions + +Describes the page routing options. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| URI of the destination page, in either of the following formats:
-  Absolute path of the page. The value is available in the pages list in the config.json file, for example:
  - pages/index/index
  - pages/detail/detail
-  Particular path. If the URI is a slash (/), the home page is displayed.| +| params | Object | No| Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| + + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > The page routing stack supports a maximum of 32 pages. diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index b2d01bd6da98d2781c3c6116af2b0a4817b6a47b..4a9ba2ab233a0e853ffb29d436ac8fd4e61dfe9b 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -107,16 +107,16 @@ Creates a **RunningLock** object. **Example** ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - var used = runninglock.isUsed(); - console.info('runninglock is used: ' + used); - runninglock.lock(500); - used = runninglock.isUsed(); - console.info('after lock runninglock is used ' + used); -}) -.catch(error => { - console.log('create runningLock test error: ' + error); +runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { + if (typeof error === "undefined") { + console.log('create runningLock test error: ' + error); + } else { + var used = lockIns.isUsed(); + console.info('runninglock is used: ' + used); + lockIns.lock(500); + used = lockIns.isUsed(); + console.info('after lock runninglock is used ' + used); + } }) ``` @@ -170,11 +170,13 @@ Locks and holds a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core +**Required permission:** ohos.permission.RUNNING_LOCK + **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | -------------------- | -| timeout | number | No | Duration for locking and holding the **RunningLock** object.| +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | -------------------------- | +| timeout | number | No | Duration for locking and holding the **RunningLock** object, in ms.| **Example** @@ -185,7 +187,7 @@ runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.B console.info('create runningLock success') }) .catch(error => { - console.log('Lock runningLock test error: ' + error) + console.log('create runningLock test error: ' + error) }); ``` @@ -198,16 +200,18 @@ Releases a **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core +**Required permission:** ohos.permission.RUNNING_LOCK + **Example** ``` runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) .then(runningLock => { runningLock.unlock() - console.info('unLock runningLock success') + console.info('create and unLock runningLock success') }) .catch(error => { - console.log('unLock runningLock test error: ' + error) + console.log('create runningLock test error: ' + error) }); ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index b163b58eb419404541c7e570ef349579d53729eb..6164de2a46b167097d43da2db6fad4f76f2306dd 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -22,14 +22,14 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| - | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes| Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); @@ -51,14 +51,14 @@ Subscribes to data changes of the linear acceleration sensor. If this API is cal **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| - | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(data){ console.info('X-coordinate component: ' + data.x); @@ -80,14 +80,14 @@ Subscribes to data changes of the uncalibrated acceleration sensor. If this API **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| - | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -110,14 +110,14 @@ Subscribes to data changes of the gravity sensor. If this API is called multiple **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**.| - | callback | Callback<[GravityResponse](#gravityresponse)> | Yes| Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ console.info('X-coordinate component: ' + data.x); @@ -139,14 +139,14 @@ Subscribes to data changes of the gyroscope sensor. If this API is called multip **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**.| - | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ console.info('X-coordinate component: ' + data.x); @@ -168,14 +168,14 @@ Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| - | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -198,14 +198,14 @@ Subscribes to data changes of the significant motion sensor. If this API is call **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| - | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ console.info('Scalar data: ' + data.scalar); @@ -225,14 +225,14 @@ Subscribes to data changes of the pedometer detection sensor. If this API is cal **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| - | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes| Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ console.info('Scalar data: ' + data.scalar); @@ -252,14 +252,14 @@ Subscribes to data changes of the pedometer sensor. If this API is called multip **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**.| - | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes| Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ console.info('Steps: ' + data.steps); @@ -277,14 +277,14 @@ Subscribes to data changes of the ambient temperature sensor. If this API is cal **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| - | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(data){ console.info('Temperature: ' + data.temperature); @@ -302,14 +302,14 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| - | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(data){ console.info('X-coordinate component: ' + data.x); @@ -323,20 +323,20 @@ Subscribes to data changes of the magnetic field sensor. If this API is called m ## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options: Options): void +on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback: Callback<MagneticFieldUncalibratedResponse>, options?: Options): void Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| - | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ console.info('X-coordinate component: ' + data.x); @@ -359,14 +359,14 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**.| - | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes| Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ console.info('Distance: ' + data.distance); @@ -384,14 +384,14 @@ Subscribes to data changes of the humidity sensor. If this API is called multipl **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**.| - | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes| Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(data){ console.info('Humidity: ' + data.humidity); @@ -409,14 +409,14 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**.| - | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes| Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(data){ console.info('Atmospheric pressure: ' + data.pressure); @@ -434,14 +434,14 @@ Subscribes to data changes of the Hall effect sensor. If this API is called mult **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**.| - | callback | Callback<[HallResponse](#hallresponse)> | Yes| Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ console.info('Status: ' + data.status); @@ -459,14 +459,14 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| - | callback | Callback<[LightResponse](#lightresponse)> | Yes| Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(data){ console.info(' Illumination: ' + data.intensity); @@ -484,14 +484,14 @@ Subscribes to data changes of the orientation sensor. If this API is called mult **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**.| - | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes| Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ console.info('The device rotates at an angle around the X axis: ' + data.beta); @@ -512,14 +512,14 @@ Subscribes to only one data change of the heart rate sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE,function(data){ @@ -537,14 +537,14 @@ Subscribes to data changes of the rotation vector sensor. If this API is called **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| - | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ console.info('X-coordinate component: ' + data.x); @@ -565,14 +565,14 @@ Subscribes to data changes of the wear detection sensor. If this API is called m **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| - | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes| Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| - | options | [Options](#options) | No| Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | -- Example +**Example** ``` sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ console.info('Wear status: ' + data.value); @@ -592,13 +592,13 @@ Subscribes to only one data change of the acceleration sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| - | callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes| One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER**. | +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ console.info('X-coordinate component: ' + data.x); @@ -619,13 +619,13 @@ Subscribes to only one data change of the linear acceleration sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| - | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes| One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(data) { console.info('X-coordinate component: ' + data.x); @@ -646,13 +646,13 @@ Subscribes to only one data change of the uncalibrated acceleration sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| - | callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -674,13 +674,13 @@ Subscribes to only one data change of the gravity sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**.| - | callback | Callback<[GravityResponse](#gravityresponse)> | Yes| One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { console.info('X-coordinate component: ' + data.x); @@ -701,13 +701,13 @@ Subscribes to only one data change of the gyroscope sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**.| - | callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes| One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE**. | +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { console.info('X-coordinate component: ' + data.x); @@ -728,13 +728,13 @@ Subscribes to only one data change of the uncalibrated gyroscope sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| - | callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -756,13 +756,13 @@ Subscribes to only one data change of the significant motion sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| - | callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes| One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { console.info('Scalar data: ' + data.scalar); @@ -781,13 +781,13 @@ Subscribes to only one data change of the pedometer detection sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| - | callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes| One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { console.info('Scalar data: ' + data.scalar); @@ -806,13 +806,13 @@ Subscribes to only one data change of the pedometer sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**.| - | callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes| One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { console.info('Steps: ' + data.steps); @@ -829,13 +829,13 @@ Subscribes to only one data change of the ambient temperature sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| - | callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes| One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { console.info('Temperature: ' + data.temperature); @@ -852,13 +852,13 @@ Subscribes to only one data change of the magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| - | callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes| One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | +| callback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { console.info('X-coordinate component: ' + data.x); @@ -877,13 +877,13 @@ Subscribes to only one data change of the uncalibrated magnetic field sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| - | callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes| One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { console.info('X-coordinate component: ' + data.x); @@ -905,13 +905,13 @@ Subscribes to only one data change of the proximity sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**.| - | callback | Callback<[ProximityResponse](#proximityresponse)> | Yes| One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_PROXIMITY**. | +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { @@ -932,13 +932,13 @@ Subscribes to only one data change of the humidity sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**.| - | callback | Callback<[HumidityResponse](#humidityresponse)> | Yes| One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { console.info('Humidity: ' + data.humidity); @@ -955,13 +955,13 @@ Subscribes to only one data change of the barometer sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**.| - | callback | Callback<[BarometerResponse](#barometerresponse)> | Yes| One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_BAROMETER**. | +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { console.info('Atmospheric pressure: ' + data.pressure); @@ -978,13 +978,13 @@ Subscribes to only one data change of the Hall effect sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**.| - | callback | Callback<[HallResponse](#hallresponse)> | Yes| One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------------ | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { console.info('Status: ' + data.status); @@ -1001,13 +1001,13 @@ Subscribes to only one data change of the ambient light sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| - | callback | Callback<[LightResponse](#lightresponse)> | Yes| One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | -------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| +| callback | Callback<[LightResponse](#lightresponse)> | Yes | One-shot callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(data) { console.info(' Illumination: ' + data.intensity); @@ -1024,13 +1024,13 @@ Subscribes to only one data change of the orientation sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**.| - | callback | Callback<[OrientationResponse](#orientationresponse)> | Yes| One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ORIENTATION**. | +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { console.info('The device rotates at an angle around the X axis: ' + data.beta); @@ -1049,13 +1049,13 @@ Subscribes to only one data change of the rotation vector sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| - | callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes| One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { console.info('X-coordinate component: ' + data.x); @@ -1077,13 +1077,13 @@ Subscribes to only one data change of the heart rate sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**.| - | callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes| One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(data) { console.info("Heart rate: " + data.heartRate); @@ -1100,13 +1100,13 @@ Subscribes to only one data change of the wear detection sensor. **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | [SensorType](#sensortype) | Yes| Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| - | callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes| One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -- Example +**Example** ``` sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { console.info("Wear status: "+ data.value); @@ -1124,14 +1124,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| -| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER**.| +| callback | Callback<[AccelerometerResponse](#accelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1152,14 +1152,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| -| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED**.| +| callback | Callback<[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)> | Yes | Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1181,14 +1181,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| -| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_LIGHT**.| +| callback | Callback<[LightResponse](#lightresponse)> | Yes | Callback used to return the ambient light sensor data. The reported data type in the callback is **LightResponse**. | -- Example +**Example** ``` function callback(data) { @@ -1205,14 +1205,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| -| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_AMBIENT_TEMPERATURE**.| +| callback | Callback<[AmbientTemperatureResponse](#ambienttemperatureresponse)> | Yes | Callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1229,14 +1229,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**. | -| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_BAROMETER**.| +| callback | Callback<[BarometerResponse](#barometerresponse)> | Yes | Callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1253,14 +1253,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | -| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GRAVITY**. | +| callback | Callback<[GravityResponse](#gravityresponse)> | Yes | Callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1281,14 +1281,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**. | -| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE**.| +| callback | Callback<[GyroscopeResponse](#gyroscoperesponse)> | Yes | Callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1301,7 +1301,7 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); ## sensor.off(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeResponse>): void +off(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback?: Callback<GyroscopeUncalibratedResponse>): void Unsubscribes from sensor data changes. @@ -1309,14 +1309,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| -| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED**.| +| callback | Callback<[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)> | Yes | Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1335,14 +1335,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | -| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HALL**. | +| callback | Callback<[HallResponse](#hallresponse)> | Yes | Callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1361,14 +1361,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype)[SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**.| +| callback | Callback<[HeartRateResponse](#heartrateresponse)> | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1387,14 +1387,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | -| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HUMIDITY**. | +| callback | Callback<[HumidityResponse](#humidityresponse)> | Yes | Callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1413,14 +1413,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**.| +| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1441,14 +1441,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**. | -| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD**.| +| callbackcallback | Callback<[MagneticFieldResponse](#magneticfieldresponse)> | Yes | Callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1467,14 +1467,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| -| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED**.| +| callback | Callback<[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)> | Yes | Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1496,14 +1496,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**. | -| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ORIENTATION**.| +| callback | Callback<[OrientationResponse](#orientationresponse)> | Yes | Callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1522,14 +1522,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | -| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER**. | +| callback | Callback<[PedometerResponse](#pedometerresponse)> | Yes | Callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**.| -- Example +**Return value** ``` function callback(data) { @@ -1548,14 +1548,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| -| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PEDOMETER_DETECTION**.| +| callback | Callback<[PedometerDetectionResponse](#pedometerdetectionresponse)> | Yes | Callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1572,14 +1572,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**. | -| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_PROXIMITY**.| +| callback | Callback<[ProximityResponse](#proximityresponse)> | Yes | Callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1596,14 +1596,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| -| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_ROTATION_VECTOR**.| +| callback | Callback<[RotationVectorResponse](#rotationvectorresponse)> | Yes | Callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1623,14 +1623,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| -| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_SIGNIFICANT_MOTION**.| +| callback | Callback<[SignificantMotionResponse](#significantmotionresponse)> | Yes | Callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**.| -- Example +**Example** ``` function callback(data) { @@ -1647,14 +1647,14 @@ Unsubscribes from sensor data changes. **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| -| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_WEAR_DETECTION**.| +| callback | Callback<[WearDetectionResponse](#weardetectionresponse)> | Yes | Callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**.| -- Example +**Example** ``` function accCallback(data) { @@ -1671,29 +1671,28 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ---------------- | ----------------------------------------- | ---- | ---------------------- | - | inRotationVector | Array<number> | Yes | Rotation vector to rotate. | - | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | - | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------------- | ---- | ----------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation vector after being rotated.| -- Example - - ``` - sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}, function(err, data) { - if (err) { - console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); - return; - } - console.info("Operation successed. Data obtained: " + data.x); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }) - ``` +**Example** +``` +sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}, function(err, data) { + if (err) { + console.error("Operation failed. Error code: " + err.code + ", message: " + err.message); + return; + } + console.info("Operation successed. Data obtained: " + data.x); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }) +``` ## sensor.transformCoordinateSystem transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> @@ -1702,35 +1701,32 @@ Rotates a rotation vector so that it can represent the coordinate system in diff **System capability**: SystemCapability.Sensors.Sensor -- Parameters - - | Name | Type | Mandatory| Description | - | ---------------- | ----------------------------------------- | ---- | ---------------- | - | inRotationVector | Array<number> | Yes | Rotation vector to rotate. | - | coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| - -- Return value +**Parameters** - | Type | Description | - | ---------------------------------- | ---------------------- | - | Promise<Array<number>> | Promise used to return the rotation vector after being converted.| +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------------- | ---- | -------- | +| inRotationVector | Array<number> | Yes | Rotation vector to rotate. | +| coordinates | [CoordinatesOptions](#coordinatesoptions) | Yes | Direction of the coordinate system.| -- Example +**Return value** - ``` - const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}); - promise.then((data) => { - console.info("Operation successed."); - for (var i=0; i < data.length; i++) { - console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); - } - }).catch((err) => { - console.info("Operation failed"); - }) - ``` +| Type | Description | +| ---------------------------------- | ----------- | +| Promise<Array<number>> | Promise used to return the rotation vector after being rotated.| - +**Example** +``` +const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {'axisX':2, 'axisY':3}); + promise.then((data) => { + console.info("Operation successed."); + for (var i=0; i < data.length; i++) { + console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); + } + }).catch((err) => { + console.info("Operation failed"); +}) +``` ## sensor.getGeomagneticField @@ -1740,27 +1736,25 @@ Obtains the geomagnetic field of a geographic location. This API uses a callback **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locationOptions | [LocationOptions](#locationoptions) | Yes| Geographic location.| - | timeMillis | number | Yes| Time for obtaining the magnetic declination, in milliseconds.| - | callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes| Callback used to return the geomagnetic field.| - -- Example - ``` - sensor.getGeomagneticField([80, 0, 0], {'timeMillis':1580486400000}, function(err, data) { - if (err) { - console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); - return; - } - console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + - data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + - ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); - }); - ``` - +**Parameters** +| Name | Type | Mandatory | Description | +| --------------- | ---------------------------------------- | ---- | ----------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | +**Example** +``` +sensor.getGeomagneticField([80, 0, 0], 1580486400000, function(err, data) { + if (err) { + console.error('Operation failed. Error code: ' + err.code + '; message: ' + err.message); + return; + } + console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); +}); +``` ## sensor.getGeomagneticField getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> @@ -1769,20 +1763,20 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise **System capability**: SystemCapability.Sensors.Sensor -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | locationOptions | [LocationOptions](#locationoptions) | Yes| Geographic location.| - | timeMillis | number | Yes| Time for obtaining the magnetic declination, in milliseconds.| +**Parameters** +| Name | Type | Mandatory | Description | +| --------------- | ----------------------------------- | ---- | ----------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| +**Return value** +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[GeomagneticResponse](#geomagneticresponse)> | Promise used to return the geomagnetic field.| -- Example +**Return value** ``` - const promise = sensor.getGeomagneticField([80, 0, 0], {'timeMillis':1580486400000}); + const promise = sensor.getGeomagneticField([80, 0, 0], 1580486400000); promise.then((data) => { console.info('sensor_getGeomagneticField_promise x: ' + data.x + ',y: ' + data.y + ',z: ' + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + @@ -1800,15 +1794,15 @@ Obtains the altitude at which the device is located based on the sea-level atmos **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------- | --------------------------- | ---- | ------------------------------------- | - | seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | - | currentPressure | number | Yes | Current atmospheric pressure at the altitude where the device is located, in hPa.| - | callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | ---- | -------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| callback | AsyncCallback<number> | Yes | Callback used to return the altitude, in meters. | -- Example +**Return value** ``` sensor.getAltitude(0, 200, function(err, data) { @@ -1829,20 +1823,20 @@ Obtains the altitude at which the device is located based on the sea-level atmos **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------- | ------ | ---- | ------------------------------------- | - | seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | - | currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| +| Name | Type | Mandatory | Description | +| --------------- | ------ | ---- | -------------------- | +| seaPressure | number | Yes | Sea-level atmospheric pressure, in hPa. | +| currentPressure | number | Yes | Atmospheric pressure at the altitude where the device is located, in hPa.| -- Return value +**Return value** - | Type | Description | - | --------------------- | ------------------------------------ | - | Promise<number> | Promise used to return the altitude, in meters.| +| Type | Description | +| --------------------- | ------------------ | +| Promise<number> | Promise used to return the altitude, in meters.| -- Example +**Return value** ``` const promise = sensor.getAltitude(0, 200); @@ -1862,14 +1856,14 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ----------------- | --------------------------- | ---- | ---------------------------- | - | inclinationMatrix | Array<number> | Yes | Inclination matrix. | - | callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| +| Name | Type | Mandatory | Description | +| ----------------- | --------------------------- | ---- | -------------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix. | +| callback | AsyncCallback<number> | Yes | Callback used to return the magnetic dip, in radians.| -- Example +**Return value** ``` sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { @@ -1878,7 +1872,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a callba err.message); return; } - console.info(Successed to get getGeomagneticDip interface get data: " + data); + console.info("Successed to get getGeomagneticDip interface get data: " + data); }) ``` @@ -1890,19 +1884,19 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ----------------- | ------------------- | ---- | -------------- | - | inclinationMatrix | Array<number> | Yes | Inclination matrix.| +| Name | Type | Mandatory | Description | +| ----------------- | ------------------- | ---- | ------- | +| inclinationMatrix | Array<number> | Yes | Inclination matrix.| -- Return value +**Return value** - | Type | Description | - | --------------------- | ---------------------------- | - | Promise<number> | Promise used to return the magnetic dip, in radians.| +| Type | Description | +| --------------------- | -------------- | +| Promise<number> | Promise used to return the magnetic dip, in radians.| -- Example +**Return value** ``` const promise = sensor.getGeomagneticDip([1, 0, 0, 0, 1, 0, 0, 0, 1]); @@ -1921,15 +1915,15 @@ Obtains the angle change between two rotation matrices. This API uses a callback **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------------- | ---------------------------------------- | ---- | --------------------------------- | - | currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | - | preRotationMatrix | Array<number> | Yes | The other rotation matrix. | - | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| +| Name | Type | Mandatory | Description | +| --------------------- | ---------------------------------------- | ---- | ------------------ | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix. | +| preRotationMatrix | Array<number> | Yes | The other rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the angle change around the z, x, and y axes.| -- Example +**Return value** ``` sensor. getAngleModify([1,0,0,0,1,0,0,0,1], [1, 0, 0, 0, 0.87, -0.50, 0, 0.50, 0.87], function(err, data) { @@ -1954,20 +1948,20 @@ Obtains the angle change between two rotation matrices. This API uses a promise **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | --------------------- | ------------------- | ---- | ------------------ | - | currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| - | preRotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory | Description | +| --------------------- | ------------------- | ---- | --------- | +| currentRotationMatrix | Array<number> | Yes | Current rotation matrix.| +| preRotationMatrix | Array<number> | Yes | Rotation matrix. | -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | --------------------------------- | - | Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | ------------------ | +| Promise<Array<number>> | Promise used to return the angle change around the z, x, and y axes.| -- Example +**Return value** ``` const promise = sensor.getAngleModify([1,0,0,0,1,0,0,0,1], [1,0,0,0,0.87,-0.50,0,0.50,0.87]); @@ -1990,14 +1984,14 @@ Converts a rotation vector into a rotation matrix. This API uses a callback to r **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ---------------------------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| - | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation matrix.| -- Example +**Return value** ``` sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { @@ -2022,19 +2016,19 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | -------------- | - | Promise<Array<number>> | Promise used to return the rotation matrix.| +| Type | Description | +| ---------------------------------- | ------- | +| Promise<Array<number>> | Promise used to return the rotation matrix.| -- Example +**Return value** ``` const promise = sensor.createRotationMatrix([0.20046076, 0.21907, 0.73978853, 0.60376877]); @@ -2057,14 +2051,14 @@ Converts a rotation vector into a quaternion. This API uses a callback to return **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ---------------------------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| - | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the quaternion. | -- Example +**Return value** ``` sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877], function(err, data) { @@ -2089,19 +2083,19 @@ Converts a rotation vector into a quaternion. This API uses a promise to return **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationVector | Array<number> | Yes | Rotation vector to convert.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationVector | Array<number> | Yes | Rotation vector to convert.| -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | ------------ | - | Promise<Array<number>> | Promise used to return the quaternion.| +| Type | Description | +| ---------------------------------- | ------ | +| Promise<Array<number>> | Promise used to return the quaternion.| -- Example +**Return value** ``` const promise = sensor.createQuaternion([0.20046076, 0.21907, 0.73978853, 0.60376877]); @@ -2124,14 +2118,14 @@ Obtains the device direction based on the rotation matrix. This API uses a callb **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ---------------------------------------- | ---- | --------------------------------- | - | rotationMatrix | Array<number> | Yes | Rotation matrix. | - | callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ------------------ | +| rotationMatrix | Array<number> | Yes | Rotation matrix. | +| callback | AsyncCallback<Array<number>> | Yes | Callback used to return the rotation angle around the z, x, and y axes.| -- Example +**Return value** ``` sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1], function(err, data) { @@ -2156,19 +2150,19 @@ Obtains the device direction based on the rotation matrix. This API uses a promi **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | -------------- | ------------------- | ---- | -------------- | - | rotationMatrix | Array<number> | Yes | Rotation matrix.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------- | ---- | ------- | +| rotationMatrix | Array<number> | Yes | Rotation matrix.| -- Return value +**Return value** - | Type | Description | - | ---------------------------------- | --------------------------------- | - | Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| +| Type | Description | +| ---------------------------------- | ------------------ | +| Promise<Array<number>> | Promise used to return the rotation angle around the z, x, and y axes.| -- Example +**Return value** ``` const promise = sensor.getDirection([1, 0, 0, 0, 1, 0, 0, 0, 1]); @@ -2191,15 +2185,15 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ----------- | ------------------------------------------------------------ | ---- | -------------- | - | gravity | Array<number> | Yes | Gravity vector.| - | geomagnetic | Array<number> | Yes | Geomagnetic vector.| - | callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| callback | AsyncCallback<[RotationMatrixResponse](#rotationmatrixresponse)> | Yes | Callback used to return the rotation matrix.| -- Example +**Return value** ``` sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444], function(err, data) { @@ -2224,20 +2218,20 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th **System capability**: SystemCapability.Sensors.Sensor -- Parameters +**Parameters** - | Name | Type | Mandatory| Description | - | ----------- | ------------------- | ---- | -------------- | - | gravity | Array<number> | Yes | Gravity vector.| - | geomagnetic | Array<number> | Yes | Geomagnetic vector.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | ------- | +| gravity | Array<number> | Yes | Gravity vector.| +| geomagnetic | Array<number> | Yes | Geomagnetic vector.| -- Return value +**Return value** - | Type | Description | - | ------------------------------------------------------------ | -------------- | - | Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[RotationMatrixResponse](#rotationmatrixresponse)> | Promise used to return the rotation matrix.| -- Example +**Return value** ``` const promise = sensor.createRotationMatrix([-0.27775216, 0.5351276, 9.788099], [210.87253, -78.6096, -111.44444]); @@ -2259,29 +2253,29 @@ Enumerates the sensor types. **System capability**: SystemCapability.Sensors.Sensor -| Name| Default Value| Description| -| -------- | -------- | -------- | -| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor.| -| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor.| -| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor.| -| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor.| -| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor.| -| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor.| -| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor.| -| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor.| -| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor.| -| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor.| -| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | Linear acceleration sensor.| -| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor.| -| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor.| -| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor.| -| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor.| -| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor.| -| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor.| -| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor.| -| SENSOR_TYPE_ID_HEART_RATE | 278 | Heart rate sensor.| -| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor.| -| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| +| Name | Default Value | Description | +| ---------------------------------------- | ---- | ----------- | +| SENSOR_TYPE_ID_ACCELEROMETER | 1 | Acceleration sensor. | +| SENSOR_TYPE_ID_GYROSCOPE | 2 | Gyroscope sensor. | +| SENSOR_TYPE_ID_AMBIENT_LIGHT | 5 | Ambient light sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD | 6 | Magnetic field sensor. | +| SENSOR_TYPE_ID_BAROMETER | 8 | Barometer sensor. | +| SENSOR_TYPE_ID_HALL | 10 | Hall effect sensor. | +| SENSOR_TYPE_ID_PROXIMITY | 12 | Proximity sensor. | +| SENSOR_TYPE_ID_HUMIDITY | 13 | Humidity sensor. | +| SENSOR_TYPE_ID_ORIENTATION | 256 | Orientation sensor. | +| SENSOR_TYPE_ID_GRAVITY | 257 | Gravity sensor. | +| SENSOR_TYPE_ID_LINEAR_ACCELERATION | 258 | Linear acceleration sensor. | +| SENSOR_TYPE_ID_ROTATION_VECTOR | 259 | Rotation vector sensor. | +| SENSOR_TYPE_ID_AMBIENT_TEMPERATURE | 260 | Ambient temperature sensor. | +| SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED | 261 | Uncalibrated magnetic field sensor. | +| SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED | 263 | Uncalibrated gyroscope sensor. | +| SENSOR_TYPE_ID_SIGNIFICANT_MOTION | 264 | Significant motion sensor. | +| SENSOR_TYPE_ID_PEDOMETER_DETECTION | 265 | Pedometer detection sensor. | +| SENSOR_TYPE_ID_PEDOMETER | 266 | Pedometer sensor. | +| SENSOR_TYPE_ID_HEART_RATE | 278 | Heart rate sensor. | +| SENSOR_TYPE_ID_WEAR_DETECTION | 280 | Wear detection sensor. | +| SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED | 281 | Uncalibrated acceleration sensor.| ## Response @@ -2290,9 +2284,9 @@ Describes the timestamp of the sensor data. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| timestamp | number | Yes| Yes| Timestamp when the sensor reports data.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------------ | +| timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| ## AccelerometerResponse @@ -2302,11 +2296,11 @@ Describes the acceleration sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes| Yes| Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes| Yes| Acceleration along the z-axis of the device, in m/s2.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ---------------------- | +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| ## LinearAccelerometerResponse @@ -2316,11 +2310,11 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes| Yes| Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes| Yes| Linear acceleration along the z-axis of the device, in m/s2.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------------------------ | +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| ## AccelerometerUncalibratedResponse @@ -2330,14 +2324,14 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Uncalibrated acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes| Yes| Uncalibrated acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes| Yes| Uncalibrated acceleration along the z-axis of the device, in m/s2.| -| biasX | number | Yes| Yes| Uncalibrated acceleration bias along the x-axis of the device, in m/s2.| -| biasY | number | Yes| Yes| Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes| Yes| Uncalibrated acceleration bias along the z-axis of the device, in m/s2.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ---------------------------- | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | ## GravityResponse @@ -2347,11 +2341,11 @@ Describes the gravity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes| Yes| Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes| Yes| Gravitational acceleration along the z-axis of the device, in m/s2.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------------------------ | +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| ## OrientationResponse @@ -2361,11 +2355,11 @@ Describes the orientation sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| alpha | number | Yes| Yes| Rotation angle of the device around the z-axis, in rad.| -| beta | number | Yes| Yes| Rotation angle of the device around the x-axis, in rad.| -| gamma | number | Yes| Yes| Rotation angle of the device around the y-axis, in rad.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ------------------------ | +| alpha | number | Yes | Yes | Rotation angle of the device around the z-axis, in rad.| +| beta | number | Yes | Yes | Rotation angle of the device around the x-axis, in rad. | +| gamma | number | Yes | Yes | Rotation angle of the device around the y-axis, in rad. | ## RotationVectorResponse @@ -2375,12 +2369,12 @@ Describes the rotation vector sensor data. It extends from [Response](#response) **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| X-component of the rotation vector.| -| y | number | Yes| Yes| Y-component of the rotation vector.| -| z | number | Yes| Yes| Z-component of the rotation vector.| -| w | number | Yes| Yes| Scalar.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | --------- | +| x | number | Yes | Yes | X-component of the rotation vector.| +| y | number | Yes | Yes | Y-component of the rotation vector.| +| z | number | Yes | Yes | Z-component of the rotation vector.| +| w | number | Yes | Yes | Scalar. | ## GyroscopeResponse @@ -2390,11 +2384,11 @@ Describes the gyroscope sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Angular velocity of rotation around the x-axis of the device, in rad/s.| -| y | number | Yes| Yes| Angular velocity of rotation around the y-axis of the device, in rad/s.| -| z | number | Yes| Yes| Angular velocity of rotation around the z-axis of the device, in rad/s.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------------------- | +| x | number | Yes | Yes | Angular velocity of rotation around the x-axis of the device, in rad/s.| +| y | number | Yes | Yes | Angular velocity of rotation around the y-axis of the device, in rad/s.| +| z | number | Yes | Yes | Angular velocity of rotation around the z-axis of the device, in rad/s.| ## GyroscopeUncalibratedResponse @@ -2404,14 +2398,14 @@ Describes the uncalibrated gyroscope sensor data. It extends from [Response](#re **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s.| -| y | number | Yes| Yes| Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s.| -| z | number | Yes| Yes| Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s.| -| biasX | number | Yes| Yes| Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| -| biasY | number | Yes| Yes| Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| -| biasZ | number | Yes| Yes| Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ------------------------ | +| x | number | Yes | Yes | Uncalibrated angular velocity of rotation around the x-axis of the device, in rad/s. | +| y | number | Yes | Yes | Uncalibrated angular velocity of rotation around the y-axis of the device, in rad/s. | +| z | number | Yes | Yes | Uncalibrated angular velocity of rotation around the z-axis of the device, in rad/s. | +| biasX | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the x-axis of the device, in rad/s.| +| biasY | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the y-axis of the device, in rad/s.| +| biasZ | number | Yes | Yes | Uncalibrated angular velocity bias of rotation around the z-axis of the device, in rad/s.| ## SignificantMotionResponse @@ -2421,9 +2415,9 @@ Describes the significant motion sensor data. It extends from [Response](#respon **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| scalar | number | Yes| Yes| Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| scalar | number | Yes | Yes | Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| ## ProximityResponse @@ -2433,9 +2427,9 @@ Describes the proximity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| distance | number | Yes| Yes| Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ---------------------------- | +| distance | number | Yes | Yes | Proximity between the visible object and the device monitor. The value **0** means the two are close to each other, and **1** means that they are far away from each other.| ## LightResponse @@ -2445,9 +2439,9 @@ Describes the ambient light sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| intensity | number | Yes| Yes| Illumination, in lux.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ----------- | +| intensity | number | Yes | Yes | Illumination, in lux.| ## HallResponse @@ -2457,9 +2451,9 @@ Describes the Hall effect sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| status | number | Yes| Yes| Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | --------------------------------- | +| status | number | Yes | Yes | Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value **0** means that a magnetic field exists around the device, and **1** means the opposite.| ## MagneticFieldResponse @@ -2469,11 +2463,11 @@ Describes the magnetic field sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Magnetic field strength on the x-axis, in μT.| -| y | number | Yes| Yes| Magnetic field strength on the y-axis, in μT.| -| z | number | Yes| Yes| Magnetic field strength on the z-axis, in μT.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------------------ | +| x | number | Yes | Yes | Magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Magnetic field strength on the z-axis, in μT.| ## MagneticFieldUncalibratedResponse @@ -2483,14 +2477,14 @@ Describes the uncalibrated magnetic field sensor data. It extends from [Response **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| Uncalibrated magnetic field strength on the x-axis, in μT.| -| y | number | Yes| Yes| Uncalibrated magnetic field strength on the y-axis, in μT.| -| z | number | Yes| Yes| Uncalibrated magnetic field strength on the z-axis, in μT.| -| biasX | number | Yes| Yes| Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| -| biasY | number | Yes| Yes| Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| -| biasZ | number | Yes| Yes| Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ---------------------- | +| x | number | Yes | Yes | Uncalibrated magnetic field strength on the x-axis, in μT. | +| y | number | Yes | Yes | Uncalibrated magnetic field strength on the y-axis, in μT. | +| z | number | Yes | Yes | Uncalibrated magnetic field strength on the z-axis, in μT. | +| biasX | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the x-axis, in μT.| +| biasY | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the y-axis, in μT.| +| biasZ | number | Yes | Yes | Bias of the uncalibrated magnetic field strength on the z-axis, in μT.| ## PedometerResponse @@ -2500,9 +2494,9 @@ Describes the pedometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| steps | number | Yes| Yes| Number of steps a user has walked.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | -------- | +| steps | number | Yes | Yes | Number of steps a user has walked.| ## HumidityResponse @@ -2512,9 +2506,9 @@ Describes the humidity sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| humidity | number | Yes| Yes| Ambient relative humidity, in a percentage (%).| +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------------------------------------ | +| humidity | number | Yes | Yes | Ambient relative humidity, in a percentage (%).| ## PedometerDetectionResponse @@ -2524,9 +2518,9 @@ Describes the pedometer detection sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| scalar | number | Yes| Yes| Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| scalar | number | Yes | Yes | Pedometer detection. This parameter specifies whether a user takes a step. The value **0** means that the user does not take a step, and **1** means that the user takes a step.| ## AmbientTemperatureResponse @@ -2536,9 +2530,9 @@ Describes the ambient temperature sensor data. It extends from [Response](#respo **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| temperature | number | Yes| Yes| Ambient temperature, in degree Celsius.| +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------------- | +| temperature | number | Yes | Yes | Ambient temperature, in degree Celsius.| ## BarometerResponse @@ -2548,9 +2542,9 @@ Describes the barometer sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| pressure | number | Yes| Yes| Atmospheric pressure, in pascal.| +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------------ | +| pressure | number | Yes | Yes | Atmospheric pressure, in pascal.| ## HeartRateResponse @@ -2560,9 +2554,9 @@ Describes the heart rate sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| heartRate | number | Yes| Yes| Heart rate, in beats per minute (bpm).| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | --------------------- | +| heartRate | number | Yes | Yes | Heart rate, in beats per minute (bpm).| ## WearDetectionResponse @@ -2572,9 +2566,9 @@ Describes the wear detection sensor data. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| value | number | Yes| Yes| Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ------------------------- | +| value | number | Yes | Yes | Whether the device is being worn. The value **1** means that the device is being worn, and **0** means the opposite.| ## Options @@ -2583,8 +2577,8 @@ Describes the sensor data reporting frequency. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Description| -| -------- | -------- | -------- | +| Name | Type | Description | +| -------- | ------ | --------------------------- | | interval | number | Frequency at which a sensor reports data. The default value is 200,000,000 ns.| ## RotationMatrixResponse @@ -2593,10 +2587,10 @@ Describes the response for setting the rotation matrix. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable| Writable| Description | -| ----------- | ------------------- | ---- | ---- | ---------- | -| rotation | Array<number> | Yes | Yes | Rotation matrix.| -| inclination | Array<number> | Yes | Yes | Inclination matrix.| +| Name | Type | Readable | Writable | Description | +| ----------- | ------------------- | ---- | ---- | ----- | +| rotation | Array<number> | Yes | Yes | Rotation matrix.| +| inclination | Array<number> | Yes | Yes | Inclination matrix.| ## CoordinatesOptions @@ -2605,10 +2599,10 @@ Describes the coordinate options. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description | -| ---- | -------- | ---- | ---- | ----------- | -| x | number | Yes | Yes | X coordinate direction.| -| y | number | Yes | Yes | Y coordinate direction.| +| Name | Type | Readable | Writable | Description | +| ---- | ------ | ---- | ---- | ------ | +| x | number | Yes | Yes | X coordinate direction.| +| y | number | Yes | Yes | Y coordinate direction.| ## GeomagneticResponse @@ -2617,15 +2611,15 @@ Describes a geomagnetic response object. It extends from [Response](#response). **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| x | number | Yes| Yes| North component of the geomagnetic field.| -| y | number | Yes| Yes| East component of the geomagnetic field.| -| z | number | Yes| Yes| Vertical component of the geomagnetic field.| -| geomagneticDip | number | Yes| Yes| Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector.| -| deflectionAngle | number | Yes| Yes| Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| -| levelIntensity | number | Yes| Yes| Horizontal intensity of the magnetic field vector field.| -| totalIntensity | number | Yes| Yes| Total intensity of the magnetic field vector.| +| Name | Type | Readable | Writable | Description | +| --------------- | ------ | ---- | ---- | ------------------------- | +| x | number | Yes | Yes | North component of the geomagnetic field. | +| y | number | Yes | Yes | East component of the geomagnetic field. | +| z | number | Yes | Yes | Vertical component of the geomagnetic field. | +| geomagneticDip | number | Yes | Yes | Magnetic dip, also called magnetic inclination, which is the angle measured from the horizontal plane to the magnetic field vector. | +| deflectionAngle | number | Yes | Yes | Magnetic declination, which is the angle between true north (geographic north) and the magnetic north (the horizontal component of the field).| +| levelIntensity | number | Yes | Yes | Horizontal intensity of the magnetic field vector field. | +| totalIntensity | number | Yes | Yes | Total intensity of the magnetic field vector. | ## LocationOptions @@ -2633,8 +2627,8 @@ Describes the geographical location. **System capability**: SystemCapability.Sensors.Sensor -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| latitude | number | Yes| Yes| Latitude.| -| longitude | number | Yes| Yes| Longitude.| -| altitude | number | Yes| Yes| Altitude.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ----- | +| latitude | number | Yes | Yes | Latitude. | +| longitude | number | Yes | Yes | Longitude. | +| altitude | number | Yes | Yes | Altitude.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-service-extension-ability.md deleted file mode 100644 index c78d82cad48b93519c6b01729e753e6f4d746cb9..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ /dev/null @@ -1,161 +0,0 @@ -# ServiceExtensionAbility - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. - - -Provides APIs related to **ServiceExtension**. - - -## Modules to Import - -``` -import ServiceExtension from '@ohos.application.ServiceExtensionAbility'; -``` - - -## Required Permissions - -None. - - -## Attributes - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service extension context, which is inherited from **ExtensionContext**.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core| - - -## ServiceExtensionAbility.onCreate - -onCreate(want: Want): void; - -Called when an extension is created to initialize the service logic. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onCreate(want) { - console.log('onCreate, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onDestroy - -onDestroy(): void; - -Called when this extension is destroyed to clear resources. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onDestroy() { - console.log('onDestroy'); - } - } - ``` - - -## ServiceExtensionAbility.onRequest - -onRequest(want: Want, startId: number): void; - -Called after **onCreate** is invoked when an ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onRequest(want, startId) { - console.log('onRequest, want:' + want.abilityName); - } - } - ``` - - -## ServiceExtensionAbility.onConnect - -onConnect(want: Want): rpc.RemoteObject; - -Called after **onCreate** is invoked when an ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| - -**Example** - - ```js - import rpc from '@ohos.rpc' - class StubTest extends rpc.RemoteObject{ - constructor(des) { - super(des); - } - onRemoteRequest(code, data, reply, option) { - } - } - class ServiceExt extends ServiceExtension { - onConnect(want) { - console.log('onConnect , want:' + want.abilityName); - return new StubTest("test"); - } - } - ``` - - -## ServiceExtensionAbility.onDisconnect - -onDisconnect(want: Want): void; - -Called when the ability is disconnected. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| - -**Example** - - ```js - class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index ce5ab6b95a4e75fc5a5aa65ae37f75cdd0e0587c..0c6b7c6749e3a7bab2d40fc730742dd3daef9f05 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -1,7 +1,7 @@ # ServiceExtensionContext > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index b5e188671584289f3a36396e98b0a0f99ed790c2..b3908e1f7a4032c0988885c819a15cf123c05b8f 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -350,7 +350,7 @@ Obtains the status of the SIM card in the specified slot. This API uses an async | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID. The options are as follows:
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[SimState](#simState)\> | Yes | Callback used to return the result. For details, see [SimState](#simState). | +| callback | AsyncCallback\<[SimState](#simstate)\> | Yes | Callback used to return the result. For details, see [SimState](#simState). | **Example** @@ -379,7 +379,7 @@ Obtains the status of the SIM card in the specified slot. This API uses a promis | Type | Description | | -------------------------------- | ------------------------------------------ | -| Promise\<[SimState](#simState)\> | Promise used to return the result.| +| Promise\<[SimState](#simstate)\> | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 2cec7c7cc3489abc2cd0316c837e1a3403844d83..3a8edec81681964ebd5cf171c1d837b2b335e792 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -145,6 +145,7 @@ let result = stack.locate(2); ``` ### forEach + forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void @@ -179,6 +180,7 @@ stack.forEach((value, index) => { ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entries). diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md index 66b51201e3e42e7c852b7f372c4d392ed543ea29..7c2fcf494419486bb033969fa21ccfe0248d6ea7 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -3,7 +3,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. -> - This is a system API and cannot be called by third-party applications. +> - The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -125,4 +125,3 @@ Asynchronously obtains the available space of the specified volume. This method console.info("getFreeSizeOfVolume successfully:"+ number); }); ``` - diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md new file mode 100644 index 0000000000000000000000000000000000000000..db1fc9a0e06586e8361820be632c234ebc9b4fec --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -0,0 +1,214 @@ +# Application Context + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import app from '@system.app'; +``` + + +## app.getInfo + +getInfo(): AppResponse + +Obtains the declared information in the **config.json** file of an application. + +> **Note: ** [`@ohos.bundle`](js-apis-Bundle.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Return value** + +| Type| Description| +| -------- | -------- | +| [AppResponse](#appresponse) | Application response information.| + +**Example** + + ``` + export default { + getInfo(){ + var info = app.getInfo(); + console.log(JSON.stringify(info)); + } + } + ``` + +## app.terminate + +terminate(): void + +Terminates the current ability. + +> **Note: ** [`@ohos.ability.featureAbility`](js-apis-featureAbility.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Example** + + ``` + export default { + terminate(){ + app.terminate(); + }} + ``` +## app.requestFullWindow + +requestFullWindow(options?: RequestFullWindowOptions): void + +Requests the application to run in full window. You can call this API when the FA runs in a non-full window, for example, semi-modal FA. This API is invalid for an application already in full-window mode. + +This is a system API and cannot be called by third-party applications. + +> **Note: ** [`@ohos.window`](js-apis-window.md) is recommended from API version 7. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [RequestFullWindowOptions](#requestfullwindowoptions) | No| Duration for transition from the non-full window to the full window, in milliseconds. By default, the value is in direct proportion to the distance between the non-full window and the full window.| + +**Example** + + ``` + export default { + requestFullWindow(){ + app.requestFullWindow({ + duration: 200}); + } + } + ``` + +## app.setImageCacheCount7+ + +setImageCacheCount(value: number): void + +Sets the maximum number of decoded images that can be cached in the memory to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The built-in Least Recently Used (LRU) policy is used for caching. If the maximum number is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the number of images is too large, the memory usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Number of decoded images that are cached in the memory.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## app.setImageRawDataCacheSize7+ + +setImageRawDataCacheSize(value: number): void + +Sets the maximum size (in bytes) of the image data cached in the memory before decoding to speed up the loading of images from the same sources. If the input parameter is not set, the default value **0** is used, indicating that images are not cached. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the memory usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Size of the image data cached before decoding, in bytes.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageRawDataCacheSize(104,857,600) // Set the upper limit of the memory for caching image data before decoding to 100 MB. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## app.setImageFileCacheSize7+ + +setImageFileCacheSize(value: number): void + +Sets the maximum size of the image file cache (in bytes) to speed up the loading of images from the same sources, especially online image sources and thumbnails. If the input parameter is not set, the default value 100 MB is used. The LRU policy is used for caching. If the maximum size is exceeded, the images that have not been updated for the longest time will be removed. You are advised to set the parameter based on the application memory requirements. If the image cache is too large, the disk usage may be too high. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | No| Size of the image file cache, in bytes.| + +**Example** + + ``` + // app.ets + import app from '@system.app'; + + export default { + onCreate() { + app.setImageFileCacheSize(209,715,200) // Set the upper limit of the image file cache to 200 MB. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, + } + ``` + +## AppResponse + +Defines the application response information. + +**System capability**: The items in the table below require different system capabilities. For details, see the table. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- |-------- | +| appID6+ | string | Yes| Bundle name of an application. It uniquely identifies the application.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| appName | string | Yes| Application name.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| versionName | string | Yes| Application version name.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| versionCode | number | Yes| Application version number.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| + +## ScreenOnVisibleOptions + +Defines the options of the visible interface on the screen. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| visible | boolean | No| Whether to keep the application visible. The default value is **false**.| +| success | () => void | No| Callback upon success.| +| fail | (data: string, code: number) => void | No| Callback upon failure.| +| complete | () => void | No| Called when the API call is complete.| + +## RequestFullWindowOptions + +Defines the options of the **RequestFullWindow** API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| duration | number | Yes| Number of animation options.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md new file mode 100644 index 0000000000000000000000000000000000000000..c65bc13c40412db14b9e0f624db9e37a18f1098e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -0,0 +1,55 @@ +# Battery Level + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import battery from '@system.battery'; +``` + + +## battery.getStatus + +getStatus(Object): void + +Obtains the current charging state and battery level. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +**Parameter** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the check result is obtained | +| fail | Function | No | Called when the check result fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the check result is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged | +| level | number | Current battery level, which ranges from 0.00 to 1.00. | + +**Example** + +``` +export default { + getStatus() { + battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.log('fail to get battery level code:' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md new file mode 100644 index 0000000000000000000000000000000000000000..ce21ce2e7c13ac2b22e5ae026259d685b401c5e9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -0,0 +1,202 @@ +# Screen Brightness + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import brightness from '@system.brightness'; +``` + + +## brightness.getValue + +getValue(Object): void + +Obtains the current screen brightness. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Name | Type | Description | +| -------- | -------- | -------- | +| value | number | Screen brightness, which ranges from 1 to 255. | + +**Example** + +``` +export default { + getValue() { + brightness.getValue({ + success: function(data){ + console.log('success get brightness value:' + data.value); + }, + fail: function(data, code) { + console.log('get brightness fail, code: ' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setValue + +setValue(Object): void + +Sets the screen brightness. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| value | number | Yes | Screen brightness. The value is an integer ranging from 1 to 255.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used. | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setValue() { + brightness.setValue({ + value: 100, + success: function(){ + console.log('handling set brightness success.'); + }, + fail: function(data, code){ + console.log('handling set brightness value fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.getMode + +getMode(Object): void + +Obtains the screen brightness adjustment mode. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Name | Type | Description | +| -------- | -------- | -------- | +| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | + +**Example** + +``` +export default { + getMode() { + brightness.getMode({ + success: function(data){ + console.log('success get mode:' + data.mode); + }, + fail: function(data, code){ + console.log('handling get mode fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setMode + +setMode(Object): void + +Sets the screen brightness adjustment mode. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| mode | number | Yes | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setMode() { + brightness.setMode({ + mode: 1, + success: function(){ + console.log('handling set mode success.'); + }, + fail: function(data, code){ + console.log('handling set mode fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` + + +## brightness.setKeepScreenOn + +setKeepScreenOn(Object): void + +Sets whether to always keep the screen on. Call this API in **onShow()**. + +**System capability**: SystemCapability.PowerManager.DisplayPowerManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| keepScreenOn | boolean | Yes | Whether to always keep the screen on | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + setKeepScreenOn() { + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.') + }, + fail: function (data, code) { + console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md new file mode 100644 index 0000000000000000000000000000000000000000..b0dc3c5b117f5256020aa0cc5073e662c62cb6c9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -0,0 +1,165 @@ +# Encryption Algorithm + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR. + + +## Modules to Import + + +``` +import cipher from '@system.cipher' +``` + + +## cipher.rsa + +rsa(Object): void + +Encrypts or decrypts data using RSA. + +**System capability**: SystemCapability.Security.Cipher + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | +| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | +| key | string | Yes | Keys encrypted using RSA. During encryption, this parameter is a public key. During decryption, it is a private key. | +| transformation | string | No | RSA algorithm padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**. | +| success | Function | No | Called when data is encrypted or decrypted successfully. | +| fail | Function | No | Called when data fails to be encrypted or decrypted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + rsa() { + cipher.rsa({ + // Encrypt data. + action: 'encrypt', + // Text content to be encrypted + text: 'hello', + // Base64-encoded public key used for encryption + key: + 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n' + + 'eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n' + + 'h7SoaYEeluhqFimL2AEjfSwINHCLqObJkcjCfoZpE1JCehPiDOJsyT50Auc08h/4\n' + + 'jHQfanyC1nc62LqUCQIDAQAB', + success: function(data) { + console.log('handling success: ${data.text}'); + }, + fail: function(data, code) { + console.log(`### cipher.rsa encrypt fail ### ${code}: ${data}`); + } + }); + cipher.rsa({ + // Decrypt data. + action: 'decrypt', + // The text to be decrypted is a Base64-encoded binary value, and the decrypted text is "hello". + text: + 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + + 'S/ZWNI4Q8Q0suNjNkGU=', + // Base64-encoded public key used for encryption + key: + 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n' + + '7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n' + + 'aXHFEK1xQ3+HtKhpgR6W6GoWKYvYASN9LAg0cIuo5smRyMJ+hmkTUkJ6E+IM4mzJ\n' + + 'PnQC5zTyH/iMdB9qfILWdzrYupQJAgMBAAECgYEAkibhH0DWR13U0gvYJeD08Lfd\n' + + 'Sw1PMHyquEqIcho9Yv7bF3LOXjOg2EEGPx09mvuwXFgP1Kp1e67XPytr6pQQPzK7\n' + + 'XAPcLPx80R/ZjZs8vNFndDOd1HgD3vSVmYQarNzmKi72tOUWMPevsaFXPHo6Xx3X\n' + + '8x0wYb7XuBsQguRctTECQQD7GWX3JUiyo562iVrpTDPOXsrUxmzCrgz2OZildxMd\n' + + 'Pp/PkyDrx7mEXTpk4K/XnQJ3GpJNi2iDSxDuPSAeJ/aPAkEA4Tw4+1Z43S/xH3C3\n' + + 'nfulYBNyB4si6KEUuC0krcC1pDJ21Gd12efKo5VF8SaJI1ZUQOzguV+dqNsB/JUY\n' + + 'OFfX5wJAB1dKv9r7MR3Peg6x9bggm5vx2h6i914XSuuMJupASM6X5X2rrLj+F3yS\n' + + 'RHi9K1SPyeOg+1tkBtKfABgRZFBOyQJAbuTivUSe73AqTKuHjB4ZF0ubqgEkJ9sf\n' + + 'Q2rekzm9dOFvxjZGPQo1qALX09qATMi1ZN376ukby8ZAnSafLSZ64wJBAM2V37go\n' + + 'Sj44HF76ksRow8gecuQm48NCTGAGTicXg8riKog2GC9y8pMNHAezoR9wXJF7kk+k\n' + + 'lz5cHyoMZ9mcd30=', + success: function(data) { + console.log('handling success: ${data.text}'); + }, + fail: function(data, code) { + console.log(`### cipher.rsa decrypt fail ### ${code}: ${data}`); + }, + }); + } +} +``` + + +## cipher.aes + +aes(Object): void + +Encrypts or decrypts data using AES. + +**System capability**: SystemCapability.Security.Cipher + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| action | string | Yes | Action type. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data. | +| text | string | Yes | Text content to be encrypted or decrypted. The text to be encrypted must be a common text. The text content to be decrypted must be a binary value encoded using Base64. The default format is used for Base64 encoding. | +| key | string | Yes | Key used for encryption or decryption, which is a character string encrypted using Base64. | +| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | +| iv | string | No | Initial vector for AES-based encryption and decryption. The value is a character string encoded using Base64. The default value is the key value. | +| ivOffset | string | No | Offset of the initial vector for AES-based encryption and decryption. The default value is **0**. | +| ivLen | string | No | Length of the initial vector for AES-based encryption and decryption. The default value is **16**. | +| success | Function | No | Called when data is encrypted or decrypted successfully. | +| fail | Function | No | Called when data fails to be encrypted or decrypted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + aes() { + cipher.aes({ + // Encrypt data. + action: 'encrypt', + // Text content to be encrypted + text: 'hello', + // Base64-encoded key used for encryption + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: 0, + ivLen: 16, + success: (data) => { + console.log('handling success: ${data.text}'); + }, + fail: (data, code) => { + console.log(`### cipher.aes encrypt fail ### ${code}: ${data}`); + } + }); + cipher.aes({ + // Decrypt data. + action: 'decrypt', + // Text to be decrypted, which is a Base64-encoded binary value + text: 'CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n' + + 'gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n' + + 'S/ZWNI4Q8Q0suNjNkGU=', + // Base64-encoded key used for decryption + key: 'NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=', + transformation: 'AES/CBC/PKCS5Padding', + ivOffset: 0, + ivLen: 16, + success: (data) => { + this.dealTxt = data.text; + }, + fail: (data, code) => { + prompt.showToast({ + message: (`### cipher.aes decrypt fail ### code = ${code}: ${data}`) + }) + }, + }); + } +} + +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-configuration.md b/en/application-dev/reference/apis/js-apis-system-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..310abffe5779e336ca676161d09172eb39af5bac --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-configuration.md @@ -0,0 +1,45 @@ +# Application Configuration + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.i18n`](js-apis-i18n.md) and [`@ohos.intl`](js-apis-intl.md) instead. +> +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import configuration from '@system.configuration'; +``` + + +## configuration.getLocale + +getLocale(): <LocaleResponse> + +Obtains the current locale of the application, which is the same as the system locale. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Return values** +**Table 1** LocaleResponse + +| Name | Type | Description | +| -------- | -------- | -------- | +| language | string | Current language of the application, for example, **zh**. | +| countryOrRegion | string | Country or region, for example, **CN**. | +| dir | string | Text layout direction. Available values are as follows:
- **ltr**: The text direction is from left to right.
- **rtl**: The text direction is from right to left. | +| unicodeSetting5+ | string | Unicode key set determined by the locale.
For example, **{"nu":"arab"}** indicates that the current locale uses Arabic numerals.
If the current locale does not have a specific key set, an empty set is returned. | + +**Example** + +``` +export default { + getLocale() { + const localeInfo = configuration.getLocale(); + console.info(localeInfo.language); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md new file mode 100644 index 0000000000000000000000000000000000000000..c5b92831958ea79cb7b868fbf549974cdf39a669 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -0,0 +1,75 @@ +# Device Information + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.deviceInfo`](js-apis-device-info.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import device from '@system.device'; +``` + + +## device.getInfo + +getInfo(Object): void + +Obtains the device information. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> Do not call **device.getInfo** before the **onShow** event of the home page. + +**System capability**: SystemCapability.Startup.SysInfo + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the device information is obtained | +| fail | Function | No | Called when the device information fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the device information is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| brand | string | Brand | +| manufacturer | string | Manufacturer | +| model | string | Model | +| product | string | Product number | +| language4+ | string | System language | +| region4+ | string | System region | +| windowWidth | number | Window width | +| windowHeight | number | Window height | +| screenDensity4+ | number | Screen density | +| screenShape4+ | string | Screen shape. The options are as follows:
- rect: rectangle screen
- circle: circle screen | +| apiVersion4+ | number | API version | +| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions. | +| deviceType4+ | string | Device type | + +The following error code will be returned if the device information fails to be obtained. + +| Error Code | Description | +| -------- | -------- | +| 200 | The returned result contains information that cannot be obtained. | + +**Example** + +``` +export default { + getInfo() { + device.getInfo({ + success: function(data) { + console.log('Device information obtained successfully. Device brand:' + data.brand); + }, + fail: function(data, code) { + console.log('Failed to obtain device information. Error code:'+ code + '; Error information: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-fetch.md b/en/application-dev/reference/apis/js-apis-system-fetch.md new file mode 100644 index 0000000000000000000000000000000000000000..e198f5562db784b6ffe70d0bf359529abce6f2d7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-fetch.md @@ -0,0 +1,105 @@ +# Data Request + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.net.http`](js-apis-http.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import fetch from '@system.fetch'; +``` + + +## fetch.fetch + +fetch(Object): void + +Obtains data through a network. + +**Required permissions:** ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | Resource URL. | +| data | string \| Object | No | Request parameter, which can be a string or a JSON object. For details, see Relationship between data and Content-Type. | +| header | Object | No | Request header. | +| method | string | No | Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**. | +| responseType | string | No | Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values of the success callback. | +| success | Function | No | Called when the network data is obtained successfully. | +| fail | Function | No | Called when the network data fails to be obtained. | +| complete | Function | No | Called when the execution is complete. | + + **Table1** Relationship between data and Content-Type + +| data | Content-Type | Description | +| -------- | -------- | -------- | +| string | Not set | The default value of Content-Type is text/plain, and the value of data is used as the request body. | +| string | Any type | The value of data is used as the request body. | +| Object | Not set | The default value of **Content-Type** is **application/x-www-form-urlencoded**. The **data** value is encoded based on the URL rule and appended in the request body. | +| Object | application/x-www-form-urlencoded | The value of data is encoded based on the URL rule and is used as the request body. | + +The following values will be returned when data is successfully obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| code | number | Server status code. | +| data | string \| Object | The type of the returned data is determined by **responseType**. For details, see Relationship between responseType and data returned by the success function. | +| headers | Object | All headers in the response from the server. | + + **Table2** Relationship between responseType and data returned by the success function + +| responseType | data | Description | +| -------- | -------- | -------- | +| N/A | string | When the type in the header returned by the server is **text/\***, **application/json**, **application/javascript**, or **application/xml**, the value is the text content. | +| text | string | Text content. | +| json | Object | A JSON object. | + +**Example** + +``` +export default { + data: { + responseData: 'NA', + url: "test_url", + }, + fetch: function () { + var that = this; + fetch.fetch({ + url: that.url, + success: function(response) { + console.info("fetch success"); + that.responseData = JSON.stringify(response); + }, + fail: function() { + console.info("fetch fail"); + } + }); + } +} +``` + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> HTTPS is supported by default. To support HTTP, you need to add **"network"** to the **config.json** file, and set the attribute **"cleartextTraffic"** to **true**. +> +> ``` +> { +> "deviceConfig": { +> "default": { +> "network": { +> "cleartextTraffic": true +> } +> ... +> } +> } +> ... +> } +> ``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-file.md b/en/application-dev/reference/apis/js-apis-system-file.md new file mode 100644 index 0000000000000000000000000000000000000000..f05357dbe766366e8653c51b85544d12317385ce --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-file.md @@ -0,0 +1,601 @@ +# File Storage + + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.fileio`](js-apis-fileio.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import file from '@system.file'; +``` + + +## file.move + +move(Object): void + +Moves a specified file to a given location. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| srcUri | string | Yes | URI of the file to move. | +| dstUri | string | Yes | URI of the location to which the file is to move. | +| success | Function | No | Called when the source file is moved to the specified location successfully. This function returns the URI of the destination location. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + move() { + file.move({ + srcUri: 'internal://app/myfiles1', + dstUri: 'internal://app/myfiles2', + success: function(uri) { + console.log('call success callback success'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.copy + +copy(Object): void + +Copies a file and saves the copy to a specified location. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| srcUri | string | Yes | URI of the file to copy. | +| dstUri | string | Yes | URI of the location to which the copy is to save.
The directory of application resources and URI of the **tmp** type are not supported. | +| success | Function | No | Called when the source file is copied and saved to the specified location successfully. This function returns the URI of the destination location. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + copy() { + file.copy({ + srcUri: 'internal://app/file.txt', + dstUri: 'internal://app/file_copy.txt', + success: function(uri) { + console.log('call success callback success'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.list + +list(Object): void + +Obtains the list of all files in a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| fileList | Array<FileInfo> | File list. The format of each file is as follows:
{
uri:'file1',
lastModifiedTime:1589965924479,
length:10240,
type: 'file'
} | + +**Table1** FileInfo + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | File URI. | +| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | +| length | number | File size, in bytes. | +| type | string | File type. Available values are as follows:
- **dir**: directory
- **file**: file | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + list() { + file.list({ + uri: 'internal://app/pic', + success: function(data) { + console.log(data.fileList); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.get + +get(Object): void + +Obtains information about a specified local file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | File URI. | +| recursive | boolean | No | Whether to recursively obtain the file list under a subdirectory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | File URI. | +| length | number | File size, in bytes. | +| lastModifiedTime | number | Timestamp when the file is stored the last time, which is the number of milliseconds elapsed since 1970/01/01 00:00:00 GMT. | +| type | string | File type. The values are as follows:
- **dir**: directory
- **file**: file | +| subFiles | Array | File list. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + get() { + file.get({ + uri: 'internal://app/file', + success: function(data) { + console.log(data.uri); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.delete + +delete(Object): void + +Deletes local files. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the file to delete, which cannot be an application resource path. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Incorrect parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + delete() { + file.delete({ + uri: 'internal://app/my_file', + success: function() { + console.log('call delete success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.writeText + +writeText(Object): void + +Writes text into a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | +| text | string | Yes | Character string to write into the local file. | +| encoding | string | No | Encoding format. The default format is UTF-8. | +| append | boolean | No | Whether to enable the append mode. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Incorrect parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + writeText() { + file.writeText({ + uri: 'internal://app/test.txt', + text: 'Text that just for test.', + success: function() { + console.log('call writeText success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.writeArrayBuffer + +writeArrayBuffer(Object): void + +Writes buffer data into a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. If it does not exist, a file will be created. | +| buffer | Uint8Array | Yes | Buffer from which the data is derived. | +| position | number | No | Offset to the position where the writing starts. The default value is **0**. | +| append | boolean | No | Whether to enable the append mode. The default value is **false**. If the value is **true**, the **position** parameter will become invalid. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + writeArrayBuffer() { + file.writeArrayBuffer({ + uri: 'internal://app/test', + buffer: new Uint8Array(8), // The buffer is of the Uint8Array type. + success: function() { + console.log('call writeArrayBuffer success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.readText + +readText(Object): void + +Reads text from a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. | +| encoding | string | No | Encoding format. The default format is UTF-8. | +| position | number | No | Position where the reading starts. The default value is the start position of the file. | +| length | number | No | Length of the text to be read (in bytes). The default value is **4096**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| text | string | Text read from the specified file. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | The file or directory does not exist. | +| 302 | The size of text to read exceeds 4096 bytes. | + +**Example** + +``` +export default { + readText() { + file.readText({ + uri: 'internal://app/text.txt', + success: function(data) { + console.log('call readText success: ' + data.text); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.readArrayBuffer + +readArrayBuffer(Object): void + +Reads buffer data from a specified file. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of a local file. | +| position | number | No | Position where the reading starts. The default value is the start position of the file. | +| length | number | No | Length of data to read. If this parameter is not set, the reading proceeds until the end of the file. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| buffer | Uint8Array | File content that is read | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + readArrayBuffer() { + file.readArrayBuffer({ + uri: 'internal://app/test', + position: 10, + length: 200, + success: function(data) { + console.log('call readArrayBuffer success: ' + data.buffer); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.access + +access(Object): void + +Checks whether a specified file or directory exists. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory or file. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + access() { + file.access({ + uri: 'internal://app/test', + success: function() { + console.log('call access success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.mkdir + +mkdir(Object): void + +Creates a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| recursive | boolean | No | Whether to recursively create upper-level directories of the specified directory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | + +**Example** + +``` +export default { + mkdir() { + file.mkdir({ + uri: 'internal://app/test_directory', + success: function() { + console.log('call mkdir success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## file.rmdir + +rmdir(Object): void + +Deletes a specified directory. + +**System capability**: SystemCapability.FileManagement.File.FileIO + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri | string | Yes | URI of the directory. | +| recursive | boolean | No | Whether to recursively delete subfiles and subdirectories of the specified directory. The default value is **false**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 202 | Invalid parameter. | +| 300 | I/O error. | +| 301 | File or directory not exist. | + +**Example** + +``` +export default { + rmdir() { + file.rmdir({ + uri: 'internal://app/test_directory', + success: function() { + console.log('call rmdir success.'); + }, + fail: function(data, code) { + console.error('call fail callback fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md new file mode 100644 index 0000000000000000000000000000000000000000..ab53fb2d188b7b929c591a67c33cec12984e063c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -0,0 +1,211 @@ +# Geographic Location + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.geolocation`](js-apis-geolocation.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import geolocation from '@system.geolocation'; +``` + + +## Required Permissions + +ohos.permission.LOCATION + + +## geolocation.getLocation + +getLocation(Object): void + +Obtains the geographic location. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| timeout | number | No | Timeout duration, in milliseconds. The default value is **30000**.
The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.
The value is a 32-digit positive integer. If the value set is less than or equal to **0**, the default value will be used. | +| coordType | string | No | Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**. | +| success | Function | No | Called when the operation is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| longitude | number | Longitude | +| latitude | number | Latitude | +| altitude | number | Altitude | +| accuracy | number | Location accuracy | +| time | number | Time when the location is obtained | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 601 | Failed to obtain the required permission because the user rejected the request. | +| 602 | Permission not declared. | +| 800 | Operation times out due to a poor network condition or unavailable GPS. | +| 801 | System location disabled. | +| 802 | The method is called again while the previous execution result is not returned yet. | + +**Example** + +``` +export default { + getLocation() { + geolocation.getLocation({ + success: function(data) { + console.log('success get location data. latitude:' + data.latitude); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.getLocationType + +getLocationType(Object): void + +Obtains the supported location types. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following values will be returned when the operation is successful. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| types | Array<string> | Available location types, ['gps', 'network'] | + +**Example** + +``` +export default { + getLocationType() { + geolocation.getLocationType({ + success: function(data) { + console.log('success get location type:' + data.types[0]); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.subscribe + +subscribe(Object): void + +Listens to the geographical location. If this method is called multiple times, the last call takes effect. + +**System capability**: SystemCapability.Location.Location.Lite + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| coordType | string | No | Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**. | +| success | Function | Yes | Called when the geographical location changes | +| fail | Function | No | Called when the listening fails | + +The following values will be returned when the network type is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| longitude | number | Longitude | +| latitude | number | Latitude | +| altitude | number | Altitude | +| accuracy | number | Location accuracy | +| time | number | Time when the location is obtained | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 601 | Failed to obtain the required permission because the user rejected the request. | +| 602 | Permission not declared. | +| 801 | System location disabled. | + +**Example** + +``` +export default { + subscribe() { + geolocation.subscribe({ + success: function(data) { + console.log('get location. latitude:' + data.latitude); + }, + fail: function(data, code) { + console.log('fail to get location. code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## geolocation.unsubscribe + +unsubscribe(): void + +Cancels listening to the geographical location. + +**System capability**: SystemCapability.Location.Location.Lite + +**Example** + +``` +export default { + unsubscribe() { + geolocation.unsubscribe(); + }, +} +``` + + +## geolocation.getSupportedCoordTypes + +getSupportedCoordTypes(): Array<string> + +Obtains coordinate system types supported by the device. + +**System capability**: SystemCapability.Location.Location.Lite + +**Return Value** + +| Type | Non-Null | Description | +| -------- | -------- | -------- | +| Array<string> | Yes | Coordinate system types, for example, **[wgs84, gcj02]**. | + +**Example** + +``` +export default { + getSupportedCoordTypes() { + var types = geolocation.getSupportedCoordTypes(); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md new file mode 100644 index 0000000000000000000000000000000000000000..f2057a86685a5d212e84caf27e69468b8169c267 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -0,0 +1,125 @@ +# Media Query + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.mediaquery`](js-apis-mediaquery.md) instead. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import mediaquery from '@system.mediaquery'; +``` + + +## mediaquery.matchMedia + +matchMedia(condition: string): MediaQueryList + +Creates a **MediaQueryList** object based on the query condition. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| condition | string | Yes | Query condition.| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------------- | +| MediaQueryList | Attributes of the **MediaQueryList** object created. For details, see **MediaQueryList** attributes.| + +**Example** + +``` +export default { + matchMedia() { + var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); + }, +} +``` + +## MediaQueryEvent + +Defines a media query event. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ----- | +| matches | boolean | Yes | Matching result.| + +## MediaQueryList + +Defines a media query list. + +### Attributes + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | ----------------- | +| media | string | No | Serialized media query condition. This parameter is read-only.| +| matches | boolean | Yes | Matching result. | + +### onchange + +onchange?: (matches: boolean) => void + +Called when the **matches** value changes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | -------------- | +| matches | boolean | Yes | New **matches** value.| + + +### MediaQueryList.addListener + +addListener(callback: (event: MediaQueryEvent) => void): void + +Adds a listener for this **MediaQueryList** object. The listener must be added before **onShow** is called, that is, it must be added in the **onInit** or **onReady** API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | -------------- | +| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the matching condition changes.| + +**Example** + +``` +mMediaQueryList.addListener(maxWidthMatch); +``` + + +### MediaQueryList.removeListener + +removeListener(callback: (event: MediaQueryEvent) => void): void + +Removes the listener for this **MediaQueryList** object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------- | ---- | -------------- | +| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the matching condition changes.| + +**Example** + +``` +mMediaQueryList.removeListener(maxWidthMatch); +``` diff --git a/en/application-dev/reference/apis/js-apis-system-network.md b/en/application-dev/reference/apis/js-apis-system-network.md new file mode 100644 index 0000000000000000000000000000000000000000..1bf121889896276a676f177300f341da5fb327fe --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-network.md @@ -0,0 +1,134 @@ +# Network State + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.telephony.observer`](js-apis-observer.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import network from '@system.network'; +``` + + +## Required Permissions + +ohos.permission.GET_WIFI_INFO + +ohos.permission.GET_NETWORK_INFO + + +## network.getType + +getType(Object): void + +Obtains the network type. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the execution is successful. | +| fail | Function | No | Called when the operation fails. | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the multimedia volume is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| metered | boolean | Whether the billing is based on the data volume. | +| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 602 | The current permission is not declared. | + +**Example** + +``` +export default { + getType() { + network.getType({ + success: function(data) { + console.log('success get network type:' + data.type); + }, + fail: function(data, code) { + console.log('fail to get network type code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## network.subscribe + +subscribe(Object): void + +Listens to the network connection state. If this method is called multiple times, the last call takes effect. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the network connection state changes | +| fail | Function | No | Called when the multimedia volume fails to be obtained. | + +The following value will be returned when the multimedia volume is obtained. + +| Parameter | Type | Description | +| -------- | -------- | -------- | +| metered | boolean | Whether the billing is based on the data volume. | +| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. | + +One of the following error codes will be returned if the listening fails. + +| Error Code | Description | +| -------- | -------- | +| 602 | The current permission is not declared. | +| 200 | The subscription fails. | + +**Example** + +``` +export default { + subscribe() { + network.subscribe({ + success: function(data) { + console.log('network type change type:' + data.type); + }, + fail: function(data, code) { + console.log('fail to subscribe network, code:' + code + ', data:' + data); + }, + }); + }, +} +``` + + +## network.unsubscribe + +unsubscribe(): void + +Cancels listening to the network connection state. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Example** + +``` +export default { + unsubscribe() { + network.unsubscribe(); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md new file mode 100644 index 0000000000000000000000000000000000000000..c6453ec28f1dca4749d8f8c91414a609af161466 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -0,0 +1,60 @@ +# Application Management + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> +> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.bundle`](js-apis-Bundle.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import pkg from '@system.package'; +``` + + +## package.hasInstalled + +hasInstalled(Object): void + +Checks whether an application exists, or whether a native application has been installed. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO + +**System capability**: SystemCapability.BundleManager.BundleFramework + +**Parameter** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes | Application bundle name | +| success | Function | No | Called when the check result is obtained | +| fail | Function | No | Called when the check result fails to be obtained | +| complete | Function | No | Called when the execution is complete | + +The following value will be returned when the check result is obtained. + +| Name | Type | Description | +| -------- | -------- | -------- | +| result | boolean | Whether the application exists, or whether the native application has been installed | + +**Example** + +``` +export default { + hasInstalled() { + pkg.hasInstalled({ + bundleName: 'com.example.bundlename', + success: function(data) { + console.log('package has installed: ' + data); + }, + fail: function(data, code) { + console.log('query package fail, code: ' + code + ', data: ' + data); + }, + }); + }, +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-prompt.md b/en/application-dev/reference/apis/js-apis-system-prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f894715391f015cbd67ecf913a7923c00d4e78e1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-prompt.md @@ -0,0 +1,188 @@ +# Prompt + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 8. You are advised to use ['@ohos.prompt](js-apis-prompt.md)' instead. +> +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import prompt from '@system.prompt'; +``` + +## prompt.showToast + +showToast(options: ShowToastOptions): void + +Shows the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | --------------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Options for showing the toast.| + +**Example** + +``` +export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } +} +``` + + +## prompt.showDialog + +showDialog(options: ShowDialogOptions): void + +Shows the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ----------- | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Options for showing the dialog box.| + + +**Example** + +``` +export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button', + color: '#666666', + }, + ], + success: function(data) { + console.log('dialog success callback, click button : ' + data.index); + }, + cancel: function() { + console.log('dialog cancel callback'); + }, + }); + } +} +``` + +## prompt.showActionMenu6+ + +showActionMenu(options: ShowActionMenuOptions): void + +Shows the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| options | [ShowActionMenuOptions](#showactionmenuoptions) | Yes | Options for showing the action menu.| + + +**Example** + +``` +export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ], + success: function(data) { + console.log('dialog success callback, click button : ' + data.tapIndex); + }, + fail: function(data) { + console.log('dialog fail callback' + data.errMsg); + }, + }); + } +} +``` +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------------------- | -------------- | ---- | ---------------------------------------- | +| message | string | Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom5+ | string\|number | No | Distance between the toast frame and the bottom of the screen. This parameter is available only on phones and tablets. | + +## Button + +Defines the prompt information of a button. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------- | +| text | string | Yes | Text displayed on the button.| +| color | string | Yes | Color of the button.| + +## ShowDialogSuccessResponse + +Defines the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------- | +| index | number | Yes | Data index.| + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| message | string | No | Text body. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| +| success | (data: [ShowDialogSuccessResponse](#showdialogsuccessresponse)) => void | No | Callback upon success. | +| cancel | (data: string, code: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Called when the API call is complete. | + +## ShowActionMenuOptions6+ + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string | No | Title of the text to display. | +| buttons | [[Button](#button), [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?, [Button](#button)?] | Yes | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to six buttons are supported.| +| success | (tapIndex: number, errMsg: string) => void | No | Invoked when a dialog box is displayed. | +| fail | (errMsg: string) => void | No | Callback upon failure. | +| complete | (data: string) => void | No | Invoked when a dialog box is closed. | diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md new file mode 100644 index 0000000000000000000000000000000000000000..53fa3bf82253930056ccd2caa524f24d85598046 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -0,0 +1,189 @@ +# Uploading and Downloading + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.request`](js-apis-request.md) instead. +> +> - The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import request from '@system.request'; +``` + +## Required Permissions + +ohos.permission.INTERNET. + + +## request.upload + +upload(Object): void + +Uploads files. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | URL of the upload server. | +| header | Object | No | Request header. | +| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | +| files | Array<File> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | +| data | Array<RequestData> | No | Form data in the request body. | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +**Table 1** File + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| filename | string | No | File name in the header when **multipart** is used. | +| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | +| uri | string | Yes | Local storage path of a file. | +| type | string | No | Type of the file content. By default, the type is obtained based on the suffix of the file name or URI. | + +**Table 2** RequestData + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| name | string | Yes | Name of the form element | +| value | string | Yes | Value of the form element | + +The following values will be returned when the files are successfully uploaded. + +| Name | Type | Description | +| -------- | -------- | -------- | +| code | number | HTTP status code returned by the server. | +| data | string | Content returned by the server. The value type is determined by the type in the returned headers. | +| headers | Object | Headers returned by the server. | + +**Example** + +``` +export default { + upLoad() { + request.upload({ + url: 'http://www.path.com', + files: [ + { + uri: 'internal://cache/path/to/file.txt', + name: 'file', + filename: 'file.txt', + }, + ], + data:[ + { + name: 'name1', + value: 'value', + }, + ], + success: function(data) { + console.log('upload success, code:' + data.code); + }, + fail: function() { + console.log('upload fail'); + }, + }); + } +} +``` + + +## request.download + +download(Object): void + +Downloads files. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| url | string | Yes | Resource URL. | +| header | Object | No | Request header. | +| description | string | No | Download description. The default value is the file name. | +| filename | string | No | Name of the file to download. The value is obtained from the current request or resource URL by default. | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| token | string | Download token, which is used to obtain the download status. | + +One of the following error codes will be returned if the operation fails. + +| Error Code | Description | +| -------- | -------- | +| 400 | Download task failed | + +**Example** + +``` +export default { + downLoad() { + request.download({ + url: 'http://www.path.com', + success: function(data) { + console.log('call success callback success: ' + data.token); + }, + fail: function(data, code) { + console.log('handling fail'); + }, + }); + } +} +``` + + +## request.onDownloadComplete + +onDownloadComplete(Object): void + +Listens to download task status. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| token | string | Yes | Token of the result returned by the download method | +| success | Function | No | Called when the download task is complete. | +| fail | Function | No | Called when downloading fails or the task does not exist. | +| complete | Function | No | Called when the execution is complete. | + +Return values of the **success** callback + +| Name | Type | Description | +| -------- | -------- | -------- | +| uri | string | URI of the download file | + +One of the following error codes will be returned if the listening fails. + +| Error Code | Description | +| -------- | -------- | +| 400 | Download task failed | +| 401 | Download task not exist | + +**Example** + +``` +export default { + onDownloadComplete() { + request.onDownloadComplete({ + token: 'token-index', + success: function(data) { + console.log('download success, uri:' + data.uri); + }, + fail: function(data, code) { + console.log('download fail'); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md new file mode 100644 index 0000000000000000000000000000000000000000..c69a1599f615ae5fc0b4dfcfbf63d5b12033dd54 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -0,0 +1,398 @@ +# Page Routing + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> +> - The APIs of this module are no longer maintained since API version 8. You are advised to use [`@ohos.router`](js-apis-router.md) instead. +> +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import router from '@system.router'; +``` + +## router.push + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | -------------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. For details, see **RouterOptions**.| + +**Example** + +``` +// Current page +export default { + pushPage() { + router.push({ + uri: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } +} +``` + + +``` +// routerpage2 page +export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> The page routing stack supports a maximum of 32 pages. + + +## router.replace + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | -------------------------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. For details, see **RouterOptions**.| + +**Example** + +``` +// Current page +export default { + replacePage() { + router.replace({ + uri: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } +} +``` + + +``` +// detail page +export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } +} +``` + +## router.back + +back(options?: BackRouterOptions): void + +Returns to the previous page or a specified page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ----------------------- | +| options | [BackRouterOptions](#backrouteroptions) | Yes | For details, see **BackRouterOptions**.| + +**Example** + +``` +// index page +export default { + indexPushPage() { + router.push({ + uri: 'pages/detail/detail', + }); + } +} +``` + + +``` +// detail page +export default { + detailPushPage() { + router.push({ + uri: 'pages/mall/mall', + }); + } +} +``` + + +``` +// Navigate from the mall page to the detail page through router.back(). +export default { + mallBackPage() { + router.back(); + } +} +``` + + +``` +// Navigate from the detail page to the index page through router.back(). +export default { + defaultBack() { + router.back(); + } +} +``` + + +``` +// Return to the detail page through router.back(). +export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. + +## router.getParams + +getParams(): ParamsInterface + +Obtains parameter information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------- | +| [ParamsInterface](#paramsinterface) | For details, see **ParamsInterface**.| + +## router.clear + +clear(): void + +Clears all historical pages in the stack and retains only the current page at the top of the stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + +``` +export default { + clearPage() { + router.clear(); + } +} +``` + +## router.getLength + +getLength(): string + +Obtains the number of pages in the current stack. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Number of pages in the stack. The maximum value is **32**.| + +**Example** + +``` +export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } +} +``` + +## router.getState + +getState(): RouterState + +Obtains state information about the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| --------------------------- | ----------------- | +| [RouterState](#routerstate) | For details, see **RouterState**.| + +**Example** + +``` +export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } +} +``` + +## router.enableAlertBeforeBackPage6+ + +enableAlertBeforeBackPage(options: EnableAlertBeforeBackPageOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | -------------------------------------- | +| options | [EnableAlertBeforeBackPageOptions](#enableAlertbeforebackpageoptions6) | Yes | For details, see **EnableAlertBeforeBackPageOptions**.| + +**Example** + +``` +export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } +} +``` + +## router.disableAlertBeforeBackPage6+ + +disableAlertBeforeBackPage(options?: DisableAlertBeforeBackPageOptions): void + +Disables the display of a confirm dialog box before returning to the previous page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------------------------------------- | +| options | [DisableAlertBeforeBackPageOptions](#disablealertbeforebackpageoptions6) | No | For details, see **DisableAlertBeforeBackPageOptions**.| + +**Example** + +``` +export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage({ + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } +} +``` + +## RouterOptions + +Defines the page routing parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| uri | string | Yes | URI of the destination page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
-pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| + + +## BackRouterOptions + +Defines the parameters for routing back. + +**System capability**: The items in the table below require different system capabilities. For details, see the table. + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ---------------------------------------- | +| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| params | Object | No | Data that needs to be passed to the destination page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| + +## RouterState + +Defines the page state. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------- | +| index | number | Yes | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.| +| name | string | Yes | Name of the current page, that is, the file name. | +| path | string | Yes | Path of the current page. | + +## EnableAlertBeforeBackPageOptions6+ + +Defines the **EnableAlertBeforeBackPage** parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ------------------------ | ---- | ------------------------- | +| message | string | Yes | Content displayed in the confirm dialog box. | +| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. | +| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.| +| complete | () => void | No | Called when the API call is complete. | + +## DisableAlertBeforeBackPageOptions6+ + +Define the **DisableAlertBeforeBackPage** parameters. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ------------------------ | ---- | ------------------------- | +| success | (errMsg: string) => void | No | Called when a dialog box is displayed. **errMsg** indicates the returned information. | +| fail | (errMsg: string) => void | No | Called when the API fails to be called. **errMsg** indicates the returned information.| +| complete | () => void | No | Called when the API call is complete. | + +## ParamsInterface + +| Name | Type | Description | +| ------------- | ------ | ------- | +| [key: string] | Object | List of routing parameters.| diff --git a/en/application-dev/reference/apis/js-apis-system-storage.md b/en/application-dev/reference/apis/js-apis-system-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..2440183d41464f6b88907b096cd0185707192bd5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-storage.md @@ -0,0 +1,162 @@ +# Data Storage + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.data.storage`](js-apis-data-storage.md) instead. +> +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +``` +import storage from '@system.storage'; +``` + + +## storage.get + +get(Object): void + +Reads the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Content index. | +| default | string | No | Default value returned when the **key** does not exist. | +| success | Function | No | Called when the stored content is successfully read. | +| fail | Function | No | Called when the stored content fails to be read. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageGet() { + storage.get({ + key: 'storage_key', + success: function(data) { + console.log('call storage.get success: ' + data); + }, + fail: function(data, code) { + console.log('call storage.get fail, code: ' + code + ', data: ' + data); + }, + complete: function() { + console.log('call complete'); + }, + }); + } +} +``` + + +## storage.set + +set(Object): void + +Modifies the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Index of the stored content to be modified. | +| value | string | No | Target storage content. The maximum number of characters allowed is 128. | +| success | Function | No | Called when the stored content is modified successfully. | +| fail | Function | No | Called when the stored content fails to be modified. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageSet() { + storage.set({ + key: 'storage_key', + value: 'storage value', + success: function() { + console.log('call storage.set success.'); + }, + fail: function(data, code) { + console.log('call storage.set fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## storage.clear + +clear(Object): void + +Clears the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| success | Function | No | Called when the stored content is cleared successfully | +| fail | Function | No | Called when the stored content fails to be cleared | +| complete | Function | No | Called when the execution is complete | + +**Example** + +``` +export default { + storageClear() { + storage.clear({ + success: function() { + console.log('call storage.clear success.'); + }, + fail: function(data, code) { + console.log('call storage.clear fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` + + +## storage.delete + +delete(Object): void + +Deletes the stored content. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| key | string | Yes | Content index. | +| success | Function | No | Called when the stored content is deleted successfully. | +| fail | Function | No | Called when the stored content fails to be deleted. | +| complete | Function | No | Called when the execution is complete. | + +**Example** + +``` +export default { + storageDelete() { + storage.delete({ + key: 'Storage1', + success: function() { + console.log('call storage.delete success.'); + }, + fail: function(data, code) { + console.log('call storage.delete fail, code: ' + code + ', data: ' + data); + }, + }); + } +} +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 31f3f1303601716d2f471a514487827b1b2dfae1..35096fe9a772de7ef95ea21d4e7660f850db366d 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -20,7 +20,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -51,7 +51,7 @@ Sets the system time. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -82,7 +82,7 @@ getCurrentTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -109,7 +109,7 @@ getCurrentTime(isNano?: boolean): Promise<number> Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -138,7 +138,7 @@ getRealActiveTime(isNano?: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, excluding the deep sleep time. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -165,7 +165,7 @@ getRealActiveTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, excluding the deep sleep time. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -194,7 +194,7 @@ getRealTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -221,7 +221,7 @@ getRealTime(): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -252,7 +252,7 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -282,7 +282,7 @@ Sets the system date. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -312,7 +312,7 @@ getDate(callback: AsyncCallback<Date>): void Obtains the current system date. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -338,7 +338,7 @@ getDate(): Promise<Date> Obtains the current system date. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - Return value | Type| Description| @@ -364,7 +364,7 @@ Sets the system time zone. This API uses an asynchronous callback to return the **Required permissions**: ohos.permission.SET_TIME_ZONE -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -393,7 +393,7 @@ Sets the system time zone. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_TIME_ZONE -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -422,7 +422,7 @@ getTimezone(callback: AsyncCallback<string>): void Obtains the system time zone. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - **Parameters** | Name| Type| Mandatory| Description| @@ -448,7 +448,7 @@ getTimezone(): Promise<string> Obtains the system time zone. This API uses a promise to return the result. -**System capability**: SystemCapability.Miscservices.Time +**System capability**: SystemCapability.MiscServices.Time - Return value | Type| Description| diff --git a/en/application-dev/reference/apis/js-apis-testRunner.md b/en/application-dev/reference/apis/js-apis-testRunner.md new file mode 100644 index 0000000000000000000000000000000000000000..47f1dc8dad5189495c3ca2a74d6b72ea96fc6de1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-testRunner.md @@ -0,0 +1,51 @@ +# TestRunner + +> **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 + +```js +import TestRunner from '@ohos.application.testRunner' +``` + + + +## TestRunner.onPrepare + +onPrepare(): void + +Prepares the unit test environment to run test cases. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + +```js +export default class UserTestRunner extends TestRunner { + onPrepare() { + console.log("Trigger onPrepare") + } +}; +``` + + + +## TestRunner.onRun + +onRun(): void + +Runs test cases. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + +```js +export default class UserTestRunner extends TestRunner { + onRun() { + console.log("Trigger onRun") + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index 047a66fbf44e97d3c45ac04d04ba5be64b629fd1..8aa15caf96fdf5886027bfae520473081cedef87 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -45,7 +45,7 @@ let treeMap = new TreeMap(); ### isEmpty -isEmpty(): boolean; +isEmpty(): boolean Checks whether this container is empty (contains no entry). @@ -65,7 +65,7 @@ let result = treeMap.isEmpty(); ### hasKey -hasKey(key: K): boolean; +hasKey(key: K): boolean Checks whether this container has the specified key. @@ -73,7 +73,7 @@ Checks whether this container has the specified key. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| key | K | Yes| Key to query.| +| key | K | Yes| Key to check.| **Return value** @@ -101,7 +101,7 @@ Checks whether this container has the specified value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value to query.| +| value | V | Yes| Value to check.| **Return value** @@ -149,7 +149,7 @@ let result = treeMap.get("sdfs"); ### getFirstKey -getFirstKey(): K; +getFirstKey(): K Obtains the first key in this container. @@ -171,7 +171,7 @@ let result = treeMap.getFirstKey(); ### getLastKey -getLastKey(): K; +getLastKey(): K Obtains the last key in this container. @@ -215,6 +215,7 @@ treeMap.setAll(map); ### set + set(key: K, value: V): Object Adds an entry to this container. @@ -242,7 +243,7 @@ treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); ### remove -remove(key: K): V; +remove(key: K): V Removes the entry with the specified key from this container. @@ -326,6 +327,7 @@ let result = treeMap.getHigherKey("sdfs"); ``` ### replace + replace(key: K, newValue: V): boolean Replaces an entry in this container. @@ -424,7 +426,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void +forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -438,8 +440,8 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | V | Yes| Value of the entry that is currently traversed.| -| key | K | Yes| Key of the entry that is currently traversed.| +| value | V | No| Value of the entry that is currently traversed.| +| key | K | No| Key of the entry that is currently traversed.| | map | TreeMap | No| Instance that invokes the **forEach** method.| **Example** @@ -484,7 +486,7 @@ while(temp != undefined) { ### [Symbol.iterator] -[Symbol.iterator]\(): IterableIterator<[K, V]>; +[Symbol.iterator]\(): IterableIterator<[K, V]> Obtains an iterator, each item of which is a JavaScript object. diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index bc937047ab2edb71d6c27322ba93f785632e9079..a37b5515c9aed096bb708c40eb2482acf35311d0 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -136,6 +136,7 @@ let result = treeSet.getLastValue(); ### add + add(value: T): boolean Adds an entry to this container. @@ -162,7 +163,7 @@ let result = treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); ### remove -remove(value: T): boolean; +remove(value: T): boolean Removes the entry with the specified key from this container. @@ -335,7 +336,7 @@ while(temp != undefined) { ### forEach -forEach(callbackfn: (value: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void +forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -349,7 +350,7 @@ Uses a callback to traverse the entries in this container and obtain their posit callbackfn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | T | Yes| Value of the entry that is currently traversed.| +| value | T | No| Value of the entry that is currently traversed.| | key | T | No| Key of the entry that is currently traversed (same as **value**).| | set | TreeSet<T> | No| Instance that invokes the **forEach** method.| diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md new file mode 100644 index 0000000000000000000000000000000000000000..b554e47f481696c48dea31a47315e454a01b9efa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -0,0 +1,1058 @@ +# UiTest + +>**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 + +``` +import {UiDriver,BY,MatchPattern} from '@ohos.uitest' +``` + +## By + +The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. +The API capabilities provided by the **By** class exhibit the following features: + +- Allows one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. + +- Provides multiple match patterns for component attributes. + +- Supports absolute positioning and relative positioning for components. APIs such as **isBefore** and **isAfter** can be used to specify the features of adjacent components to assist positioning. + +All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode, for example, **BY.text('123').type('button')**. + +### enum MatchPattern + +Enumerates the match patterns supported for component attributes. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | Contain the given value. | +| STARTS_WITH | 2 | Start with the given value.| +| ENDS_WITH | 3 | End with the given value.| + +### By.text + +text(txt:string,pattern?:MatchPattern):By + +Specifies the text attribute of the target component. Multiple match patterns are supported. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------ | ---- | ---------------------------------- | +| txt | string | Yes | Component text, used to match the target component.| +| pattern | MatchPattern | No | Match pattern. The default value is **EQUALS**. | + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute + of the target component. +``` + + +### By.key + +key(key:string):By; + +Specifies the key attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------- | +| key | string | Yes | Component key.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute + of the target component. +``` + + +### By.id + +id(id:number):By; + +Specifies the ID property of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| id | number | Yes | Component ID.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.id(123) // Use the static constructor BY to create a By object and specify the ID attribute + of the target component. +``` + + +### By.type + +type(tp:string):By; + +Specifies the type property of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| tp | string | Yes | Component type.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute + of the target component. +``` + + +### By.clickable + +clickable(b?:bool):By; + +Specifies the clickable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Clickable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable attribute + of the target component. +``` + + +### By.scrollable + +scrollable(b?:bool):By; + +Specifies the scrollable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | +| b | bool | No | Scrollable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable attribute + of the target component. +``` + +### By.enabled + +enabled(b?:bool):By; + +Specifies the enable attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| b | bool | No | Enable status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enable attribute + of the target component. +``` + +### By.focused + +focused(b?:bool):By; + +Specifies the focused attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------ | +| b | bool | No | Focused status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the focused attribute + of the target component. +``` + +### By.selected + +selected(b?:bool):By; + +Specifies the selected attribute of the target component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------------------ | +| b | bool | No | Selected status of the target component. The default value is **true**.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected attribute + of the target component. +``` + +### By.isBefore + +isBefore(by:By):By; + +Specifies the attributes of the component before which the target component is located. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| by | By | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes + of the component before which the target component is located. +``` + +### By.isAfter + +isAfter(by:By):By; + +Specifies the attributes of the component after which the target component is located. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| by | By | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type| Description | +| ---- | -------------- | +| By | Returns the **By** object itself.| + +**Example** + +``` +let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes + of the component after which the target component is located. +``` + +## UiComponent + +In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. +All APIs provided by this class use a promise to return the result and must be invoked using **await**. + +### UiComponent.click + +click():Promise; + +Clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.click() +} +``` + +### UiComponent.doubleClick + +doubleClick():Promise; + +Double-clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await buttont.doubleClick() +} +``` + +### UiComponent.longClick + +longClick():Promise; + +Long-clicks this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.longClick() +} +``` + +### UiComponent.getId + +getId():Promise; + +Obtains the ID of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------- | +| Promise; | Promise used to return the component ID.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let num = await button.getId() +} +``` + +### UiComponent.getKey + +getKey():Promise; + +Obtains the key of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | -------------------------- | +| Promise; | Promise used to return the component key.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let str_key = await button.getKey() +} +``` + +### UiComponent.getText + +getText():Promise; + +Obtains the text information of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------- | +| Promise; | Promise used to return the text information of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let text = await button.getText() +} +``` + +### UiComponent.getType + +getType():Promise; + +Obtains the type of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------- | +| Promise; | Promise used to return the component type.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + let type = await button.getType() +} +``` + +### UiComponent.isClickable + +isClickable():Promise; + +Obtains the clickable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the clickable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isClickable()) { + console.info('This button can be Clicked') + } + else{ + console.info('This button can not be Clicked') + } +} +``` + +### UiComponent.isScrollable + +isScrollable():Promise; + +Obtains the scrollable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the scrollable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.scrollable(true)) + if(await scrollBar.isScrollable()) { + console.info('This scrollBar can be operated') + } + else{ + console.info('This scrollBar can not be operated') + } +} +``` + + +### UiComponent.isEnabled + +isEnabled():Promise; + +Obtains the enable status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise; | Promise used to return the enable status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isEnabled()) { + console.info('This button can be operated') + } + else{ + console.info('This button can not be operated') + } +} + +``` + +### UiComponent.isFocused + +isFocused():Promise; + +Obtains the focused status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | --------------------------------- | +| Promise; | Promise used to return the focused status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isFocused()) { + console.info('This button is focused') + } + else{ + console.info('This button is not focused') + } +} +``` + +### UiComponent.isSelected + +isSelected():Promise; + +Obtains the selected status of this component. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise; | Promise used to return the selected status of the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + if(await button.isSelected()) { + console.info('This button is selected') + } + else{ + console.info('This button is not selected') + } +} +``` + +### UiComponent.inputText + +inputText(text: string):Promise; + +Enters text into this component (available for text boxes). + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------- | +| text | string | Yes | Text to be entered to the component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.type('button')) + await button.inputText('next page') +} +``` + +### UiComponent.scrollSearch + +scrollSearch(by:By):Promise; + +Scrolls on this component to search for the target component (available for lists). + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------- | +| Promise; | Promise used to return the target component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let scrollBar = await driver.findComponent(BY.scrollable(true)) + let button = await scrollBar.scrollSearch(BY.text('next page')) +} +``` + +## UiDriver + +The **UiDriver** class is the main entry to the **uitest** test framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. +All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. + +### UiDriver.create + +static create():UiDriver; + +Creates a **UiDriver** object and returns the object created. This API is a static API. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ------- | ---------------------- | +| UiDrive | Returns the **UiDriver** object created.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() +} +``` + +### UiDriver.delayMs + +delayMs(duration:number):Promise; + +Delays this **UiDriver** object within the specified duration. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| duration | number | Yes | Duration of time.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.delayMs(1000) +} +``` + +### UiDriver.findComponent + +findComponent(by:By):Promise; + +Searches this **UiDriver** object for the target component that has the given attributes. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise; | Promise used to return the found component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let button = await driver.findComponent(BY.text('next page')) +} +``` + +### UiDriver.findComponents + +findComponents(by:By):Promise>; + +Searches this **UiDriver** object for all components that match the given attributes. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| ---------------------------- | ------------------------------------- | +| Promise>; | Promise used to return a list of found components.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + let buttonList = await driver.findComponents(BY.text('next page')) +} +``` + +### UiDriver.assertComponentExist + +assertComponentExist(by:By):Promise; + +Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------------ | +| by | By | Yes | Attributes of the target component.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.assertComponentExist(BY.text('next page')) +} +``` + +### UiDriver.pressBack + +pressBack():Promise; + +Presses the Back button on this **UiDriver** object. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.pressBack() +} +``` + +### UiDriver.triggerKey + +triggerKey(keyCode:number):Promise; + +Triggers the key of this **UiDriver** object that matches the given key code. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------- | +| keyCode | number | Yes | Key code.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.triggerKey(123) +} +``` + +### UiDriver.click + +click(x:number,y:number):Promise; + +Clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.click(100,100) +} +``` + +### UiDriver.doubleClick + +doubleClick(x:number,y:number):Promise; + +Double-clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.doubleClick(100,100) +} +``` + +### UiDriver.longClick + +longClick(x:number,y:number):Promise; + +Long-clicks a specific point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------------------------- | +| x,y | number,number | Yes | Coordinate information of a specific point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.longClick(100,100) +} +``` + +### UiDriver.swipe + +swipe(startx:number,starty:number,endx:number,endy:number):Promise; + +Swipes from the start point to the end point of this **UiDriver** object based on the given coordinates. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | ------------------------------------------- | +| startx,starty | number,number | Yes | Coordinate information of the start point in the (number,number) format.| +| endx,endy | number,number | Yes | Coordinate information of the end point in the (number,number) format.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.swipe(100,100,200,200) +} +``` + +### UiDriver.screenCap + +screenCap(savePath:string):Promise; + +Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. + +**Required permissions**: none + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | +| savePath | string | Yes | File save path.| + +**Example** + +``` +async function demo() { + let driver = UiDriver.create() + await driver.screenCap('/local/tmp/') +} +``` diff --git a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md b/en/application-dev/reference/apis/js-apis-uripermissionmanager.md deleted file mode 100644 index b004a0a4c9c17d9c7fe09ee4c1f8db66297222fe..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-uripermissionmanager.md +++ /dev/null @@ -1,78 +0,0 @@ -# UriPermissionManager - -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -Implements URI permission management. - - -## Modules to Import - - -``` -import UriPermissionManager from '@@ohos.application.UriPermissionManager'; -``` - - -## verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback<number>): void - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a callback to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - | callback | AsyncCallback<number> | Yes| Callback used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -- Example - - ``` - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId, (result) => { - console.log("result.code = " + result.code) - }) // accessTokenId is obtained through the **BundleManager** API. - ``` - - -## verifyUriPermission - -verifyUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise<number> - -Checks whether an application has the permission specified by **flag** for an URI. This API uses a promise to return the result. - -**System capability**: - -SystemCapability.Ability.AbilityRuntime.Core - -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | uri | string | Yes| URI of a file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| - | flag | wantConstant.Flags | Yes| Read or write permission on the file specified by the URI.| - | accessTokenId | number | Yes| Unique ID of an application, which is obtained through the **BundleManager** API.| - -- Return value - | Type| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the check result. The value **0** means that the application has the specified permission, and **-1** means the opposite.| - -- Example - - ``` - let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10" - UriPermissionManager.verifyUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, accessTokenId) - .then((data) => { - console.log('Verification succeeded.' + data) - }).catch((error) => { - console.log('Verification failed.'); - }) - ``` diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 51a5615b69ef513c1c05d5fc13daa4a4948396a7..7ff865803cc3c32c0a78197ebac2996516e7dd54 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -419,122 +419,139 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface). +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| address | number | Endpoint address.
**System capability**: SystemCapability.USB.USBManager| -| attributes | number | Endpoint attributes.
**System capability**: SystemCapability.USB.USBManager| -| interval | number | Endpoint interval.
**System capability**: SystemCapability.USB.USBManager| -| maxPacketSize | number | Maximum size of data packets on the endpoint.
**System capability**: SystemCapability.USB.USBManager| -| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction.
**System capability**: SystemCapability.USB.USBManager| -| number | number | Endpoint number.
**System capability**: SystemCapability.USB.USBManager| -| type | number | Endpoint type.
**System capability**: SystemCapability.USB.USBManager| -| interfaceId | number | Unique ID of the interface to which the endpoint belongs.
**System capability**: SystemCapability.USB.USBManager| +| address | number | Endpoint address.| +| attributes | number | Endpoint attributes.| +| interval | number | Endpoint interval.| +| maxPacketSize | number | Maximum size of data packets on the endpoint.| +| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction.| +| number | number | Endpoint number.| +| type | number | Endpoint type.| +| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| ## USBInterface Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **USBInterface** instances, each providing a specific function. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| id | number | Unique ID of the USB interface.
**System capability**: SystemCapability.USB.USBManager| -| protocol | number | Interface protocol.
**System capability**: SystemCapability.USB.USBManager| -| clazz | number | Device type.
**System capability**: SystemCapability.USB.USBManager| -| subClass | number | Device subclass.
**System capability**: SystemCapability.USB.USBManager| -| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Interface name.
**System capability**: SystemCapability.USB.USBManager| -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface.
**System capability**: SystemCapability.USB.USBManager| +| id | number | Unique ID of the USB interface.| +| protocol | number | Interface protocol.| +| clazz | number | Device type.| +| subClass | number | Device subclass.| +| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| +| name | string | Interface name.| +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface.| ## USBConfig Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| id | number | Unique ID of the USB configuration.
**System capability**: SystemCapability.USB.USBManager| -| attributes | number | Configuration attributes.
**System capability**: SystemCapability.USB.USBManager| -| maxPower | number | Maximum power consumption, in mA.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Configuration name, which can be left empty.
**System capability**: SystemCapability.USB.USBManager| -| isRemoteWakeup | boolean | Support for remote wakeup.
**System capability**: SystemCapability.USB.USBManager| -| isSelfPowered | boolean | Support for independent power supplies.
**System capability**: SystemCapability.USB.USBManager| -| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes.
**System capability**: SystemCapability.USB.USBManager| +| id | number | Unique ID of the USB configuration.| +| attributes | number | Configuration attributes.| +| maxPower | number | Maximum power consumption, in mA.| +| name | string | Configuration name, which can be left empty.| +| isRemoteWakeup | boolean | Support for remote wakeup.| +| isSelfPowered | boolean | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes.| ## USBDevice -Represents the USB device information. +Represents USB device information. + +**System capability**: SystemCapability.USB.USBManager | Name| Type| Description| | -------- | -------- | -------- | -| busNum | number | Bus address.
**System capability**: SystemCapability.USB.USBManager| -| devAddress | number | Device address.
**System capability**: SystemCapability.USB.USBManager| -| serial | string | Device SN.
**System capability**: SystemCapability.USB.USBManager| -| name | string | Device name.
**System capability**: SystemCapability.USB.USBManager| -| manufacturerName | string | Device manufacturer.
**System capability**: SystemCapability.USB.USBManager| -| productName | string | Product information.
**System capability**: SystemCapability.USB.USBManager| -| version | string | Version.
**System capability**: SystemCapability.USB.USBManager| -| vendorId | number | Vendor ID.
**System capability**: SystemCapability.USB.USBManager| -| productId | number | Product ID.
**System capability**: SystemCapability.USB.USBManager| -| clazz | number | Device class.
**System capability**: SystemCapability.USB.USBManager| -| subClass | number | Device subclass.
**System capability**: SystemCapability.USB.USBManager| -| protocol | number | Device protocol code.
**System capability**: SystemCapability.USB.USBManager| -| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.
**System capability**: SystemCapability.USB.USBManager| +| busNum | number | Bus address.| +| devAddress | number | Device address.| +| serial | string | Device SN.| +| name | string | Device name.| +| manufacturerName | string | Device manufacturer.| +| productName | string | Product information.| +| version | string | Version.| +| vendorId | number | Vendor ID.| +| productId | number | Product ID.| +| clazz | number | Device class.| +| subClass | number | Device subclass.| +| protocol | number | Device protocol code.| +| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.| ## USBDevicePipe Represents a USB device pipe, which is used to determine a USB device. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | -| busNum | number | Bus address.
**System capability**: SystemCapability.USB.USBManager| -| devAddress | number | Device address.
**System capability**: SystemCapability.USB.USBManager| +| busNum | number | Bus address.| +| devAddress | number | Device address.| ## USBControlParams Represents control transfer parameters. +**System capability**: SystemCapability.USB.USBManager + | Name| Type| Description| | -------- | -------- | -------- | | request | number | Request type.| -| target | [USBRequestTargetType](#usbrequesttargettype) | Represents the request target type.
**System capability**: SystemCapability.USB.USBManager| -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Request control type.
**System capability**: SystemCapability.USB.USBManager| -| value | number | Request parameters
**System capability**: SystemCapability.USB.USBManager| -| index | number | Index of the request parameter value.
**System capability**: SystemCapability.USB.USBManager| -| data | Uint8Array | Buffer for writing or reading data.
**System capability**: SystemCapability.USB.USBManager| +| target | [USBRequestTargetType](#usbrequesttargettype) | Represents the request target type.| +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Request control type.| +| value | number | Request parameters| +| index | number | Index of the request parameter value.| +| data | Uint8Array | Buffer for writing or reading data.| ## USBRequestTargetType Represents the request target type. +**System capability**: SystemCapability.USB.USBManager | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_TARGET_DEVICE | 0 | Device.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TARGET_OTHER | 3 | Others
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_TARGET_DEVICE | 0 | Device.| +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.| +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| +| USB_REQUEST_TARGET_OTHER | 3 | Others| ## USBControlRequestType Enumerates control request types. +**System capability**: SystemCapability.USB.USBManager + | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_TYPE_STANDARD | 0 | Standard
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TYPE_CLASS | 1 | Class.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_TYPE_VENDOR | 2 | Vendor
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_TYPE_STANDARD | 0 | Standard| +| USB_REQUEST_TYPE_CLASS | 1 | Class.| +| USB_REQUEST_TYPE_VENDOR | 2 | Vendor| ## USBRequestDirection Enumerates request directions. +**System capability**: SystemCapability.USB.USBManager + | Name| Default Value | Description| | -------- | -------- | -------- | -| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.
**System capability**: SystemCapability.USB.USBManager| -| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.
**System capability**: SystemCapability.USB.USBManager| +| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| +| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| 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 1ce2456d568800cb8fe2cddd48d697e6acfd3d0e..02992c0a5f646bd1016cbcdd3aae92aac0c32f2a 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,66 +1,102 @@ -# User Authentication +# User Authentication ->**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. +> ![icon-note.gif](public_sys-resources/icon-note.gif)**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. -## Modules to Import +## Modules to Import -``` +```js import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## System Capabilities - -SystemCapability.UserIAM.UserAuth - -## Required Permissions - -ohos.permission.ACCESS\_BIOMETRIC - -## Sample Code +## Example -``` +```js +// API version 6 import userIAM_userAuth from '@ohos.userIAM.userAuth'; export default { startAuth() { console.info("start auth"); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - // Add the logic for displaying the prompt message. - }; let auth = userIAM_userAuth.getAuthenticator(); - auth.on("tip", tipCallback); auth.execute("FACE_ONLY", "S2").then((code)=>{ - auth.off("tip", tipCallback); console.info("auth success"); - // Add the logic for authentication success. + // Add the logic to be executed when the authentication is successful. }).catch((code)=>{ - auth.off("tip", tipCallback); console.error("auth fail, code = " + code); - // Add the logic for authentication failure. + // Add the logic to be executed when the authentication fails. + }); + } +} +``` + +```js +// API version 8 +import userIAM_userAuth from '@ohos.userIAM.userAuth'; +let auth = new userIAM_userAuth.UserAuth(); + +export default { + getVersion() { + console.info("start get version"); + let version = this.auth.getVersion(); + console.info("auth version = " + version); + }, + + startAuth() { + console.info("start auth"); + this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == 'SUCCESS') { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } }); }, checkAuthSupport() { console.info("start check auth support"); - let auth = userIAM_userAuth.getAuthenticator(); - let checkCode = auth.checkAvailability("FACE_ONLY", "S2"); - if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) { + let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("check auth support success"); - // Add the logic for the specified authentication type supported. + // Add the logic to be executed if the specified authentication type is supported. } else { console.error("check auth support fail, code = " + checkCode); - // Add the logic for the authentication type that is not supported. + // Add the logic to be executed if the specified authentication type is not supported. } }, cancelAuth() { console.info("start cancel auth"); - let auth = userIAM_userAuth.getAuthenticator(); - let cancelCode = auth.cancel(); + // Obtain contextId using auth(). + let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + console.info("auth onResult result = " + result); + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + console.info("auth onAcquireInfo module = " + module); + } + }); + let cancelCode = this.auth.cancel(contextId); if (cancelCode == userIAM_userAuth.Result.SUCCESS) { console.info("cancel auth success"); } else { @@ -70,800 +106,504 @@ export default { } ``` -## userIAM\_userAuth.getAuthenticator - -getAuthenticator\(\): Authenticator - -Obtains an **Authenticator** object for user authentication. 6+ - -Obtains an **Authenticator** object to check the device's capability of user authentication, perform or cancel user authentication, and obtain the tips generated in the authentication process. 7+ - -- Return values - - - - - - - - - - -

Type

-

Description

-

Authenticator

-

Authenticator object obtained.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - ``` - - -## Authenticator - -Provides an **Authenticator** object. - -### execute - -execute\(type: string, level: string, callback: AsyncCallback\): void - -Performs user authentication and returns the authentication result using an asynchronous callback. - -- 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.

-

callback

-

AsyncCallback<number>

-

No

-

Callback invoked to return the authentication result

-
- - Callback return values - - - - - - - - - - -

Type

-

Description

-

number

-

Authentication result. See AuthenticationResult.

-
- -- Example - - ``` - authenticator.execute("FACE_ONLY", "S2", (code)=>{ - if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }) - ``` - - -### execute - -execute\(type:string, level:string\): Promise - -Performs user authentication and returns the authentication result using a promise. - -- 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.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

Promise<number>

-

Promise used to return the authentication result. The number in the promise indicates the authentication result. See AuthenticationResult.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - authenticator.off("tip", tipCallback); - console.info("auth success"); - }).catch((code)=>{ - authenticator.off("tip", tipCallback); - console.error("auth fail, code = " + code); - }); - ``` - - -### cancel7+ - -cancel\(\): number - -Cancels the current authentication. - -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Whether the authentication is canceled. For details, see Result.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let cancelCode = authenticator.cancel(); - if (cancelCode == userIAM_userAuth.Result.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` - - -### checkAvailability7+ - -checkAvailability\(type: AuthType, level: SecureLevel\): number - -Checks whether the device supports the specified authentication type and security level. - -- 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.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

number

-

Check result. For details, see CheckAvailabilityResult.

-
- -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let checkCode = authenticator.checkAvailability("FACE_ONLY", "S2"); - if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) { - console.info("check auth support success"); - } else { - console.error("check auth support fail, code = " + checkCode); - } - ``` - - -### on7+ - -on\(type: "tip", callback: Callback\) : void; - -Subscribes to the events of the specified type. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. Currently, only tip is supported. An event is triggered when the authentication service sends a message to the caller.

-

callback

-

Callback<Tip>

-

Yes

-

Callback used to report the event of the specified type. Currently, only the tip event is supported.

-
- - -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode +") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - authenticator.on("tip", tipCallback); - ``` - - -### off7+ - -off\(type: "tip", callback?: Callback\) : void; - -Unsubscribes from the events of the specified type. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

Event type. Currently, only tip is supported.

-

callback

-

Callback<Tip>

-

No

-

Callback used to report the event of the specified type. Currently, only the tip event is supported. If this parameter is not specified, all callbacks corresponding to type will be canceled.

-
- - -- Example - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - // Unsubscribe from a specified callback. - authenticator.off("tip", tipCallback); - - // Unsubscribe from all callbacks. - authenticator.off("tip"); - ``` - - -## AuthenticationResult +## userIAM_userAuth.getAuthenticator(deprecated) + +getAuthenticator(): Authenticator + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [constructor](#constructor8). + +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.| + +**Example** + ```js + let authenticator = userIAM_userAuth.getAuthenticator(); + ``` + +## Authenticator(deprecated) + +> **NOTE**
+> This object is not longer maintained since API version 8. You are advised to use [UserAuth](#userauth8). + +Provides methods to manage an **Authenticator** object. + + +### execute(deprecated) + +execute(type: string, level: string, callback: AsyncCallback<number>): void + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). + +Performs user authentication. This method uses asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**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.| +| callback | AsyncCallback<number> | No | Callback used to return the result. | + + Parameters returned in callback + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| + +**Example** + ```js + authenticator.execute("FACE_ONLY", "S2", (code)=>{ + if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); + }) + ``` + + +### execute(deprecated) + +execute(type:string, level:string): Promise<number> + +> **NOTE**
+> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). + +Performs user authentication. This method uses a promise to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**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.| + +**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); +}); +``` + +## AuthenticationResult(deprecated) + +> **NOTE**
+> This parameter is not longer maintained since API version 8. You are advised to use [ResultCode](#resultcode8). Enumerates the authentication results. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NO_SUPPORT

-

-1

-

The device does not support the current authentication mode.

-

SUCCESS

-

0

-

The authentication is successful.

-

COMPARE_FAILURE

-

1

-

The feature comparison failed.

-

CANCELED

-

2

-

The user cancels the authentication.

-

TIMEOUT

-

3

-

The authentication has timed out.

-

CAMERA_FAIL

-

4

-

The camera failed to start.

-

BUSY

-

5

-

The authentication service is not available. Try again later.

-

INVALID_PARAMETERS

-

6

-

The authentication parameters are invalid.

-

LOCKED

-

7

-

The user account is locked because the number of authentication failures has reached the threshold.

-

NOT_ENROLLED

-

8

-

No authentication credential is registered.

-

GENERAL_ERROR

-

100

-

Other errors.

-
- -## Tip7+ - -Defines the object of the tip generated during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

errorCode

-

number

-

Yes

-

Whether the tip is obtained successfully. For details, see Result.

-

tipEvent

-

number

-

Yes

-

Tip event. For details, see TipEvent. Currently, only RESULT and ACQUIRE are supported.

-

tipCode

-

number

-

Yes

-

Tip code.

-
  • If tipEvent is RESULT, the tip code provides the authentication result. For details, see AuthenticationResult.
  • If tipEvent is ACQUIRE, the tip code provides prompt information. For details, see TipCode.
-

tipInfo

-

string

-

Yes

-

Description of the tip code.

-
- -## Result7+ +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ------------------ | ------ | -------------------------- | +| NO_SUPPORT | -1 | The device does not support the current authentication mode.| +| SUCCESS | 0 | The authentication is successful. | +| COMPARE_FAILURE | 1 | The feature comparison failed. | +| CANCELED | 2 | The authentication was canceled by the user. | +| TIMEOUT | 3 | The authentication has timed out. | +| CAMERA_FAIL | 4 | The camera failed to start. | +| BUSY | 5 | The authentication service is not available. Try again later. | +| INVALID_PARAMETERS | 6 | The authentication parameters are invalid. | +| LOCKED | 7 | The user account is locked because the number of authentication failures has reached the threshold.| +| NOT_ENROLLED | 8 | No authentication credential is registered. | +| GENERAL_ERROR | 100 | Other errors. | + +## UserAuth8+ + +Provides methods to manage an **Authenticator** object. + +### constructor8+ + +constructor() + +A constructor used to create an **authenticator** object. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| [UserAuth](#userauth8) | **Authenticator** object obtained.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + ``` + +### getVersion8+ + +getVersion() : number + +Obtains the authentication executor version. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Authentication executor version obtained.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + let version = auth.getVersion(); + console.info("auth version = " + version); + ``` + +### getAvailableStatus8+ + +getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number + +Checks whether the authentication capability of the specified trust level is available. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------- | ---- | -------------------------- | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Whether the authentication capability of the specified trust level is available. For details, see [ResultCode](#resultcode8).| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); + // Add the logic to be executed if the specified authentication type is supported. + } else { + console.error("check auth support fail, code = " + checkCode); + // Add the logic to be executed if the specified authentication type is not supported. + } + ``` + +### auth8+ + +auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array + +Performs user authentication. This method uses a callback to return the result. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------------- | ---- | ------------------------ | +| challenge | Uint8Array | Yes | Challenge value, which can be null. | +| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback used to return the result. | + +**Return value** + +| Type | Description | +| ---------- | ------------------------------------------------------------ | +| Uint8Array | ContextId, which is used as the input parameter of [cancelAuth](#cancelauth8).| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } + }); + ``` + +### cancelAuth8+ + +cancelAuth(contextID : Uint8Array) : number + +Cancels an authentication. + +**Required permissions**: ohos.permission.ACCESS_BIOMETRIC + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------- | ---- | ------------------------------------------ | +| contextID | Uint8Array | Yes | Context ID, which is obtained using [auth](#auth8).| + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| number | Whether the authentication is canceled.| + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + // 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); + if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); + } else { + console.error("cancel auth fail"); + } + ``` + +## IUserAuthCallback8+ + +Defines the object of the result returned by the callback during authentication. + +### onResult8+ + +onResult: (result : number, extraInfo : AuthResult) => void + +Obtains the authentication result. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------------------ | +| result | number | Yes | Authentication result obtained. For details, see [ResultCode](#resultcode8). | +| extraInfo | [AuthResult](#authresult8) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| + + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } + }); + ``` + +### onAcquireInfo8+ + +onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void + +Obtains the tip code information during authentication. This function is optional. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------ | +| module | number | Yes | Type of the authentication executor. | +| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| extraInfo | any | Yes | Reserved field. | + +**Example** + + ```js + import userIAM_userAuth from '@ohos.userIAM.userAuth'; + + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } + }); + ``` + +## AuthResult8+ + +Represents the authentication result object. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| token | Uint8Array | No | Identity authentication token. | +| remainTimes | number | No | Number of remaining authentication operations.| +| freezingTime | number | No | Time for which the authentication operation is frozen.| + +## ResultCode8+ Enumerates the operation results. - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SUCCESS

-

0

-

Successful

-

FAILED

-

1

-

Failed

-
- -## CheckAvailabilityResult7+ - -Enumerates the device authentication capability check results. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SUPPORTED

-

0

-

The device supports the specified authentication type and security level.

-

AUTH_TYPE_NOT_SUPPORT

-

1

-

The device does not support the specified authentication type.

-

SECURE_LEVEL_NOT_SUPPORT

-

2

-

The device does not support the specified authentication security level.

-

DISTRIBUTED_AUTH_NOT_SUPPORT

-

3

-

The device does not support distributed authentication.

-

NOT_ENROLLED

-

4

-

The device does not have the authentication credential.

-

PARAM_NUM_ERROR

-

5

-

The number of parameters is incorrect.

-
- -## TipEvent7+ - -Enumerates the tip events occurred during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

RESULT

-

1

-

Credential enrollment result or authentication result.

-

CANCEL

-

2

-

Credential enrollment or authentication canceled.

-

ACQUIRE

-

3

-

Tips generated in the credential enrollment or authentication process.

-

BUSY

-

4

-

Credential enrollment or authentication unavailable.

-

OUT_OF_MEM

-

5

-

Insufficient memory.

-

FACE_ID

-

6

-

Index of a face authentication credential.

-
- -## TipCode7+ - -Enumerates the tip codes generated during the authentication process. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

FACE_AUTH_TIP_TOO_BRIGHT

-

1

-

The obtained facial image is too bright due to high illumination.

-

FACE_AUTH_TIP_TOO_DARK

-

2

-

The obtained facial image is too dark due to low illumination.

-

FACE_AUTH_TIP_TOO_CLOSE

-

3

-

The face is too close to the device.

-

FACE_AUTH_TIP_TOO_FAR

-

4

-

The face is too far away from the device.

-

FACE_AUTH_TIP_TOO_HIGH

-

5

-

Only the upper part of the face is captured because the device is angled too high.

-

FACE_AUTH_TIP_TOO_LOW

-

6

-

Only the lower part of the face is captured because the device is angled too low.

-

FACE_AUTH_TIP_TOO_RIGHT

-

7

-

Only the right part of the face is captured because the device is deviated to the right.

-

FACE_AUTH_TIP_TOO_LEFT

-

8

-

Only the left part of the face is captured because the device is deviated to the left.

-

FACE_AUTH_TIP_TOO_MUCH_MOTION

-

9

-

The face moves too fast during facial information collection.

-

FACE_AUTH_TIP_POOR_GAZE

-

10

-

The face is not facing the camera.

-

FACE_AUTH_TIP_NOT_DETECTED

-

11

-

No face is detected.

-
+**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------------------- | ------ | -------------------- | +| SUCCESS | 0 | The operation is successful. | +| FAIL | 1 | The operation failed. | +| GENERAL_ERROR | 2 | A common operation error occurred. | +| CANCELED | 3 | The operation is canceled. | +| TIMEOUT | 4 | The operation timed out. | +| TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | +| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | +| BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | +| LOCKED | 9 | The authentication executor is locked. | +| NOT_ENROLLED | 10 | The user has not entered the authentication information.| + + +## FaceTips8+ + +Enumerates the tip codes used during the facial authentication process. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------------------------- | ------ | ------------------------------------ | +| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | +| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | +| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. | +| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. | +| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. | +| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | +| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is deviated to the right. | +| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is deviated to the left. | +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection.| +| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the camera. | +| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | + + +## FingerprintTips8+ + +Enumerates the tip codes used during the fingerprint authentication process. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| --------------------------------- | ------ | -------------------------------------------------- | +| FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | +| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| +| FINGERPRINT_AUTH_TIP_INSUFFICIENT | 2 | The noise of the fingerprint image is too large to be processed. | +| FINGERPRINT_AUTH_TIP_PARTIAL | 3 | Incomplete fingerprint image is detected. | +| FINGERPRINT_AUTH_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to fast movement. | +| FINGERPRINT_AUTH_TIP_TOO_SLOW | 5 | Failed to obtain the fingerprint image because the finger seldom moves. | + + +## UserAuthType8+ + +Enumerates the identity authentication types. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name | Default Value| Description | +| ----------- | ------ | ---------- | +| FACE | 2 | Facial authentication.| +| FINGERPRINT | 4 | Fingerprint authentication.| + +## AuthTrustLevel8+ + +Enumerates the trust levels of the authentication result. + +**System capability**: SystemCapability.UserIAM.UserAuth.Core + +| Name| Default Value| Description | +| ---- | ------ | ------------------------- | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 8f24f6a17a4f5bbac42b8b6ddbe48711b80af4ab..b4a031c8a87a50688d0bcfaa6e7493eeb322004d 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -5,7 +5,7 @@ > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. +This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **types** for checks of built-in object types. ## Modules to Import @@ -1614,20 +1614,20 @@ Decodes the input content asynchronously. ``` -## Types8+ +## types8+ ### constructor8+ constructor() -A constructor used to create a **Types** object. +A constructor used to create a **types** object. **System capability**: SystemCapability.Utils.Lang **Example** ``` - var type = new util.Types(); + var type = new util.types(); ``` @@ -1651,7 +1651,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isAnyArrayBuffer(new ArrayBuffer([])); ``` @@ -1678,7 +1678,7 @@ Checks whether the input value is of the **ArrayBufferView** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isArrayBufferView(new Int8Array([])); ``` @@ -1703,7 +1703,7 @@ Checks whether the input value is of the **arguments** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); function foo() { var result = that.isArgumentsObject(arguments); } @@ -1731,7 +1731,7 @@ Checks whether the input value is of the **ArrayBuffer** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isArrayBuffer(new ArrayBuffer([])); ``` @@ -1756,7 +1756,7 @@ Checks whether the input value is an asynchronous function. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isAsyncFunction(async function foo() {}); ``` @@ -1781,7 +1781,7 @@ Checks whether the input value is of the **Boolean** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isBooleanObject(new Boolean(true)); ``` @@ -1806,7 +1806,7 @@ Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isBoxedPrimitive(new Boolean(false)); ``` @@ -1831,7 +1831,7 @@ Checks whether the input value is of the **DataView** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const ab = new ArrayBuffer(20); var result = that.isDataView(new DataView(ab)); ``` @@ -1857,7 +1857,7 @@ Checks whether the input value is of the **Date** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isDate(new Date()); ``` @@ -1882,7 +1882,7 @@ Checks whether the input value is of the **native external** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const data = util.createExternalType(); var result = that.isExternal(data); ``` @@ -1908,7 +1908,7 @@ Checks whether the input value is of the **Float32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isFloat32Array(new Float32Array()); ``` @@ -1933,7 +1933,7 @@ Checks whether the input value is of the **Float64Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isFloat64Array(new Float64Array()); ``` @@ -1958,7 +1958,7 @@ Checks whether the input value is a generator function. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isGeneratorFunction(function* foo() {}); ``` @@ -1983,7 +1983,7 @@ Checks whether the input value is a generator object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); function* foo() {} const generator = foo(); var result = that.isGeneratorObject(generator); @@ -2010,7 +2010,7 @@ Checks whether the input value is of the **Int8Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt8Array(new Int8Array([])); ``` @@ -2035,7 +2035,7 @@ Checks whether the input value is of the **Int16Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt16Array(new Int16Array([])); ``` @@ -2060,7 +2060,7 @@ Checks whether the input value is of the **Int32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isInt32Array(new Int32Array([])); ``` @@ -2085,7 +2085,7 @@ Checks whether the input value is of the **Map** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isMap(new Map()); ``` @@ -2110,7 +2110,7 @@ Checks whether the input value is of the **MapIterator** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const map = new Map(); var result = that.isMapIterator(map.keys()); ``` @@ -2136,7 +2136,7 @@ Checks whether the input value is of the **Error** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isNativeError(new TypeError()); ``` @@ -2161,7 +2161,7 @@ Checks whether the input value is a number object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isNumberObject(new Number(0)); ``` @@ -2186,7 +2186,7 @@ Checks whether the input value is a promise. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isPromise(Promise.resolve(1)); ``` @@ -2211,7 +2211,7 @@ Checks whether the input value is a proxy. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const target = {}; const proxy = new Proxy(target, {}); var result = that.isProxy(proxy); @@ -2238,7 +2238,7 @@ Checks whether the input value is of the **RegExp** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isRegExp(new RegExp('abc')); ``` @@ -2263,7 +2263,7 @@ Checks whether the input value is of the **Set** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isSet(new Set()); ``` @@ -2288,7 +2288,7 @@ Checks whether the input value is of the **SetIterator** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const set = new Set(); var result = that.isSetIterator(set.keys()); ``` @@ -2314,7 +2314,7 @@ Checks whether the input value is a string object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isStringObject(new String('foo')); ``` @@ -2339,7 +2339,7 @@ Checks whether the input value is a symbol object. **Example** ``` - var that = new util.Types(); + var that = new util.types(); const symbols = Symbol('foo'); var result = that.isSymbolObject(Object(symbols)); ``` @@ -2367,7 +2367,7 @@ Checks whether the input value is of the **TypedArray** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isTypedArray(new Float64Array([])); ``` @@ -2392,7 +2392,7 @@ Checks whether the input value is of the **Uint8Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint8Array(new Uint8Array([])); ``` @@ -2417,7 +2417,7 @@ Checks whether the input value is of the **Uint8ClampedArray** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` @@ -2442,7 +2442,7 @@ Checks whether the input value is of the **Uint16Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint16Array(new Uint16Array([])); ``` @@ -2467,7 +2467,7 @@ Checks whether the input value is of the **Uint32Array** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isUint32Array(new Uint32Array([])); ``` @@ -2492,7 +2492,7 @@ Checks whether the input value is of the **WeakMap** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isWeakMap(new WeakMap()); ``` @@ -2517,6 +2517,6 @@ Checks whether the input value is of the **WeakSet** type. **Example** ``` - var that = new util.Types(); + var that = new util.types(); var result = that.isWeakSet(new WeakSet()); ``` diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index ce4af8ba13f2876cc08c8f7ab3be528f44301f32..149fdc42e3179d86a052ad72b87d4e4c1fd4f4e5 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -241,7 +241,8 @@ let result = vector.remove(2); ``` ### removeByRange -removeByRange(fromIndex: number, toIndex: number): void; + +removeByRange(fromIndex: number, toIndex: number): void Removes from this container all of the entries within a range, including the entry at the start position but not that at the end position. @@ -266,6 +267,7 @@ vector.removeByRange(2,6); ``` ### replaceAllElements + replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void @@ -303,8 +305,9 @@ vector.replaceAllElements((value, index) => { ``` ### forEach + forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, -thisArg?: Object): void; +thisArg?: Object): void Uses a callback to traverse the entries in this container and obtain their position indexes. @@ -338,6 +341,7 @@ vector.forEach((value, index) => { ``` ### sort + sort(comparator?: (firstValue: T, secondValue: T) => number): void Sorts entries in this container. @@ -369,6 +373,7 @@ vector.sort(); ``` ### subVector + subVector(fromIndex: number, toIndex: number): Vector<T> Obtains entries within a range in this container, including the entry at the start position but not that at the end position, and returns these entries as a new **Vector** instance. @@ -401,6 +406,7 @@ let result2 = vector.subVector(2,6); ``` ### clear + clear(): void Clears all entries in this container and sets its length to **0**. @@ -417,6 +423,7 @@ vector.clear(); ``` ### clone + clone(): Vector<T> Clones this container and returns a copy. The modification to the copy does not affect the original instance. @@ -439,6 +446,7 @@ let result = vector.clone(); ``` ### getCapacity + getCapacity(): number Obtains the capacity of this container. @@ -461,6 +469,7 @@ let result = vector.getCapacity(); ``` ### convertToArray + convertToArray(): Array<T> Converts this container into an array. @@ -483,6 +492,7 @@ let result = vector.convertToArray(); ``` ### isEmpty + isEmpty(): boolean Checks whether this container is empty (contains no entries). @@ -505,6 +515,7 @@ let result = vector.isEmpty(); ``` ### increaseCapacityTo + increaseCapacityTo(newCapacity: number): void Increases the capacity of this container. @@ -528,6 +539,7 @@ vector.increaseCapacityTo(8); ``` ### trimToCurrentLength + trimToCurrentLength(): void Trims the capacity of this container into its current length. @@ -699,6 +711,7 @@ let result = vector.getIndexFrom(4, 3); ``` ### setLength + setLength(newSize: number): void Sets a new length for this container. @@ -722,6 +735,7 @@ vector.setLength(2); ``` ### get + get(index: number): T Obtains an entry at the specified position in this container. @@ -749,6 +763,7 @@ Obtains an entry at the specified position in this container. let result = vector.get(2); ``` ### set + set(index: number, element: T): T Replaces an entry at the specified position in this container with a given entry. diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 55c4189e30fccbf66c71fce380642bb9a105805b..1251c4b6d0a6cb4b9f88b555101e230972906b05 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -22,18 +22,18 @@ Triggers vibration with a specific duration. This API uses a promise to return t **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | duration | number | Yes| Vibration duration.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| duration | number | Yes | Vibration duration.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(1000).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -53,13 +53,13 @@ Triggers vibration with a specific duration. This API uses an asynchronous callb **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | duration | number | Yes| Vibration duration.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is triggered successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| duration | number | Yes | Vibration duration. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(1000,function(error){ if(error){ @@ -81,17 +81,17 @@ Triggers vibration with a specific effect. This API uses a promise to return the **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | effectId | [EffectId](#effectid) | Yes| String that indicates the vibration effect.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ------------- | +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -111,13 +111,13 @@ Triggers vibration with a specific effect. This API uses an asynchronous callbac **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | effectId | [EffectId](#effectid) | Yes| String that indicates the vibration effect.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is triggered successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------------- | +| effectId | [EffectId](#effectid) | Yes | String that indicates the vibration effect. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is triggered successfully.| -- Example +**Example** ``` vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ if(error){ @@ -139,17 +139,17 @@ Stops the vibration based on the specified **stopMode**. This API uses a promise **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes| Vibration mode to stop.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | --------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop.| -- Return value - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| +**Return value** +| Type | Description | +| ------------------- | ----------- | +| Promise<void> | Promise used to indicate whether the vibration is stopped successfully.| -- Example +**Example** ``` vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ console.log("Promise returned to indicate a successful vibration."); @@ -169,13 +169,13 @@ Stops the vibration based on the specified **stopMode**. This API uses an asynch **System capability**: SystemCapability.Sensors.MiscDevice -- Parameters - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes| Vibration mode to stop.| - | callback | AsyncCallback<void> | No| Callback used to indicate whether the vibration is stopped successfully.| +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------- | ---- | ----------------------- | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Vibration mode to stop. | +| callback | AsyncCallback<void> | No | Callback used to indicate whether the vibration is stopped successfully.| -- Example +**Example** ``` vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ if(error){ @@ -193,8 +193,8 @@ Describes the vibration effect. **System capability**: SystemCapability.Sensors.MiscDevice -| Name| Default Value| Description| -| -------- | -------- | -------- | +| Name | Default Value | Description | +| ------------------ | -------------------- | --------------- | | EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| @@ -204,7 +204,7 @@ Describes the vibration mode to stop. **System capability**: SystemCapability.Sensors.MiscDevice -| Name| Default Value| Description| -| -------- | -------- | -------- | -| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| +| Name | Default Value | Description | +| ------------------------- | -------- | ---------------------------------------- | +| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| | VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 5b51de9baa01f675421059ab5acdeddd563208e5..d3d17810360c3ffa6074118413daddcb67fce31f 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -141,7 +141,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous | Name | Readable| Writable | Type | Mandatory| Description | | -------- | --- | ---- | ----------------------- | ---- | --------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose bundle name is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -213,7 +213,7 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose bundle name is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -282,7 +282,7 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | ----------------------- | ---- | ----------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose user ID is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the user ID.| **Example** @@ -354,7 +354,7 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose user ID is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -423,7 +423,7 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | --------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose want is to be obtained. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the want.| **Example** @@ -495,7 +495,7 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object whose want is to be obtained.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -564,7 +564,7 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return | Name | Readable| Writable| Type | Mandatory| Description | | -------- | --- | ---- | --------------------- | ---- | --------------------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object to cancel. | +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | | callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -636,7 +636,13 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. | Name | Readable| Writable| Type | Mandatory| Description | | ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | **WantAgent** object to cancel.| +| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index 7ffb3babc8171c25ffb2e1814e69e150870071e9..1796e369ab3d562eab9cf49815c31c3d53dd26e1 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -85,7 +85,7 @@ let ws = webSocket.createWebSocket(); ## WebSocket -Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#webSocketcreatewebsocket) to create a **WebSocket** object. +Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object. ### connect diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 2070b5438c925d2b97bc0ac4f9321d0879388afa..c4d8d105f13c4214912120eb9fc1659276ba07be 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -147,11 +147,11 @@ Enumerates the WLAN security types. | **Name**| **Default Value**| **Description**| | -------- | -------- | -------- | -| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type | -| WIFI_SEC_TYPE_OPEN | 1 | Open security type | -| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP) | -| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK) | -| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE) | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP)| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK)| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE)| ## wifi.addUntrustedConfig7+ @@ -182,11 +182,11 @@ Represents the WLAN configuration. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| | preSharedKey | string | Read only| Private key of the hotspot.| | isHiddenSsid | boolean | Read only| Whether to hide the network.| -| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type. | +| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type| ## wifi.addUntrustedConfig7+ @@ -335,7 +335,7 @@ Represents the WLAN connection information. | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| +| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| | rssi | number | Read only| Signal strength of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN AP.| @@ -443,13 +443,13 @@ Represents IP information. | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address. | -| gateway | number | Read only| Gateway. | -| netmask | number | Read only| Subnet mask. | -| primaryDns | number | Read only| IP address of the preferred DNS server. | -| secondDns | number | Read only| IP address of the alternate DNS server. | -| serverIp | number | Read only| IP address of the DHCP server. | -| leaseDuration | number | Read only| Lease duration of the IP address. | +| ipAddress | number | Read only| IP address| +| gateway | number | Read only| Gateway| +| netmask | number | Read only| Subnet mask| +| primaryDns | number | Read only| IP address of the preferred DNS server| +| secondDns | number | Read only| IP address of the alternate DNS server| +| serverIp | number | Read only| IP address of the DHCP server| +| leaseDuration | number | Read only| Lease duration of the IP address| ## wifi.getCountryCode7+ @@ -589,7 +589,7 @@ Represents the P2P device information. | deviceAddress | string | Read only| MAC address of the device.| | primaryDeviceType | string | Read only| Type of the primary device.| | deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| groupCapabilities | number | Read only| Group capabilities.| ## P2pDeviceStatus8+ @@ -1046,7 +1046,7 @@ Registers the hotspot state change events. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.AP + SystemCapability.Communication.WiFi.AP.Core - Parameters | **Name**| **Type**| **Mandatory**| **Description**| @@ -1073,7 +1073,7 @@ Unregisters the hotspot state change events. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.AP + SystemCapability.Communication.WiFi.AP.Core - Parameters | **Name**| **Type**| **Mandatory**| **Description**| @@ -1239,7 +1239,7 @@ Unregisters the P2P peer device state change events. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| - | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the P2P peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index d3b1c26cd6eddc26f04dd3a5dc64c885f96ca9ca..2e2e9394b2a4361fa8adad332c459d4ff33a4e4d 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,7 @@ # WLAN > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -21,7 +21,7 @@ Enables the WLAN hotspot. ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | **Type**| **Description**| @@ -39,7 +39,7 @@ Disables the WLAN hotspot. ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | **Type**| **Description**| @@ -57,7 +57,7 @@ Obtains the supported power models. The method uses a promise to return the resu ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | Type| Description| @@ -86,7 +86,7 @@ Obtains the supported power models. The method uses an asynchronous callback to ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| @@ -104,7 +104,7 @@ Obtains the power model. The method uses a promise to return the result. ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Return value | Type| Description| @@ -122,7 +122,7 @@ Obtains the power model. The method uses an asynchronous callback to return the ohos.permission.GET_WIFI_INFO - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| @@ -140,7 +140,7 @@ setPowerModel(model: PowerModel) : boolean; ohos.permission.MANAGE_WIFI_HOTSPOT_EXT - System capability: - SystemCapability.Communication.WiFi.HotspotExt + SystemCapability.Communication.WiFi.AP.Extension - Parameters | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index c3ec8f7fb3b13c935a4d3dc23f4f9cf8b96dfa12..c8ae2e39fdcd5ef9abcb9062c2abf70315302df8 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -160,12 +160,14 @@ Describes the color gamut mode. | DEFAULT | 0 | Default color gamut mode.| | WIDE_GAMUT | 1 | Wide color gamut mode. | -## window.create7 +## window.create7+ create(id: string, type: WindowType, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. +This API is discarded since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. + **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters @@ -191,12 +193,14 @@ Creates a subwindow. This API uses an asynchronous callback to return the result }); ``` -## window.create7 +## window.create7+ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. +This API is discarded since API version 8. You are advised to use [window.create8+](#windowcreate8) instead. + **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters @@ -229,18 +233,18 @@ Creates a subwindow. This API uses a promise to return the result. create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a system window when the context is [ServiceExtensionContext](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-service-extension-context.md). This API uses an asynchronous callback to return the result. +Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context, which is the base class of **ServiceExtensionContext**.| - | id | string | Yes | Window ID. | - | type | [WindowType](#windowtype) | Yes | Window type. | - | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the system window created. | + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------- | ---- | ---------------------- | + | ctx | [Context](js-apis-service-extension-context.md) | Yes | Current application context. | + | id | string | Yes | Window ID. | + | type | [WindowType](#windowtype) | Yes | Window type. | + | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the system window created.| - Example @@ -261,17 +265,17 @@ Creates a system window when the context is [ServiceExtensionContext](https://gi create(ctx: Context, id: string, type: WindowType): Promise<Window> -Creates a system window when the context is [ServiceExtensionContext](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-service-extension-context.md). This API uses a promise to return the result. +Creates a system window when the context is [ServiceExtensionContext](js-apis-service-extension-context.md). This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core - Parameters - | Name| Type | Mandatory| Description | - | ------ | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context, which is the base class of **ServiceExtensionContext**.| - | id | string | Yes | Window ID. | - | type | [WindowType](#windowtype) | Yes | Window type. | + | Name| Type | Mandatory| Description | + | ------ | ----------------------------------------------- | ---- | -------------------- | + | ctx | [Context](js-apis-service-extension-context.md) | Yes | Current application context.| + | id | string | Yes | Window ID. | + | type | [WindowType](#windowtype) | Yes | Window type. | - Return value @@ -419,10 +423,10 @@ Obtains the top window of the current application. This API uses an asynchronous - Parameters - | Name | Type | Mandatory| Description | - | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context. | - | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | + | ctx | [Context](js-apis-Context.md) | Yes | Current application context. | + | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | - Example @@ -448,9 +452,9 @@ Obtains the top window of the current application. This API uses a promise to re - Parameters - | Name| Type | Mandatory| Description | - | ------ | ------------------------------------------------------------ | ---- | -------------------- | - | ctx | [Context](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-Context.md) | Yes | Current application context.| + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ------------------------------------------------------------ | + | ctx | [Context](js-apis-Context.md) | Yes | Current application context. | - Return value @@ -523,7 +527,7 @@ This is a system API and cannot be called by third-party applications. ## Window -In the following API examples, you must use [getTopWindow()](#window-gettopwindow), [create()](#window-create), or [find()](#window-find) to obtain a **Window** instance and then call a method in this instance. +In the following API examples, you must use [getTopWindow()](#window-gettopwindow), [create()](#windowcreate7), or [find()](#window-find) to obtain a **Window** instance and then call a method in this instance. ### hide7+ diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index b0c4df2c8331baeebbe24c47df87e5ce70abf275..65ad4b643700e21017f06608e538419bcdbdb55d 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -329,6 +329,7 @@ that.parse(options); Defines the XML parsing options. + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.| @@ -337,7 +338,6 @@ Defines the XML parsing options. | attributeValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **attributeValue**.| | tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=> boolean | No| Callback used to return **tokenValue**.| - ## ParseInfo Provides APIs to manage the parsed XML information. diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 0a6cd0200e8e87cfcebbf473fb343922314d89de..f1435417e60cc03f23ec9ef79166256000a1c0d8 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -3,7 +3,11 @@ ## Constraints None ## Modules to Import -import zlib from '@ohos.zlib' + +```javascript +import zlib from '@ohos.zlib'; +``` + ## zlib.zipFile zipFile(inFile:string, outFile:string, options: Options): Promise; Zips a file. This API uses a promise to return the result. @@ -121,7 +125,7 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ## options -| Name | | +| Name | Description | | --------------------------- | ------------------------------------------------------------ | | level?: CompressLeve | See [zip.CompressLevel](#zip.CompressLevel).| | memLevel?: MemLevel | See [zip.MemLevel](#zip.MemLevel) | @@ -129,8 +133,9 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { ## zip.MemLevel -| MEM_LEVEL_MIN | Minimum memory used by the **zip** API during compression.| +| Name | Description | | ----------------- | -------------------------------- | +| MEM_LEVEL_MIN | Minimum memory used by the **zip** API during compression.| | MEM_LEVEL_MAX | Maximum memory used by the **zip** API during compression.| | MEM_LEVEL_DEFAULT | Default memory used by the **zip** API during compression.| @@ -150,7 +155,7 @@ zlib.unzipFile(inFile, outFile, options).then((data) => { | COMPRESS_STRATEGY_DEFAULT_STRATEGY : 0 | Default compression strategy. | | COMPRESS_STRATEGY_FILTERED : 1 | Filtered compression strategy.| | COMPRESS_STRATEGY_HUFFMAN_ONLY : 2 | Huffman coding compression strategy. | -| OMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | +| COMPRESS_STRATEGY_RLE : 3 | RLE compression strategy. | | COMPRESS_STRATEGY_FIXED : 4 | Fixed compression strategy. | ## zip.ErrorCode diff --git a/en/application-dev/reference/arkui-js/js-components-basic-web.md b/en/application-dev/reference/arkui-js/js-components-basic-web.md index 403162b023a9ea4788559e5f96812ce9a5f785ea..7130a68b89c88a8e02cc9872a0eaa29d17807105 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-web.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-web.md @@ -3,6 +3,9 @@ The **\** component displays web page content. >![](../../public_sys-resources/icon-note.gif) **NOTE** > This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +## Required Permissions +ohos.permission.INTERNET, required only for accessing online web pages. + ## Constraints The **\** component does not follow the transition animation. A page allows only one **\** component. @@ -44,7 +47,7 @@ The following methods are supported. ``` ``` - +// xxx.js export default { reloadWeb() { this.$element('web').reload() diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.gif new file mode 100644 index 0000000000000000000000000000000000000000..23a03cf07feddcb9866e7ab141c212ebf01bf8b2 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374661.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374661.png new file mode 100644 index 0000000000000000000000000000000000000000..438d698967ec582748d39118ad509743c131aa3c Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374661.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md index f14fcd3c6df29523f7fe798de697ca69a04bbdd9..d8c994e636c06ad43593963892bd020534747456 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-datepicker.md @@ -48,7 +48,7 @@ Creates a date picker in the given date range. | Name| Type| Description| | -------- | -------- | -------- | | year | number | Year of the selected date.| -| month | number | Month of the selected date.| +| month | number | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and the value **11** indicates December. | | day | number | Day of the selected date.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md index 73793a0f011b51fdb410e346c49b9570f4c25368..eaec942aac1e53c0bb6e23988bdb55eba6e29a31 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md @@ -29,11 +29,11 @@ Creates a component that can automatically display the navigation bar, title, an | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| title | string \| [Custom Builder](../../ui/ts-types.md) | - | Page title. | +| title | string \| [CustomBuilder](../../ui/ts-types.md)8+ | - | Page title. | | subtitle | string | - | Subtitle of the page. | -| menus | Array<NavigationMenuItem> \| [Custom Builder](../../ui/ts-types.md) | - | Menu in the upper right corner of the page. | +| menus | Array<NavigationMenuItem> \| [CustomBuilder](../../ui/ts-types.md)8+ | - | Menu in the upper right corner of the page. | | titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. | -| toolBar | {
items:[
Object
] }
\| [Custom Builder](../../ui/ts-types.md) | - | Content of the toolbar.
**items**: all items on the toolbar. | +| toolBar | {
items:[
Object
] }
\| [CustomBuilder](../../ui/ts-types.md)8+ | - | Content of the toolbar.
**items**: all items on the toolbar. | | hideToolBar | boolean | false | Whether to hide the toolbar.
**true**: Hide the toolbar.
**false**: Show the toolbar. | | hideTitleBar | boolean | false | Whether to hide the title bar. | | hideBackButton | boolean | false | Whether to hide the back button. | @@ -67,7 +67,7 @@ Creates a component that can automatically display the navigation bar, title, an | Name | Description | | -------- | -------- | -| onTitleModeChanged(callback: (titleMode: NavigationTitleMode) => void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. | +| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. | ## Example @@ -140,7 +140,7 @@ struct NavigationExample { .titleMode(NavigationTitleMode.Free) .hideTitleBar(false) .hideBackButton(false) - .onTitleModeChanged((titleModel: NavigationTitleMode) => { + .onTitleModeChange((titleModel: NavigationTitleMode) => { console.log('titleMode') }) .toolBar({ items: [ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 76f1ec8a496d8b31e4c7df7498971c3460987edc..d5d79e4e4fbc004715cac5dd92fce24f5a7f9b6d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -22,7 +22,7 @@ RichText\(content:string\) | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | | content | string | Yes| - | String in HTML format.| - + ## Events @@ -41,8 +41,8 @@ RichText\(content:string\) | \
| Inserts a newline character.| \

This is a paragraph\
This is a new paragraph\

| | \
| Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \

This is a paragraph\

\
\

This is a paragraph\

| | \
\
| Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \
\

This is the heading in a div element\

\
| -| \\ | Displays text in italic style.| \

\This is in italic style\\

| -| \\ | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \ tag where it could be confused with a hyperlink.| \

This is an underlined paragraph\

| +| \\ | Displays text in italic style.| \This is in italic style\ | +| \\ | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \ tag where it could be confused with a hyperlink.| \

\This is an underlined paragraph\\

| | \ | Used to embed CSS within an HTML document.| \ | | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \

This is a heading\

\

This is a paragraph\

| | \ | Used to embed or reference a client-side script, such as JavaScript.| \ | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md b/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md index eac2cce6037bc2c7608f0ef3d3c84fc2c81be5e5..f07fde18fa2eab1eaec4c4354dfda5eb316ca7be 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-scrollbar.md @@ -20,9 +20,9 @@ This component can contain a single child component. ## APIs -ScrollBar(value: ScrollBarOption) +ScrollBar(value: ScrollBarOptions) -- ScrollBarOption parameters +- ScrollBarOptions parameters | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | | scroller | [Scroller](ts-container-scroll.md#scroller) | Yes | - | Scroller, which can be bound to and control scrollable components. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md index 4a3936bd7cf2d65558e5c5433b4c57150c6f3000..fbd02e43d85081fbc64ed53d7987e86bcb3d053a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-search.md @@ -31,7 +31,7 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | | searchButton | string | –| Text on the search button located next to the search text box. By default, there is no search button.| -| placeholderColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Placeholder text color.| +| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color.| | placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style.| | textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md index 25d73234a372a9e13f9a693e2e834e45d6bf9cda..4699fe90c574530e27774d811e4329da363e6cd0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md @@ -20,8 +20,8 @@ Select(options: Array) | Name| Type| Mandatory| Default Value| Description| | ------ | ----------------------------------------------- | ---- | ------ | -------------- | - | value | [ResourceStr](../../ui/ts-types.md#ResourceStr) | Yes| - | Value of an option in the drop-down list box.| - | icon | [ResourceStr](../../ui/ts-types.md#ResourceStr) | No| - | Icon of an option in the drop-down list box.| + | value | [ResourceStr](../../ui/ts-types.md) | Yes| - | Value of an option in the drop-down list box.| + | icon | [ResourceStr](../../ui/ts-types.md) | No| - | Icon of an option in the drop-down list box.| ## Attributes @@ -29,20 +29,20 @@ Select(options: Array) | ----------------------- | --------------------------------------------------- | ------ | ----------------------------------------------- | | selected | number | - | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.| | value | string | - | Text of the drop-down button.| -| font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.| -| fontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the drop-down button.| -| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of the selected option in the drop-down list box.| -| selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box.| -| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of the selected option in the drop-down list box.| -| optionBgColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Background color of an option in the drop-down list box.| -| optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box.| -| optionFontColor | [ResourceColor](../../ui/ts-types.md#ResourceColor) | - | Text color of an option in the drop-down list box.| +| font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.| +| fontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the drop-down button.| +| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of the selected option in the drop-down list box.| +| selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box.| +| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the selected option in the drop-down list box.| +| optionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of an option in the drop-down list box.| +| optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box.| +| optionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of an option in the drop-down list box.| ## Events | Name| Description| | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onSelected(callback: (index: number, value?:string) => void)| Invoked when an option in the drop-down list box is selected. **index** indicates the index of the selected option. **value** indicates the value of the selected option.| +| onSelect(callback: (index: number, value?:string) => void) | Invoked when an option in the drop-down list box is selected. **index** indicates the index of the selected option. **value** indicates the value of the selected option.| ## Example @@ -61,7 +61,7 @@ struct SliderExample { .font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal }) .selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal }) .optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal }) - .onSelected((index:number)=>{ + .onSelecte((index:number)=>{ console.info("Select:" + index) }) } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index 1e4c9f90e5815ec2ee326eac5ae35fbc68efc0a9..9acf78b9759c113a654d03940f299b5df1adc290 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -31,7 +31,7 @@ TextArea(value?:{placeholder?: string controller?: TextAreaController}) ## Attributes -In addition to [universal attributes](ts-universal-attributes.md), the following attributes are supported. +In addition to [universal attributes](ts-universal-attributes-index.md), the following attributes are supported. | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | @@ -49,15 +49,6 @@ In addition to [universal attributes](ts-universal-attributes.md), the following | End | Align the tail horizontally. | -### TextAreaController8+ - -Defines the controller for controlling the **<TextArea>** component. - -| Name | Description | -| -------- | -------- | -| caretPosition(value: number): void | Position of the input cursor.
**value**: indicates the length from the start of the string to the position where the input cursor is located. | - - ## Events | Name | Description | @@ -67,6 +58,28 @@ Defines the controller for controlling the **<TextArea>** component. | onCut8+(callback:(value: string) => void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be cut. | | onPaste8+(callback:(value: string) => void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be pasted. | +## TextAreaController8+ + +Defines the controller for controlling the **<TextArea>** component. + +### Objects to Import + +``` +controller: TextAreaController = new TextAreaController() + +``` + +### caretPosition8+ + +caretPosition(value: number): void + +Sets the position of the caret. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | ----- | ------ | ---- | ---- | ------------------- | + | value | number | Yes | - | Length from the start of the string to the position where the input cursor is located. | + ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md index 6f23dd45ae12120f7dcec85d26d16383e2b464ab..32e8897dfc8623d7167c4c3294d2efd5e2619601 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -18,32 +18,46 @@ TextClock(options?: {timeZoneOffset?: number, contorller?: TextClockController}) - Parameters - | Name| Type| Mandatory| Default Value| Description| + | Name | Type| Mandatory| Default Value | Description | | -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ | - | timeZoneOffset | number | No| Time zone offset| Sets the time zone offset. The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8. For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region.| + | timeZoneOffset | number | No | Time zone offset| Sets the time zone offset. The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8. For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region.| | contorller | [TextClockContorller](#TextClockController) | No| null | Binds a controller to control the status of the **** component.| ## Attributes -| Name| Type| Default Value| Description| +| Name | Type| Default Value | Description | | ------ | -------- | -------- | ------------------------------------------------------------ | | format | string | 'hhmmss' | Time format, for example, **yyyy/mm/dd** or **yyyy-mm-dd**. Supported time format strings:
  • yyyy (year)
  • mm (two-letter abbreviated month name)
  • mmm (three-letter abbreviated month name)
  • mmmm (full month name)
  • dd (two-letter abbreviated day of the week)
  • ddd (three-letter abbreviated day of the week)
  • dddd (full day of the week)
  • HH (24-hour format)
  • hh (12-hour format)
  • MM/mm (minute)
  • SS/ss (second)
| +## Events + +| Name | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| onDateChange(event: (value: number) => void) | Triggered when the time changes in seconds at minimum.
**value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.| + ## TextClockController Controller of the **** component, which can be bound to the component for status control. -| API| Description| -| -------------------------------------------- | ------------------------------------------------------------ | -| start() | Starts the **** component.| -| stop() | Stops the **** component.| +### Objects to Import +``` +controller: TextClockController = new TextClockController() -## Events +``` + +### start + +start() + +Starts the **** component. + +### stop + +stop() + +Stops the **** component. -| Name| Description| -| -------------------------------------------- | ------------------------------------------------------------ | -| onDateChange(event: (value: number) => void) | Triggered when the time changes in seconds at minimum.
value: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 369fe964a4861711c0862a40f9a17b84a05492c2..b24dec295a1264222075a3c4cc51216bc8373715 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -31,7 +31,7 @@ TextInput(value?:{placeholder?: string controller?: TextInputController}) ## Attributes -In addition to [universal attributes](ts-universal-attributes.md), the following attributes are supported. +In addition to [universal attributes](ts-universal-attributes-index.md), the following attributes are supported. | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | @@ -96,7 +96,8 @@ Sets the cursor in a specified position. | -------- | -------- | | onChange(value: string) => void | Triggered when the input changes. | | onSubmit(callback: (enterKey: EnterKeyType) => void) | Triggered when the Enter key on the physical or soft keyboard is pressed. | -| onEditChanged(callback: (isEditing: boolean) => void) | Triggered when the input status changes. | +| onEditChanged(callback: (isEditing: boolean) => void)(deprecated) | Triggered when the input status changes. | +| onEditChange(callback: (isEditing: boolean) => void) 8+ | Triggered when the input status changes. | | onCopy8+(callback:(value: string) => void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be copied. | | onCut8+(callback:(value: string) => void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be cut. | | onPaste8+(callback:(value: string) => void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
**value**: text to be pasted. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md b/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md index 0fef4104bbc778aaf8e7d2350d53d653d7145581..9664340b21efcc4e5784f2a32cc84e1023a98843 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-texttimer.md @@ -23,36 +23,54 @@ None TextTimer(options: { isCountDown?: boolean, count?: number, controller?: TextTimerController }) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | isCountDown | boolean | No | false | Whether to count down. | - | count | number | No | 60000 | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.
- If the value of **count** is less than or equal to 0, the default value is used.
- If the value of **count** is greater than 0, it is used. | - | controller | [TextTimerController](#texttimercontroller) | No | null | **<TextTimer>** controller. | + | isCountDown | boolean | No | false | Whether to count down. | + | count | number | No | 60000 | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.
- If the value of **count** is less than or equal to 0, the default value is used.
- If the value of **count** is greater than 0, it is used. | + | controller | [TextTimerController](#texttimercontroller) | No | null | **<TextTimer>** controller. | +## Attributes -### TextTimerController +| Name | Type | Default Value | Description | +| -------- | -------- | -------- | -------- | +| format | string | 'hh:mm:ss.ms' | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**. | -Defines the controller for controlling the **<TextTimer>** component. - | Name | Description | +## Events + +| Name | Description | | -------- | -------- | -| start() | Starts the timer. | -| pause() | Pauses the timer. | -| reset() | Resets the timer. | +| onTimer(callback: (utc: number, elapsedTime: number) => void) | Triggered when the time text changes.
**utc**: currently displayed time, in milliseconds.
**elapsedTime**: elapsed time of the timer, in milliseconds. | -## Attributes +## TextTimerController - | Name | Type | Default Value | Description | -| -------- | -------- | -------- | -------- | -| format | string | 'hh:mm:ss.ms' | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**. | +Defines the controller for controlling the **<TextTimer>** component. +### Objects to Import -## Events +``` +textTimerController: TextTimerController = new TextTimerController() - | Name | Description | -| -------- | -------- | -| onTimer(callback: (utc: number, elapsedTime: number) => void) | Triggered when the time text changes.
**utc**: currently displayed time, in milliseconds.
**elapsedTime**: elapsed time of the timer, in milliseconds. | +``` + +### start + +start() + +Starts the timer. + +### pause + +pause() + +Pauses the timer. + +### reset + +reset() + +Resets the timer. ## Example @@ -62,12 +80,12 @@ Defines the controller for controlling the **<TextTimer>** component. @Entry @Component struct TextTimerExample { - myTimerController: TextTimerController = new TextTimerController() + textTimerController: TextTimerController = new TextTimerController() @State format: string = 'hh:mm:ss.ms' build() { Column() { - TextTimer({controller: this.myTimerController}) + TextTimer({controller: this.textTimerController}) .format(this.format) .fontColor(Color.Black) .fontSize(this.textSize) @@ -76,13 +94,13 @@ struct TextTimerExample { }) Row() { Button("start").onClick(() => { - this.myTimerController.start(); + this.textTimerController.start(); }); Button("pause").onClick(() => { - this.myTimerController.pause(); + this.textTimerController.pause(); }); Button("reset").onClick(() => { - this.myTimerController.reset(); + this.textTimerController.reset(); }); } } diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md index 78911b09c70cb2d6218d6180a2675d9616294462..7857f66342105d3ddbfb15cd6f4c5f33e32cd546 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-longpressgesture.md @@ -15,25 +15,25 @@ None LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number }) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | - | repeat | boolean | No | false | Whether to continuously trigger the event callback. | - | duration | number | No | 500 | Minimum hold-down time, in ms. | + | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | + | repeat | boolean | No | false | Whether to continuously trigger the event callback. | + | duration | number | No | 500 | Minimum hold-down time, in ms. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onAction((event?: LongPressGestureEvent) => void) | Callback invoked when a long press gesture is recognized. | -| onActionEnd((event?: LongPressGestureEvent) => void) | Callback invoked when the finger used for a long press gesture is lift. | -| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized. | +| onAction((event?: GestureEvent) => void) | Callback invoked when a long press gesture is recognized. | +| onActionEnd((event?: GestureEvent) => void) | Callback invoked when the finger used for a long press gesture is lift. | +| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized. | -- LongPressGestureEvent8+ attributes - | Name | Type | Description | +- GestureEvent attributes related to the long press gesture + | Name | Type | Description | | -------- | -------- | -------- | - | repeat | boolean | Whether the event is repeated. | + | repeat | boolean | Whether the event is repeated. | ## Example @@ -53,7 +53,7 @@ struct LongPressGestureExample { .gesture( LongPressGesture({ repeat: true }) // Repeatedly triggered when the long press gesture exists. - .onAction((event: LongPressGestureEvent) => { + .onAction((event: GestureEvent) => { if (event.repeat) { this.count++ } }) // Triggered when the long press gesture ends. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md index 86ec87b6d1f59620e9b26d761b0f08b4677fb159..76c51b674b80f17de07c1d662893d0efa270cd4d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-pangesture.md @@ -12,59 +12,59 @@ None ## APIs -PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOption](#pangestureoption)) +PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOption](#pangestureoptions)) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | - | direction | PanDirection | No | All | Slide direction. The enumerated value supports the AND (&) and OR (\|) operations. | - | distance | number | No | 5.0 | Minimum slide recognition distance, in vp. | + | fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. | + | direction | PanDirection | No | All | Slide direction. The enumerated value supports the AND (&) and OR (\|) operations. | + | distance | number | No | 5.0 | Minimum slide recognition distance, in vp. | - PanDirection enums - | Name | Description | + | Name | Description | | -------- | -------- | - | All | All directions. | - | Horizontal | Horizontal slide. | - | Vertical | Vertical slide. | - | Left | Slide to the left. | - | Right | Slide to the right. | - | Up | Slide up. | - | Down | Slide down. | - | None | Slide disabled. | + | All | All directions. | + | Horizontal | Horizontal slide. | + | Vertical | Vertical slide. | + | Left | Slide to the left. | + | Right | Slide to the right. | + | Up | Slide up. | + | Down | Slide down. | + | None | Slide disabled. | -### PanGestureOption +### PanGestureOptions -The attributes of the slide gesture recognizer can be dynamically modified using the **PanGestureOption** AP. This avoids modifying attributes through status variables, which will cause the UI to be refreshed. +The attributes of the slide gesture recognizer can be dynamically modified using the **PanGestureOptions** AP. This avoids modifying attributes through status variables, which will cause the UI to be refreshed. -PanGestureOption(options?: { fingers?: number, direction?: PanDirection, distance?: number }) +PanGestureOptions(options?: { fingers?: number, direction?: PanDirection, distance?: number }) - Parameters For details, see **PanGesture**. - APIs - | Name | Description | + | Name | Description | | -------- | -------- | - | setDirection(value: PanDirection) | Sets the direction. | - | setDistance(value: number) | Sets the distance. | - | setFingers(value: number) | Sets the number of fingers. | + | setDirection(value: PanDirection) | Sets the direction. | + | setDistance(value: number) | Sets the distance. | + | setFingers(value: number) | Sets the number of fingers. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onActionStart(callback: (event?: PanGestureEvent) => void) | Callback for the pan gestures reorganization event. | -| onActionUpdate(callback: (event?: PanGestureEvent) => void) | Callback invoked when a pan gesture is recognized. | -| onActionEnd(callback: (event?: PanGestureEvent) => void) | Callback invoked when the finger used for a pan gesture is lift. | -| onActionCancel(callback: () => void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized. | +| onActionStart(callback: (event?: GestureEvent) => void) | Callback for the pan gestures reorganization event. | +| onActionUpdate(callback: (event?: GestureEvent) => void) | Callback invoked when a pan gesture is recognized. | +| onActionEnd(callback: (event?: GestureEvent) => void) | Callback invoked when the finger used for a pan gesture is lift. | +| onActionCancel(callback: () => void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized. | -- PanGestureEvent8+ attributes - | Name | Type | Description | +- GestureEvent attributes related to the pan gesture + | Name | Type | Description | | -------- | -------- | -------- | - | offsetX | number | Offset of the gesture event, in vp. | - | offsetY | number | Offset of the gesture event, in vp. | + | offsetX | number | Offset of the gesture event, in vp. | + | offsetY | number | Offset of the gesture event, in vp. | ## Example @@ -85,10 +85,10 @@ struct PanGestureExample { .translate({ x: this.offsetX, y: this.offsetY, z: 5 }) .gesture( PanGesture({}) - .onActionStart((event: PanGestureEvent) => { + .onActionStart((event: GestureEvent) => { console.info('Pan start') }) - .onActionUpdate((event: PanGestureEvent) => { + .onActionUpdate((event: GestureEvent) => { this.offsetX = event.offsetX this.offsetY = event.offsetY }) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md index 328feb245f82260fdb593364c8c377659669971e..88e5122a44a112ca8bff3d06386b390b54c7df96 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-pinchgesture.md @@ -15,27 +15,27 @@ None PinchGesture(options?: { fingers?: number, distance?: number }) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. | - | distance | number | No | 3.0 | Minimum recognition distance, in vp. | + | fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. | + | distance | number | No | 3.0 | Minimum recognition distance, in vp. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onActionStart((event?: PinchGestureEvent) => void) | Callback invoked when a pinch gesture is recognized. | -| onActionUpdate((event?: PinchGestureEvent) => void) | Callback invoked during the movement of a pinch gesture. | -| onActionEnd((event?: PinchGestureEvent) => void) | Callback invoked when the finger used for a pinch gesture is lift. | -| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. | +| onActionStart((event?: GestureEvent) => void) | Callback invoked when a pinch gesture is recognized. | +| onActionUpdate((event?: GestureEvent) => void) | Callback invoked during the movement of a pinch gesture. | +| onActionEnd((event?: GestureEvent) => void) | Callback invoked when the finger used for a pinch gesture is lift. | +| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. | -- PinchGestureEvent8+ attributes - | Name | Type | Description | +- GestureEvent attributes related to the pinch gesture + | Name | Type | Description | | -------- | -------- | -------- | - | scale | number | Scale ratio. This attribute is used for the pinch gesture. | - | pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. | - | pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. | + | scale | number | Scale ratio. This attribute is used for the pinch gesture. | + | pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. | + | pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. | ## Example @@ -55,10 +55,10 @@ struct PinchGestureExample { .scale({ x: this.scale, y: this.scale, z: this.scale }) .gesture( PinchGesture() - .onActionStart((event: PinchGestureEvent) => { + .onActionStart((event: GestureEvent) => { console.info('Pinch start') }) - .onActionUpdate((event: PinchGestureEvent) => { + .onActionUpdate((event: GestureEvent) => { this.scale = event.scale }) .onActionEnd(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md index 16eb5921d688a188d76147f92439a3e120c3aa61..cd4d73e60f9d2b4a43402f379ec4f8e456ae7fd5 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-rotationgesture.md @@ -15,25 +15,25 @@ None RotationGesture(options?: { fingers?: number, angle?: number }) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. | - | angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. | + | fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. | + | angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onActionStart((event?: RotationGestureEvent) => void) | Callback invoked when a rotation gesture is recognized. | -| onActionUpdate((event?: RotationGestureEvent) => void) | Callback invoked during the movement of the rotation gesture. | -| onActionEnd((event?: RotationGestureEvent) => void) | Callback invoked when the finger used for the rotation gesture is lift. | -| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after the rotation gesture is recognized. | +| onActionStart((event?: GestureEvent) => void) | Callback invoked when a rotation gesture is recognized. | +| onActionUpdate((event?: GestureEvent) => void) | Callback invoked during the movement of the rotation gesture. | +| onActionEnd((event?: GestureEvent) => void) | Callback invoked when the finger used for the rotation gesture is lift. | +| onActionCancel(event: () => void) | Callback invoked when a tap cancellation event is received after the rotation gesture is recognized. | -- RotationGestureEvent8+ attributes - | Name | Type | Description | +- GestureEvent attributes related to the rotation gesture + | Name | Type | Description | | -------- | -------- | -------- | - | angle | number | Rotation angle. | + | angle | number | Rotation angle. | ## Example @@ -53,10 +53,10 @@ struct RotationGestureExample { .margin(80).rotate({ x:1, y:2, z:3, angle: this.angle }) .gesture( RotationGesture() - .onActionStart((event: RotationGestureEvent) => { + .onActionStart((event: GestureEvent) => { console.log('Rotation start') }) - .onActionUpdate((event: RotationGestureEvent) => { + .onActionUpdate((event: GestureEvent) => { this.angle = event.angle }) .onActionEnd(() => { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md index 4a3b138a0e5652bddebcff46479d43773fc1354e..7e6ec61e15dc004d7c9a4a26211f5f6e22dbc4de 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md @@ -15,33 +15,34 @@ None SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number }) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | fingers | number | No | 1 | Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10. | - | direction | SwipeDirection | No | SwipeDirection.All | Swipe direction. | - | speed | number | No | 100 | Minimum speed of the swipe gesture (100 vp/s). | + | fingers | number | No | 1 | Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10. | + | direction | SwipeDirection | No | SwipeDirection.All | Swipe direction. | + | speed | number | No | 100 | Minimum speed of the swipe gesture (100 vp/s). | - SwipeDirection enums - | Name | Description | + | Name | Description | | -------- | -------- | - | All | All directions. | - | Horizontal | Horizontal direction. | - | Vertical | Vertical direction. | + | All | All directions. | + | Horizontal | Horizontal direction. | + | Vertical | Vertical direction. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onAction(callback:(event?: SwipeGestureEvent) => void) | Callback invoked when a swipe gesture is recognized. | +| onAction(callback:(event?: GestureEvent) => void) | Callback invoked when a swipe gesture is recognized. | -- SwipeGestureEvent attributes - | Name | Type | Description | +- GestureEvent attributes related to the swipe gesture + | Name | Type | Description | | -------- | -------- | -------- | - | angle | number | Angle of the swipe gesture. | - | speed | number | Speed of the swipe gesture. | + | angle | number | Angle of the swipe gesture.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Angle calculation method: After the swipe gesture is identified, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction. Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. | + | speed | number | Speed of the swipe gesture. | +![en-us_image_0000001231374559](figures/en-us_image_0000001231374661.png) ## Example @@ -64,7 +65,7 @@ struct SwipeGestureExample { .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) .gesture( SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical}) - .onAction((event: SwipeGestureEvent) => { + .onAction((event: GestureEvent) => { this.speed = event.speed this.rotateAngle = event.angle }) @@ -73,4 +74,4 @@ struct SwipeGestureExample { } ``` -![en-us_image_0000001257138365](figures/en-us_image_0000001257138365.gif) +![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index 40adadc6097c2e27f33c7f245661cf070257b096..be29bb3bdb125c821da0748c8163f7a09e2920fa 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -30,16 +30,16 @@ Canvas(context: CanvasRenderingContext2D) ## Attributes -[Universal attributes](ts-universal-attributes-size.md) are supported. +[Universal attributes]( ts-universal-attributes-index.md) are supported. ## Events -In addition to [universal events](ts-universal-events-click.md), the following events are supported. +In addition to [universal events](ts-universal-events-index.md), the following events are supported. - | Name | Parameter | Description | +| Name | Parameter | Description | | -------- | -------- | -------- | -| onReady(callback: () => void) | None | Triggered when . | +| onReady(callback: () => void) | None | Triggered when . | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index 8d676b0de93488e61d5fe09388d758115c6143e3..6af901e21636c03f1189766ea5296217bf72cc91 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -12,7 +12,7 @@ None ## Modules to Import - + ``` import lottie from 'lottie-ohos-ets' ``` @@ -30,15 +30,15 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea Loads an animation. Before calling this method, declare the **Animator('__lottie_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**. | - | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance. | - | render | string | Yes | Rendering type. The value can only be **"canvas"**. | - | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | - | autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | - | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | - | initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | + | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**. | + | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance. | + | render | string | Yes | Rendering type. The value can only be **"canvas"**. | + | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | + | autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. | + | name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. | + | initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. | ## lottie.destroy @@ -48,12 +48,12 @@ destroy(name: string): void Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed. | + | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed. | - Example - + ``` import lottie from 'lottie-web' @@ -128,12 +128,12 @@ play(name: string): void Plays a specified animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played. | + | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played. | - Example - + ``` lottie.play(this.animateName) ``` @@ -146,12 +146,12 @@ pause(name: string): void Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | + | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | - Example - + ``` lottie.pause(this.animateName) ``` @@ -164,12 +164,12 @@ togglePause(name: string): void Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | + | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | - Example - + ``` lottie.togglePause(this.animateName) ``` @@ -182,12 +182,12 @@ stop(name: string): void Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | + | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused. | - Example - + ``` lottie.stop(this.animateName) ``` @@ -200,13 +200,13 @@ setSpeed(speed: number, name: string): void Sets the playback speed of the specified animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed. | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped. | + | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed. | + | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped. | - Example - + ``` lottie.setSpeed(5, this.animateName) ``` @@ -219,13 +219,13 @@ setDirection(direction: AnimationDirection, name: string): void Sets the direction in which the specified animation plays. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
**AnimationDirection**: 1 \| -1. | - | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set. | + | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
**AnimationDirection**: 1 \| -1. | + | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set. | - Example - + ``` lottie.setDirection(-1, this.animateName) ``` @@ -235,28 +235,28 @@ Sets the direction in which the specified animation plays. Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows: - | Name | Type | Description | +| Name | Type | Description | | -------- | -------- | -------- | -| name | string | Animation name. | -| isLoaded | boolean | Whether the animation is loaded. | -| currentFrame | number | Frame that is being played. The default precision is a floating-point number greater than or equal to 0.0. After **setSubframe(false)** is called, the value is a positive integer without decimal points. | -| currentRawFrame | number | Number of frames that are being played. The precision is a floating point number greater than or equal to 0.0. | -| firstFrame | number | First frame of the animation segment that is being played. | -| totalFrames | number | Total number of frames in the animation segment that is being played. | -| frameRate | number | Frame rate (frame/s). | -| frameMult | number | Frame rate (frame/ms). | -| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | -| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). | -| playCount | number | Number of times the animation plays. | -| isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. | -| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing. | -| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | -| renderer | any | Animation rendering object, which depends on the rendering type. | -| animationID | string | Animation ID. | -| timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**. | -| segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. | -| isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. | -| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | +| name | string | Animation name. | +| isLoaded | boolean | Whether the animation is loaded. | +| currentFrame | number | Frame that is being played. The default precision is a floating-point number greater than or equal to 0.0. After **setSubframe(false)** is called, the value is a positive integer without decimal points. | +| currentRawFrame | number | Number of frames that are being played. The precision is a floating point number greater than or equal to 0.0. | +| firstFrame | number | First frame of the animation segment that is being played. | +| totalFrames | number | Total number of frames in the animation segment that is being played. | +| frameRate | number | Frame rate (frame/s). | +| frameMult | number | Frame rate (frame/ms). | +| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | +| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). | +| playCount | number | Number of times the animation plays. | +| isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. | +| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing. | +| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. | +| renderer | any | Animation rendering object, which depends on the rendering type. | +| animationID | string | Animation ID. | +| timeCompleted | number | Number of frames that are played for an animation sequence. The value is affected by the setting of **AnimationSegment** and is the same as the value of **totalFrames**. | +| segmentPos | number | ID of the current animation segment. The value is a positive integer greater than or equal to 0. | +| isSubframeEnabled | boolean | Whether the precision of **currentFrame** is a floating point number. | +| segments | AnimationSegment \| AnimationSegment[] | Current segment of the animation. | ## AnimationItem.play @@ -266,12 +266,12 @@ play(name?: string): void Plays an animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | No | Name of the target animation. By default, the value is null. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` this.animateItem.play() ``` @@ -284,12 +284,12 @@ destroy(name?: string): void Destroys an animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | No | Name of the target animation. By default, the value is null. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` this.animateItem.destroy() ``` @@ -302,12 +302,12 @@ pause(name?: string): void Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | No | Name of the target animation. By default, the value is null. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` this.animateItem.pause() ``` @@ -320,12 +320,12 @@ togglePause(name?: string): void Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | No | Name of the target animation. By default, the value is null. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` this.animateItem.togglePause() ``` @@ -338,12 +338,12 @@ stop(name?: string): void Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | string | No | Name of the target animation. By default, the value is null. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` this.animateItem.stop() ``` @@ -356,12 +356,12 @@ setSpeed(speed: number): void Sets the playback speed of an animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | + | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. | - Example - + ``` this.animateItem.setSpeed(5); ``` @@ -374,12 +374,12 @@ setDirection(direction: AnimationDirection): void Sets the playback direction of an animation. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
**AnimationDirection**: 1 \| -1. | + | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.
**AnimationDirection**: 1 \| -1. | - Example - + ``` this.animateItem.setDirection(-1) ``` @@ -387,19 +387,19 @@ Sets the playback direction of an animation. ## AnimationItem.goToAndStop -goToAndStop(value: number, isFrame: boolean): void +goToAndStop(value: number, isFrame?: boolean): void Sets the animation to stop at the specified frame or time. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | - | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**. | - | name | string | No | Name of the target animation. By default, the value is null. | + | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. | + | isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` // Set the animation to stop at the specified frame. this.animateItem.goToAndStop(25, true) @@ -410,19 +410,19 @@ Sets the animation to stop at the specified frame or time. ## AnimationItem.goToAndPlay -goToAndPlay(value: number, isFrame: boolean): void +goToAndPlay( value: number, isFrame: boolean, name?: string): void Sets the animation to start from the specified frame or time progress. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | - | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**. | - | name | string | No | Name of the target animation. By default, the value is null. | + | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | + | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**. | + | name | string | No | Name of the target animation. By default, the value is null. | - Example - + ``` // Set the animation to stop at the specified frame. this.animateItem.goToAndPlay(25, true) @@ -438,13 +438,13 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean Sets the animation to play only the specified segment. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle. | - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | + | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.
If all segments in the segment list are played, only the last segment is played in the next cycle. | + | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | - Example - + ``` // Set the animation to play the specified segment. this.animateItem.playSegments([10, 20], false) @@ -460,12 +460,12 @@ resetSegments(forceFlag: boolean): void Resets the settings configured by the **playSegments** method to play all the frames. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | + | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | - Example - + ``` this.animateItem.resetSegments(true) ``` @@ -478,7 +478,7 @@ resize(): void Resizes the animation layout. - Example - + ``` this.animateItem.resize() ``` @@ -491,12 +491,12 @@ setSubframe(useSubFrame: boolean): void Sets the precision of the **currentFrame** attribute to display floating-point numbers. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers. | + | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.
**true**: The **currentFrame** attribute displays floating-point numbers.
**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers. | - Example - + ``` this.animateItem.setSubframe(false) ``` @@ -509,12 +509,12 @@ getDuration(inFrames?: boolean): void Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | inFrames | boolean | No | Whether to obtain the duration or number of frames. **true**: number of frames. **false**: duration, in ms. The default value is **false**. | + | inFrames | boolean | No | Whether to obtain the duration or number of frames. **true**: number of frames. **false**: duration, in ms. The default value is **false**. | - Example - + ``` this.animateItem.getDuration(true) ``` @@ -527,13 +527,13 @@ addEventListener<T = any>(name: AnimationEventName, callback: AnimationEve Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | - | callback | AnimationEventCallback<T> | Yes | Custom callback. | + | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | + | callback | AnimationEventCallback<T> | Yes | Custom callback. | - Example - + ``` private callbackItem: any = function() { console.log("grunt loopComplete") @@ -552,13 +552,13 @@ removeEventListener<T = any>(name: AnimationEventName, callback?: Animatio Removes an event listener. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | - | callback | AnimationEventCallback<T> | Yes | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | + | name | AnimationEventName | Yes | Animation event type. The available options are as follows:
'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images' | + | callback | AnimationEventCallback<T> | Yes | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | - Example - + ``` this.animateItem.removeEventListener('loopComplete', this.animateName) ``` @@ -571,13 +571,13 @@ triggerEvent<T = any>(name: AnimationEventName, args: T): void Directly triggers all configured callbacks of a specified event. - Parameters - | Name | Type | Mandatory | Description | + | Name | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | name | AnimationEventName | Yes | Animation event type. | - | args | any | Yes | Custom callback parameters. | + | name | AnimationEventName | Yes | Animation event type. | + | args | any | Yes | Custom callback parameters. | - Example - + ``` private triggerCallBack: any = function(item) { console.log("trigger loopComplete, name:" + item.name) diff --git a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index 4ac71e31814747edb77ee2ff3409b2c2b88bc1b8..33471a248de86a79f1fb72c2fa3365e7e2b330f8 100644 --- a/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -15,12 +15,12 @@ addPath(path: Object): void Adds a path to this path. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | path | Object | Yes | null | Path to be added to this path. | + | path | Object | Yes | null | Path to be added to this path. | - Example - + ``` @Entry @Component @@ -58,7 +58,7 @@ closePath(): void Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing. - Example - + ``` @Entry @Component @@ -97,13 +97,13 @@ moveTo(x: number, y: number): void Moves the current coordinate point of the path to the target point, without drawing a line during the movement. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes | 0 | X-coordinate of the target point. | - | y | number | Yes | 0 | Y-coordinate of the target point. | + | x | number | Yes | 0 | X-coordinate of the target point. | + | y | number | Yes | 0 | Y-coordinate of the target point. | - Example - + ``` @Entry @Component @@ -142,13 +142,13 @@ lineTo(x: number, y: number): void Draws a straight line from the current point to the target point. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes | 0 | X-coordinate of the target point. | - | y | number | Yes | 0 | Y-coordinate of the target point. | + | x | number | Yes | 0 | X-coordinate of the target point. | + | y | number | Yes | 0 | Y-coordinate of the target point. | - Example - + ``` @Entry @Component @@ -188,17 +188,17 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, Draws a cubic bezier curve on the canvas. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | - | cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | - | cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | - | cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | - | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | - | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | + | cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | + | cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | + | cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | + | cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | + | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | + | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | - Example - + ``` @Entry @Component @@ -234,15 +234,15 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void Draws a quadratic curve on the canvas. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. | - | cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. | - | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | - | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | + | cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. | + | cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. | + | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | + | y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | - Example - + ``` @Entry @Component @@ -274,22 +274,22 @@ Draws a quadratic curve on the canvas. ## arc -arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: number): void +arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void Draws an arc on the canvas. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes | 0 | X-coordinate of the center point of the arc. | - | y | number | Yes | 0 | Y-coordinate of the center point of the arc. | - | radius | number | Yes | 0 | Radius of the arc. | - | startAngle | number | Yes | 0 | Start radian of the arc. | - | endAngle | number | Yes | 0 | End radian of the arc. | - | anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | + | x | number | Yes | 0 | X-coordinate of the center point of the arc. | + | y | number | Yes | 0 | Y-coordinate of the center point of the arc. | + | radius | number | Yes | 0 | Radius of the arc. | + | startAngle | number | Yes | 0 | Start radian of the arc. | + | endAngle | number | Yes | 0 | End radian of the arc. | + | anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | - Example - + ``` @Entry @Component @@ -324,16 +324,16 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void Draws an arc based on the radius and points on the arc. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x1 | number | Yes | 0 | X-coordinate of the first point on the arc. | - | y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. | - | x2 | number | Yes | 0 | X-coordinate of the second point on the arc. | - | y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. | - | radius | number | Yes | 0 | Radius of the arc. | + | x1 | number | Yes | 0 | X-coordinate of the first point on the arc. | + | y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. | + | x2 | number | Yes | 0 | X-coordinate of the second point on the arc. | + | y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. | + | radius | number | Yes | 0 | Radius of the arc. | - Example - + ``` @Entry @Component @@ -369,19 +369,19 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number Draws an ellipse in the specified rectangular region. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes | 0 | X-coordinate of the ellipse center. | - | y | number | Yes | 0 | Y-coordinate of the ellipse center. | - | radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | - | radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | - | rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. | - | startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. | - | endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. | - | anticlockwise | number | No | 0 | Whether to draw the ellipse in the counterclockwise direction. The value **0** means to draw the ellipse in the clockwise direction, and **1** means to draw the ellipse in the counterclockwise direction. This parameter is optional. The default value is **0**. | + | x | number | Yes | 0 | X-coordinate of the ellipse center. | + | y | number | Yes | 0 | Y-coordinate of the ellipse center. | + | radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | + | radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | + | rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. | + | startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. | + | endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. | + | anticlockwise | number | No | 0 | Whether to draw the ellipse in the counterclockwise direction. The value **0** means to draw the ellipse in the clockwise direction, and **1** means to draw the ellipse in the counterclockwise direction. This parameter is optional. The default value is **0**. | - Example - + ``` @Entry @Component @@ -417,15 +417,15 @@ rect(x: number, y: number, width: number, height: number): void Creates a rectangle. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | - | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | - | width | number | Yes | 0 | Width of the rectangle. | - | height | number | Yes | 0 | Height of the rectangle. | + | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | + | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | + | width | number | Yes | 0 | Width of the rectangle. | + | height | number | Yes | 0 | Height of the rectangle. | - Example - + ``` @Entry @Component diff --git a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md index 89610005db9561f3cb52282fd4a97cc414a57d23..ba2b3259ee48b1627a1f100b1e33f496b7b3a974 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-alphabet-indexer.md @@ -23,46 +23,47 @@ None AlphabetIndexer(value: {arrayValue : Array<string>, selected : number}) - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | arrayValue | Array<string> | Yes | - | Array of strings to be displayed in the alphabetic index bar. | - | selected | number | Yes | - | ID of a selected item. | + | arrayValue | Array<string> | Yes | - | Array of strings to be displayed in the alphabetic index bar. | + | selected | number | Yes | - | ID of a selected item. | ## Attributes - | Name | Type | Description | +| Name | Type | Description | | -------- | -------- | -------- | -| selectedColor | Color | Font color of the selected text. | -| popupColor | Color | Font color of the pop-up text. | -| selectedBackgroundColor | Color | Background color of the selected text. | -| popupBackground | Color | Background color of the pop-up text. | -| usingPopup | boolean | Whether to use pop-up text. | -| selectedFont | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Font style of the selected text. | -| popupFont | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Font style of the pop-up text. | -| font | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Default font style of the alphabetic index bar. | -| itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. | -| alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported. The alignment style affects the position of the pop-up window. | +| selectedColor | Color | Font color of the selected text. | +| popupColor | Color | Font color of the pop-up text. | +| selectedBackgroundColor | Color | Background color of the selected text. | +| popupBackground | Color | Background color of the pop-up text. | +| usingPopup | boolean | Whether to use pop-up text. | +| selectedFont | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Font style of the selected text. | +| popupFont | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Font style of the pop-up text. | +| font | {
size?: number,
weight?: FontWeight,
family?: string,
style?: FontStyle
} | Default font style of the alphabetic index bar. | +| itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. | +| alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported. The alignment style affects the position of the pop-up window. | - IndexerAlign enums - | Name | Description | + | Name | Description | | -------- | -------- | - | Left | The pop-up window is displayed on the right of the alphabetic indexer bar. | - | Right | The pop-up window is displayed on the left of the alphabetic indexer bar. | + | Left | The pop-up window is displayed on the right of the alphabetic indexer bar. | + | Right | The pop-up window is displayed on the left of the alphabetic indexer bar. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onSelected(index: number) => void | Callback invoked when an item in the alphabetic indexer bar is selected. | -| onRequestPopupData(callback: (index: number) => Array<string>)8+ | Invoked when a request for displaying content in the index prompt window is sent when an item in the alphabetic indexer bar is selected.
The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling. | -| onPopupSelected(callback: (index: number) => void)8+ | Invoked when an item in the index pop-up window is selected. | +| onSelected(index: number) => void(deprecated) | Invoked when an item in the alphabetic indexer bar is selected. | +| onSelect(index: number) => void8+ | Invoked when an item in the alphabetic indexer bar is selected. | +| onRequestPopupData(callback: (index: number) => Array<string>)8+ | Invoked when a request for displaying content in the index prompt window is sent when an item in the alphabetic indexer bar is selected.
The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling. | +| onPopupSelect(callback: (index: number) => void)8+ | Invoked when an item in the index pop-up window is selected. | ## Example - + ``` @Entry @Component @@ -80,7 +81,7 @@ struct AlphabetIndexerSample { .popupFont({ size: 30, weight: FontWeight.Bolder }) // Font style of the pop-up text .itemSize(28) // Size of each item (square) .alignStyle(IndexerAlign.Left) // Left aligned - .onSelected((index: number) => { + .onSelect((index: number) => { console.info(this.value[index] + 'Selected') // Event indicating that an item is selected }) .margin({ left: 50 }) diff --git a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md index 66689eb6452cf7a71a11d2f242be8d996526728a..04f4a38ccca5fe7f11919dfdd1cbbbb0e5305b80 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -25,9 +25,9 @@ RowSplit() ## Attributes - | Name | Type | Description | +| Name | Type | Description | | -------- | -------- | -------- | -| resizeable | boolean | Whether the divider can be dragged. The default value is **false**. | +| resizeable | boolean | Whether the divider can be dragged. The default value is **false**. | > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > Similar to **<RowSplit>**, the divider of **<RowSplit>** can be dragged to a position that just fully holds a component. @@ -35,14 +35,14 @@ RowSplit() ## Example - + ``` @Entry @Component struct RowSplitExample { build() { Column() { - Text('The secant line can be dragged').fontSize(9).fontColor(0xCCCCCC).width('90%') + Text('The second line can be dragged').fontSize(9).fontColor(0xCCCCCC).width('90%') RowSplit() { Text('1').width('10%').height(100).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) Text('2').width('10%').height(100).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index fe9f455dd4fe3052843fd4f22e76605acd0457f2..076505a2951dac1b2e3a729768f56f8d52692775 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -25,19 +25,19 @@ Scroll(scroller?: Scroller) ## Attributes -| Name | Type | Default Value | Description | +| Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. | -| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. | +| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. | +| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. | | scrollBarColor | Color | - | Color of the scroll bar. | | scrollBarWidth | Length | - | Width of the scrollbar. | - ScrollDirection - | Name | Description | + | Name | Description | | -------- | -------- | - | Horizontal | Only horizontal scrolling is supported. | - | Vertical | Only vertical scrolling is supported. | - | None | Scrolling is disabled. | + | Horizontal | Only horizontal scrolling is supported. | + | Vertical | Only vertical scrolling is supported. | + | None | Scrolling is disabled. | ## Scroller @@ -62,11 +62,11 @@ Scrolls to the specified position. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | xOffset | Length | Yes | - | Horizontal scrolling offset. | - | yOffset | Length | Yes | - | Vertical scrolling offset. | - | animation | {
duration: number,
curve: Curve \|
CubicBezier \|
SpringCurve
} | No | | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve. | + | xOffset | Length | Yes | - | Horizontal scrolling offset. | + | yOffset | Length | Yes | - | Vertical scrolling offset. | + | animation | {
duration: number,
curve: Curve \|
CubicBezier \|
SpringCurve
} | No | | Animation configuration, which includes the following:
- **duration**: scrolling duration.
- **curve**: scrolling curve. | ### scroller.scrollEdge @@ -78,9 +78,9 @@ Scrolls to the edge of the container. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | value | Edge | Yes | - | Edge position to scroll to. | + | value | Edge | Yes | - | Edge position to scroll to. | ### scroller.scrollPage @@ -90,7 +90,7 @@ scrollPage(value: { next: boolean, direction?: Axis }): void Scrolls to the next or previous page. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | | next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and the value **false** means to scroll to the previous page. | @@ -104,9 +104,9 @@ Obtains the scrolling offset. - Return values - | Type | Description | + | Type | Description | | -------- | -------- | - | {
xOffset: number,
yOffset: number
} | **xOffset**: horizontal scrolling offset.
**yOffset**: vertical scrolling offset. | + | {
xOffset: number,
yOffset: number
} | **xOffset**: horizontal scrolling offset.
**yOffset**: vertical scrolling offset. | ### scroller.scrollToIndex @@ -122,18 +122,18 @@ Scrolls to the specified index. - Parameters - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | value | number | Yes | - | Index of the item to be scrolled to in the list. | + | value | number | Yes | - | Index of the item to be scrolled to in the list. | ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onScroll(xOffset: number, yOffset: number) => void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | -| onScrollEdge(side: Edge) => void | Callback for the event of scrolling to the edge. | -| onScrollEnd() => void | Invoked when scrolling stops. | +| onScroll(xOffset: number, yOffset: number) => void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. | +| onScrollEdge(side: Edge) => void | Callback for the event of scrolling to the edge. | +| onScrollEnd() => void | Invoked when scrolling stops. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index 42797131cef70c6f80bc8baa55302732432f2e06..4f797a9f483942a8b4af751730e9ddbedc85899a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -36,15 +36,6 @@ Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsContro | End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container. | -### TabsController - -Defines a tab controller, which is used to control switching of tabs. - -| API | Description | -| -------- | -------- | -| changeIndex(value: number): void | Changes the index of a tab. The value starts from **0**. | - - ## Attributes Touch target configuration is not supported. @@ -71,6 +62,27 @@ Touch target configuration is not supported. | -------- | -------- | | onChange(callback: (index: number) => void) | Event triggered when a tab is switched. | +## TabsController + +Defines a tab controller, which is used to control switching of tabs. +### Objects to Import + +``` +controller: TabsController = new TabsController() + +``` + +### changeIndex + +changeIndex(value: number): void + +Switches to the specified tab. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | - | Index of a tab. The value starts from **0**. | + ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md index f8c65982db423a9dc3eb4a7573b9501e15a1b73d..d3a75465226905a1a9b144f09dffd50d5a7ee0a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-explicit-animation.md +++ b/en/application-dev/reference/arkui-ts/ts-explicit-animation.md @@ -4,28 +4,28 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - | Name | Description | +| Name | Description | | -------- | -------- | -| animateTo(value: [AnimationOption](#animationoption-object), event: ()=> void) : void | Provides a transition animation when the status changes due to the closure code.
**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function. | +| animateTo(value: [AnimationOptions](#animationoptions), event: ()=> void) : void | Provides a transition animation when the status changes due to the closure code.
**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function. | -## AnimationOption Object +## AnimationOptions - Attributes - | Name | Type | Default Value | Description | + | Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | - | duration | number | 1000 | Animation duration, in ms. | - | tempo | number | 1.0 | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation. | - | curve | Curve \| Curves | Linear | Animation curve. | - | delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | - | iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | - | playMode | PlayMode | Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete. | + | duration | number | 1000 | Animation duration, in ms. | + | tempo | number | 1.0 | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation. | + | curve | Curve \| Curves | Linear | Animation curve. | + | delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | + | iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | + | playMode | PlayMode | Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete. | - APIs - | Name | Description | + | Name | Description | | -------- | -------- | - | onFinish() => void | Callback invoked when the animation playback is complete. | + | onFinish() => void | Callback invoked when the animation playback is complete. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index 8e2f943835a48517e45377c0ac81fd6145471bed..461eac8e5042ffc2594879c11fde7d426124a7ba 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -15,9 +15,9 @@ The **<Video>** component does not support any child component. ## APIs -Video(value: VideoOption) +Video(value: VideoOptions) -- VideoOption attributes +- VideoOptions attributes | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | | src | string | No | - | Path of the video source. | @@ -27,13 +27,13 @@ Video(value: VideoOption) - PlaybackSpeed8+ - | Name | Description | + | Name | Description | | -------- | -------- | - | Speed_Forward_0_75_X | 0.75x playback speed. | - | Speed_Forward_1_00_X | 1x playback speed. | - | Speed_Forward_1_25_X | 1.25x playback speed. | - | Speed_Forward_1_75_X | 1.75x playback speed. | - | Speed_Forward_2_00_X | 2x playback speed. | + | Speed_Forward_0_75_X | 0.75x playback speed. | + | Speed_Forward_1_00_X | 1x playback speed. | + | Speed_Forward_1_25_X | 1.25x playback speed. | + | Speed_Forward_1_75_X | 1.75x playback speed. | + | Speed_Forward_2_00_X | 2x playback speed. | ## Attributes @@ -49,38 +49,94 @@ Video(value: VideoOption) ## Events - | Name | Description | +| Name | Description | | -------- | -------- | -| onStart() => void | Triggered when the video is played. | -| onPause() => void | Triggered when the video playback is paused. | -| onFinish() => void | Triggered when the video playback is finished. | +| onStart() => void | Triggered when the video is played. | +| onPause() => void | Triggered when the video playback is paused. | +| onFinish() => void | Triggered when the video playback is finished. | | onError() => void | Triggered when the video playback fails. | -| onPrepared(event?: { duration: number }) => void | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**. | -| onSeeking(event?: { time: number }) => void | Triggered to report the time (in seconds) when the progress bar is being dragged. | -| onSeeked(event?: { time: number }) => void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. | -| onUpdate(event?: { time: number }) => void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. | +| onPrepared(event?: { duration: number }) => void | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**. | +| onSeeking(event?: { time: number }) => void | Triggered to report the time (in seconds) when the progress bar is being dragged. | +| onSeeked(event?: { time: number }) => void | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. | +| onUpdate(event?: { time: number }) => void | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. | -### VideoController +## VideoController -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> A **VideoController** object can control one or more videos. +A **VideoController** object can control one or more videos. - | Name | Description | -| -------- | -------- | -| start() : void | Starts playback. | -| pause() : void | Pauses playback. | -| stop() : void | Stops playback. | -| setCurrentTime(value: number) | Sets the video playback position. | -| setCurrentTime(value: number, seekMode: SeekMode)8+ | Sets the video playback position with the specified seek mode. | + +### Objects to Import + +``` +controller: VideoController = new VideoController(); +``` + +### start + +start(): void + +Starts playback. + +### pause + +pause(): void + +Pauses playback. + +### stop + +stop(): void + +Stops playback. + +### setCurrentTime + +setCurrentTime(value: number) + +Sets the video playback position. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | - | Video playback position. | + +### requestFullscreen + +requestFullscreen(value: boolean) + +Requests full-screen mode. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | false | Whether the playback is in full-screen mode. | + +### exitFullscreen + +exitFullscreen() + +Exits full-screen mode. + +### setCurrentTime8+ + +setCurrentTime(value: number, seekMode: SeekMode) + +Sets the video playback position with the specified seek mode. + +- Parameters + | Name | Type | Mandatory | Default Value | Description | + | -------- | -------- | -------- | -------- | -------- | + | value | number | Yes | - | Video playback position. | + | seekMode | SeekMode | Yes | - | Seek mode. | - SeekMode8+ - | Name | Description | + | Name | Description | | -------- | -------- | - | PreviousKeyframe | Seeks to the nearest previous keyframe. | - | NextKeyframe | Seeks to the nearest next keyframe. | - | ClosestKeyframe | Seeks to the nearest keyframe. | - | Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. | + | PreviousKeyframe | Seeks to the nearest previous keyframe. | + | NextKeyframe | Seeks to the nearest next keyframe. | + | ClosestKeyframe | Seeks to the nearest keyframe. | + | Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md index c064d4cd32cfa97c3b96203628506e73e2486b50..c92528167d4bd71bc5d349afec978fafe7731077 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md @@ -10,7 +10,7 @@ The **CustomDialogController** class is used to display a custom dialog box. ## APIs -CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean}) +CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean}) - Parameters diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 33f5b2b99a98549ba58125493535f8efbad948b5..0a323a7abe01a0b6ccf50c2c6a18179ae0bbe9ff 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -48,7 +48,6 @@ struct DatePickerDialogExample01 { onAccept: (value: DatePickerResult) => { this.selectedDate.setFullYear(value.year, value.month, value.day) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - } }, onCancel: () => { console.info("DatePickerDialog:onCancel()") @@ -82,7 +81,6 @@ struct DatePickerDialogExample02 { onAccept: (value: DatePickerResult) => { this.selectedDate.setFullYear(value.year, value.month, value.day) console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) - } }, onCancel: () => { console.info("DatePickerDialog:onCancel()") diff --git a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index 5102db0b6f597b3b18210c31619a8271a1ae8cb0..7a81a17c79418684213543b1dda4a023a55ba209 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -11,11 +11,11 @@ None ## TextPickerDialog.show -show(options: TextPickerDialogOption) +show(options: TextPickerDialogOptions) Shows a text picker in the given settings. -- TextPickerDialogOption parameters +- TextPickerDialogOptions | Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- | -------- | | range | string[] | Yes| - | Data selection range of the picker.| diff --git a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 5c0bc59793f8386e1cc1e93d1b5c6d11da00f8b7..2dba7f369d72c031022544ce941e71501428259b 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -40,7 +40,6 @@ struct TimePickerDialogExample01 { TimePickerDialog.show({ useMilitaryTime: this.isUseMilitaryTime, onAccept: (value: TimePickerResult) => { - this.selectedDate.setHours(value.hour, value.minute, value.second) console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) }, onCancel: () => { @@ -69,7 +68,6 @@ struct TimePickerDialogExample02 { TimePickerDialog.show({ useMilitaryTime: this.isUseMilitaryTime, onAccept: (value: TimePickerResult) => { - this.selectedDate.setHours(value.hour, value.minute, value.second) console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) }, onCancel: () => { diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md index dfdd81c8275ad9c5ddebf9aeec2626c7959d5402..c8aed1d08bb6797e69b650aefc2d1b7adb9b47fb 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md @@ -2,7 +2,7 @@ > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions @@ -13,14 +13,14 @@ None ## Attributes - | **Name** | **Type** | **Default Value** | **Description** | -| -------- | -------- | -------- | -------- | -| touchable | boolean | true | Whether the current component is touchable. | +| **Name** | **Type** | **Default Value** | **Description** | +| -------- | -------- | -------- | -------- | +| touchable | boolean | true | Whether the current component is touchable. | ## Example - + ``` @Entry @Component diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-hover-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-hover-effect.md index 7c1c225962fcbda50f7277fba18bef4166a3f1e2..56ea57821dfedf2870eeba23e2031b95921b885b 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-hover-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-hover-effect.md @@ -12,22 +12,22 @@ None ## Attributes - | Name | Type | Default Value | Description | +| Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| hoverEffect | HoverEffect | HoverEffect.Auto | Hover effect of the component in hover state. | +| hoverEffect | HoverEffect | HoverEffect.Auto | Hover effect of the component in hover state. | - HoverEffect enums - | Name | Description | + | Name | Description | | -------- | -------- | - | Auto | Default hover effect. | - | Scale | Scale effect. | - | Board | Fade-in and fade-out effect. | - | None | No effect. | + | Auto | Default hover effect. | + | Scale | Scale effect. | + | Highlight | Fade-in and fade-out effect. | + | None | No effect. | ## Example - + ``` @Entry @Component @@ -43,17 +43,17 @@ struct HoverExample { .position({ x: 40, y: 120 }) .hoverEffect(HoverEffect.Scale) .onHover((isHover: boolean) => { - console.info('Scale' + isHover) + console.info('Scale isHover: ' + isHover) this.isHoverVal = isHover }) Text('Board').fontSize(20).fontColor(Color.Gray).width('90%').position({ x: 0, y: 380 }) Column() .width('80%').height(200).backgroundColor(Color.Gray) - .hoverEffect(HoverEffect.Board) + .hoverEffect(HoverEffect.Highlight) .position({ x: 40, y: 420 }) .onHover((isHover: boolean) => { - console.info('HoverEffect.Board') + console.info('Highlight isHover: ' +isHover ) this.isHoverVal = isHover }) } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md index e4ab894bb4ec9529aaec2fcdc073b8fa56132b0a..48bd346aa8202c019f7425097f66f1453dc96fd7 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-polymorphic-style.md @@ -15,21 +15,21 @@ None ## Attributes - | Name | Type | Default Value | Description | +| Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| stateStyle | StateStyles | - | Sets the styles of a component for different states. | +| stateStyles | StateStyles | - | Styles of a component for different states. | - StateStyles8+ - | Name | Type | Mandatory | Default Value | Description | + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | normal | ()=>void | No | - | Style of the component when stateless. | - | pressed | ()=>void | No | - | Style of the component in the pressed state. | - | disabled | ()=>void | No | - | Style of the component in disabled state. | + | normal | ()=>void | No | - | Style of the component when stateless. | + | pressed | ()=>void | No | - | Style of the component in the pressed state. | + | disabled | ()=>void | No | - | Style of the component in disabled state. | ## Example - + ``` @Entry @Component diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index 224ece16207a0d67c4ebdb05f55d157442271301..9d801b2503cc4225907879d5eba7596c120db3b6 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -13,21 +13,21 @@ None ## Attributes - | Name | Type | Default Value | Description | +| Name | Type | Default Value | Description | | -------- | -------- | -------- | -------- | -| bindPopup | show: boolean,
popup: PopupOption \| CustomPopupOption | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the current popup. | +| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to a component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the current popup. | -- PopupOption attributes - | Name | Type | Mandatory | Default Value | Description | +- PopupOptions attributes + | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | - | message | string | Yes | - | Content of the popup message. | - | placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. | - | primaryButton | {
value: string,
action: () => void
} | No | - | First button.
**value**: text of the primary button in the popup.
**action**: callback function for clicking the primary button. | - | secondaryButton | {
value: string,
action: () => void
} | No | - | Second button.
**value**: text of the secondary button in the popup.
**action**: callback function for clicking the secondary button. | - | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. | + | message | string | Yes | - | Content of the popup message. | + | placementOnTop | boolean | No | false | Whether to display the popup above the component. The default value is **false**. | + | primaryButton | {
value: string,
action: () => void
} | No | - | First button.
**value**: text of the primary button in the popup.
**action**: callback function for clicking the primary button. | + | secondaryButton | {
value: string,
action: () => void
} | No | - | Second button.
**value**: text of the secondary button in the popup.
**action**: callback function for clicking the secondary button. | + | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. | -- CustomPopupOption8+ +- CustomPopupOptions8+ | Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- | -------- | | builder | () => any | Yes | - | Builder of the tooltip content. | @@ -39,16 +39,16 @@ None | onStateChange | (isVisible: boolean) => void | No | - | Callback for the popup status change event. The parameter **isVisible** indicates the visibility of the popup. | - Placement8+ enums - | Name | Description | + | Name | Description | | -------- | -------- | - | Left | The tooltip is on the left of the component. | - | Right | The tooltip is on the right of the component. | - | Top | The tooltip is on the top of the component. | - | Bottom | The tooltip is at the bottom of the component. | - | TopLeft | The tooltip is in the upper left corner of the component. | - | TopRight | The tooltip is in the upper right corner of the component. | - | BottomLeft | The tooltip is in the lower left corner of the component. | - | BottomRight | The tooltip is in the lower right corner of the component. | + | Left | The tooltip is on the left of the component. | + | Right | The tooltip is on the right of the component. | + | Top | The tooltip is on the top of the component. | + | Bottom | The tooltip is at the bottom of the component. | + | TopLeft | The tooltip is in the upper left corner of the component. | + | TopRight | The tooltip is in the upper right corner of the component. | + | BottomLeft | The tooltip is in the lower left corner of the component. | + | BottomRight | The tooltip is in the lower right corner of the component. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md index 85f747e8f45c5094683abdd91b52e08effbad07e..92ceedcdc8cdf532dcaf9bfb3205c7f9d4cf7c6d 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md @@ -12,43 +12,43 @@ None ## Events - | Name | Bubble Supported | Description | +| Name | Bubble Supported | Description | | -------- | -------- | -------- | -| onClick(callback: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about the event parameters, see [ClickEvent](#clickevent). | +| onClick(callback: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about the event parameters, see [ClickEvent](#clickevent). | ### ClickEvent - | Name | Type | Description | +| Name | Type | Description | | -------- | -------- | -------- | -| screenX | number | X coordinate of the click relative to the left edge of the screen. | -| screenY | number | Y coordinate of the click relative to the upper edge of the screen. | -| x | number | X coordinate of the click relative to the left edge of the component being clicked. | -| y | number | Y coordinate of the click relative to the upper edge of the component being clicked. | -| target8+ | EventTarget | Target element that is clicked. | -| timestamp | number | Timestamp of the event. | +| screenX | number | X coordinate of the click relative to the left edge of the screen. | +| screenY | number | Y coordinate of the click relative to the upper edge of the screen. | +| x | number | X coordinate of the click relative to the left edge of the component being clicked. | +| y | number | Y coordinate of the click relative to the upper edge of the component being clicked. | +| target8+ | EventTarget | Target element that is clicked. | +| timestamp | number | Timestamp of the event. | - EventTarget8+ attributes - | Name | Type | Description | + | Name | Type | Description | | -------- | -------- | -------- | - | area | Area | Area information of the target element.| + | area | Area | Area information of the target element.| - Area8+ attributes - | Name | Type | Description | + | Name | Type | Description | | -------- | -------- | -------- | - | width | number | Width of the target element, in vp. | - | height | number | Height of the target element, in vp. | - | pos | Position | Position of the upper left corner of the target element relative to that of the parent element. | - | globalPos | Position | Position of the upper left corner of the target element relative to that of the page. | + | width | number | Width of the target element, in vp. | + | height | number | Height of the target element, in vp. | + | position | Position | Position of the upper left corner of the target element relative to that of the parent element. | + | globalPosition | Position | Position of the upper left corner of the target element relative to that of the page. | - Position8+ attributes - | Name | Type | Description | + | Name | Type | Description | | -------- | -------- | -------- | - | x | number | X-coordinate, in vp. | - | y | number | Y-coordinate, in vp. | + | x | number | X-coordinate, in vp. | + | y | number | Y-coordinate, in vp. | ## Example diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index a07d7e86e951ca950fed04908591c7c6a6d84014..6d434aacb1d4e894bba5d8d9707f3add72e4e0b6 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -3,5 +3,14 @@ - User Authentication - [User Authentication Overview](userauth-overview.md) - [User Authentication Development](userauth-guidelines.md) -- hapsigner - - [hapsigner Guide](hapsigntool-guidelines.md) \ No newline at end of file + +- Key Management + - [HUKS Overview](huks-overview.md) + - [HUKS Development](huks-guidelines.md) + +- hapsigntool + - [hapsigntool Guide](hapsigntool-guidelines.md) + +- Access Control + - [Access Control Overview](accesstoken-overview.md) + - [Access Control Development](accesstoken-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..d24182fb86a50223ecc708867f6acfa1bc99ae49 --- /dev/null +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -0,0 +1,152 @@ +# Access Control Development + +## Scenario + +In this example, the app requires the **ohos.permission.PERMISSION1** and **ohos.permission.PERMISSION2** permissions to implement core functions. + +- The ability privilege level (APL) of the app is normal. +- The level of **ohos.permission.PERMISSION1** is normal, and the authorization mode is system_grant. +- The level of **ohos.permission.PERMISSION2** is system_basic, and the authorization mode is user_grant. + +> **Precautions** +> +> In this scenario, the required permissions include a user_grant permission. You can check whether the caller has the required permission through permission verification. +> +> If the permission verification result indicates that the app has not obtained that permission, dynamic user authorization is required. +> +## Available APIs + +The table below lists only the API used in this guide. For more information, see the [API Reference](../reference/apis/js-apis-abilityAccessCtrl.md). + +| API | Description | +| ------------------------------------------------------------ | --------------------------------------------------- | +| verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Verifies whether an app has the specified permission. This API uses a promise to return the result.| + +## Declaring Permissions + +### config.json + +Declare the permissions required by the app one by one in the **config.json** file. The app cannot obtain a permission if it is not declared in the **config.json** file. + +**Description of config.json** + +| Field | Description | +| --------- | ------------------------------------------------------------ | +| name | Name of the permission. | +| reason | Reason for requesting the permission. This field is mandatory for a user_grant permission.| +| usedScene | Scenario of the permission. This field is mandatory for a user_grant permission.| +| abilities | Abilities that use the permission. The value is an array. | +| when | Time when the permission is used. The value can be **inuse** (the permission can be used only in the foreground) or **always** (the permission can be used in foreground and background).| + +**Example** + +```json +{ + "module" : { + "requesetPermissions":[ + { + "name" : "ohos.permission.PERMISSION1", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "FormAbility" + ], + "when":"inuse" + } + }, + { + "name" : "ohos.permission.PERMISSION2", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "FormAbility" + ], + "when":"always" + } + } + ], + } +} +``` +## Declaring the ACL + +The permission level of **ohos.permission.PERMISSION2** is system_basic, which is higher than the app's APL. In this case, use the ACL. + +In addition to declaring all the permissions in the **config.json** file, you must declare the permissions whose levels are higher than the app's APL in the app's profile. In this example, declare the permission under the **acls** field: +```json +{ + "version-name": "1.0.0", + "version-code": 1, + "app-distribution-type": "os_integration", + "uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18", + "validity": { + "not-before": 1594865258, + "not-after": 1689473258 + }, + "type": "release", + "bundle-info": { + "developer-id": "OpenHarmony", + "distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO\nMRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh\nbTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjEwMjAy\nMTIxOTMxWhcNNDkxMjMxMTIxOTMxWjBoMQswCQYDVQQGEwJDTjEUMBIGA1UEChML\nT3Blbkhhcm1vbnkxGTAXBgNVBAsTEE9wZW5IYXJtb255IFRlYW0xKDAmBgNVBAMT\nH09wZW5IYXJtb255IEFwcGxpY2F0aW9uIFJlbGVhc2UwWTATBgcqhkjOPQIBBggq\nhkjOPQMBBwNCAATbYOCQQpW5fdkYHN45v0X3AHax12jPBdEDosFRIZ1eXmxOYzSG\nJwMfsHhUU90E8lI0TXYZnNmgM1sovubeQqATo1IwUDAfBgNVHSMEGDAWgBTbhrci\nFtULoUu33SV7ufEFfaItRzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFPtxruhl\ncRBQsJdwcZqLu9oNUVgaMAwGCCqGSM49BAMDBQADaAAwZQIxAJta0PQ2p4DIu/ps\nLMdLCDgQ5UH1l0B4PGhBlMgdi2zf8nk9spazEQI/0XNwpft8QAIwHSuA2WelVi/o\nzAlF08DnbJrOOtOnQq5wHOPlDYB4OtUzOYJk9scotrEnJxJzGsh/\n-----END CERTIFICATE-----\n", + "bundle-name": "com.ohos.permissionmanager", + "apl": "system_core", + "app-feature": "hos_system_app" + }, + "acls": { + "allowed-acls": [ + "ohos.permission.PERMISSION2" + ] + }, + "permissions": { + "restricted-permissions": [] + }, + "issuer": "pki_internal" +} +``` + +## Applying for the user_grant Permission + +After the permissions are declared, the system grants the system_grant permission during the installation of the app. The user_grant permission must be authorized by the user. + +Therefore, before invoking the API protected by the **ohos.permission.PERMISSION2 permission**, the app needs to verify whether it has the permission. + +If the verification result indicates that the app has the permission, the app can access the target API. Otherwise, the app needs to request user authorization and then proceeds based on the authorization result. For details, see [Access Control Overview](accesstoken-overview.md). + +> **Precautions** +> +> The permissions authorized by user are not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to an app, the app's permission must be verified before the app calls an API protected by the permission. + +## Example + +The procedure is as follows: + +1. Obtain the caller's identity tokenId. +2. Determine the permission to be verified. In this example, the permission is **permissionNameUser**. +3. Call **verifyAccessToken** to verify the permissions of the caller. +4. Proceed based on the permission verification result. + +```js + import {describe, beforeEach, afterEach, it, expect} from 'deccjsunit/index' + import abilityAccessCtrl from '@ohos.abilityAccessCtrl' + import bundle from '@ohos.bundle' + + async requestPermission() { + var permissionNameUser = "ohos.permission.PERMISSION2"; + var bundleFlag = 0; + var tokenID = undefined; + var userID = 100; + var appInfo = await bundle.getApplicationInfo('ohos.acts.security.access_token.normal', bundleFlag, userID); + tokenID = appInfo.accessTokenId; + console.log("AccessTokenTest accessTokenId:" + appInfo.accessTokenId + ", name:" + appInfo.name + + ", bundleName:" + appInfo.bundleName) + var atManager = abilityAccessCtrl.createAtManager(); + var result = await atManager.verifyAccessToken(tokenID, permissionNameUser); + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + // Execute the operation. + } else { + // Apply for dynamic user authorization using requestPermissionsFromUser. + } + } + +``` +> ![icon-note.gif](../public_sys-resources/icon-note.gif)**NOTE**
+> For details about how to use **requestPermissionsFromUser**, see [API Reference] (../reference/apis/js-apis-ability-context.md). diff --git a/en/application-dev/security/accesstoken-overview.md b/en/application-dev/security/accesstoken-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..f47160a45f7cc0489bd7c8d99d36cf3e775cad6d --- /dev/null +++ b/en/application-dev/security/accesstoken-overview.md @@ -0,0 +1,272 @@ +# Access Control Overview + +## Introduction +AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony. + +By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. Systems or apps must also share their data or functions through interfaces in an explicit manner. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. + +App permissions are used to protect the following objects: + +- Data: personal data (such as photos, Contacts, calendar, and location), device data (such as device ID, camera, and microphone), and app data. +- Functions: device functions (such as making calls, sending SMS messages, and connecting to the Internet) and app functions (such as displaying windows and creating shortcuts). + +Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. + +Currently, ATM performs app permission verification based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID. + +## How to Develop + +Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package. + +Determine whether the required permissions need to be authorized by users. If yes, provide a dialog box dynamically to request user authorization. + +After the user grants permissions to the app, the app can access the data or perform the operation. + +The figure below shows the process. + +![](figures/figure1.png) + +## When to Use + +### Scenarios + +The following describes two common scenarios. + +- **Video playback apps** + + Video playback apps need to use multimedia functions and read and write media files stored on storage devices. Therefore, the apps must have at least the following permissions: + + * ohos.permission.READ_MEDIA (allowing the app to read external media files) + + * ohos.permission.WRITE_MEDIA (allowing the app to read and write external media files) + +- **Photography apps** + + Photography apps need to use the camera function. Before accessing the camera service, the app must have the following permission: + + ohos.permission.CAMERA (allowing the app to use the camera to take photos and record videos). + +### Basic Principles + +Observe the following principles for permission management: + +- Provide clear description about the app functions and scenarios and permissions required for using the app so that users can clearly know why, when, and how to apply for permissions for using the app. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app. +- Use the principle of least authority for user permissions. Allow only necessary permissions for service functions. +- When an app is started for the first time, avoid frequently displaying pop-up windows for users to apply for multiple permissions. Allow users to apply for permissions only when they need to use the corresponding service functions. +- If a user rejects to authorize a permission, the user can still use functions irrelevant to this permission and can register and access the app. +- Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to give authorization in System Settings if the user triggers this function again or needs to use this function. + +- All the permissions granted to apps must come from the Permission List. Custom permissions are not allowed for apps currently. + +## Permission Levels + +To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability. + +### App APL + +The ability privilege level (APL) defines the priority of the app permission requested. Apps of different APLs can apply for permissions of different levels. + +The table below describes the APLs. + +| APL | Description | +| ---------------- | -------------------------------------- | +| system_core | The apps of this level provide core abilities of the operating system.| +| system_basic| The apps of this level provide basic system services. | +| Normal | The apps of this level are normal apps. | + +By default, apps are of the normal APL. To declare the system_basic or higher APL: +- The APL must be approved by the app store. +- The APL must be declared in the **apl** field of the app's profile in the app installation package, and a profile signing certificate must be generated. For details, see [Configuring OpenHarmony App Signature Information]( https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section17660437768). + +### Permission Levels + +The permissions open to apps vary with the permission level. The permission levels include the following in ascending order of seniority. + +- **normal** + + The normal permission allows access to common system resources beyond the default rules. Access to these system resources (including data and functions) has minor risks on user privacy and other apps. + + The permissions of this level are available only to apps of the normal or higher APL. + +- **system_basic** + + The system_basic permission allows access to resources related to basic operating system services. The basic services are basic functions provided or preconfigured by the system, such as system setting and identity authentication. Access to these resources may have considerable risks to user privacy and other apps. + + The permissions of this level are available only to the apps of the system_basic APL. + +- **system_core** + + The system_core permission allows access to core resources of the operating system. These resources are the underlying core services of the system. If these resources are corrupted, the OS cannot run properly. + + The permissions of this type are not open to any app currently. + +### ACL + +As described above, permission levels and app APLs are in one-to-one correspondence. In principle, **an app with a lower APL cannot apply for higher permissions by default**. + +The Access Control List (ACL) makes low-level apps to have high-level permissions. + +**Example** + +The APL of app A is normal. App A needs to have permission B (system_basic level) and permission C (normal level). In this case, you can use the ACL to grant permission B to app A. + +For details, see [Using the ACL](#usingacl). + +## Permission Authorization Modes + +Permissions can be classified into the following types based on the authorization mode: + +- **system_grant** + + The app permissions are authorized by the system. This type of apps cannot access user or device sensitive information. The allowed operations have minor impact on the system or other apps. + + For a system_grant app, the system automatically grants the required permissions to the app when the app is installed. The system_grant permission list must be presented to users on the details page of the app store. + +- **user_grant** + + The app permissions must be authorized by users. This type of apps may access user or device sensitive information. The allowed operations may have a critical impact on the system or other apps. + + This type of permissions must be declared in the app installation package and authorized by users dynamically during the running of the app. The app has the permission only after user authorization. + + For example, in the [Permission List](#permissionlist), the permissions for the microphone and camera are user_grant permissions. The list provides reasons for using the permissions. + + The user_grant permission list must also be presented on the details page of the app store. + +## Authorization Processes + +The process for an app obtaining the required permissions varies + +depending on the permission authorization mode. + +- For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md) in the **config.json** file. The permission will be pre-granted when the app is installed. + +- For a user_grant permission, you need to [declare the permission](accesstoken-guidelines.md) in the **config.json** file, and a dialog box needs to be displayed to request user authorization during the running of the app. + +### Permission Authorization Process (user_grant) + +The procedure is as follows: + +1. In the **config.json** file, declare the permissions required by the app. For details, see [Access Control Development](accesstoken-guidelines.md). + +2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions. + +3. Check whether the user has granted the required permissions to the app when the app is running. If yes, the app can access the data or perform the operation. If the user has not granted the permissions to the app, display a dialog box requesting the user authorization when the app attempts to access the data or perform the operation. + +4. Check the user authorization result. Allow the next step only after the user has granted the permissions to the app. + +**Precautions** + +- Check the app's permission each time before the operation requiring the permission is performed. + +- To check whether a user has granted specific permissions to your app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](#accesstoken-guidelines.md). +- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call the API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the requested permission. The user will determine whether to grant the permission based on the running context of the app. +- The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission. + +### Using the ACL + +If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permissions required. + +In addition to the preceding [authorization processes](#authorizationprocesses), you need to declare the ACL. + +In addition to declaring the required permissions in the **config.json** file, you must declare the high-level permissions in the app's [profile](accesstoken-guidelines.md). The subsequent steps remain unchanged. + +**NOTE** + +* The ACL must be approved by the app store. +* Declare the target ACL in the **acl** field of the app's profile in the app installation package, and generate a profile signing certificate. For details, see [Configuring OpenHarmony App Signature Information]( https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-debugging-and-running-0000001263040487#section17660437768). + +## Permission List + +The following lists the permissions defined by the system. + +| Permission | APL | Authorization Mode | Enable ACL| Description | +| -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------------------------ | +| ohos.permission.USE_BLUETOOTH | normal | system_grant | TRUE | Allows an app to access to Bluetooth configuration. | +| ohos.permission.DISCOVER_BLUETOOTH | normal | system_grant | TRUE | Allows an app to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. | +| ohos.permission.MANAGE_BLUETOOTH | system_basic | system_grant | TRUE | Allows an app to pair with a Bluetooth device and access the Contacts or messages of the device. | +| ohos.permission.INTERNET | normal | system_grant | TRUE | Allows an app to access the Internet. | +| ohos.permission.MODIFY_AUDIO_SETTINGS | normal | system_grant | TRUE | Allows an app to modify audio settings. | +| ohos.permission.GET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to read telephony information. | +| ohos.permission.REQUIRE_FORM | system_basic | system_grant | TRUE | Allows an app to obtain the Ability Form. | +| ohos.permission.GET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to obtain network information. | +| ohos.permission.PLACE_CALL | system_basic | system_grant | TRUE | Allows an app to make calls without starting the dialer. | +| ohos.permission.SET_NETWORK_INFO | normal | system_grant | TRUE | Allows an app to set data network information. | +| ohos.permission.REMOVE_CACHE_FILES | system_basic | system_grant | TRUE | Allows the cache of the specified app to be cleared. | +| ohos.permission.REBOOT | system_basic | system_grant | TRUE | Allows an app to restart the device. | +| ohos.permission.RUNNING_LOCK | normal | system_grant | TRUE | Allows an app to obtain a running lock. | +| ohos.permission.ENROLL_BIOMETRIC | system_core | system_grant | FALSE | Allows an app to add or remove biometric data. | +| ohos.permission.ACCESS_BIOMETRIC | normal | system_grant | FALSE | Allows an app to use biometric recognition for identity authentication. | +| ohos.permission.ACCESS_BIOMETRIC_INTERNAL | system_core | system_grant | FALSE | Allows an app to apply for or release biometric recognition resources. | +| ohos.permission.RESET_BIOMETRIC_LOCKOUT | system_core | system_grant | FALSE | Allows an app to reset the maximum number of failures allowed before biometric authentication is locked. | +| ohos.permission.SET_TIME | system_basic | system_grant | TRUE | Allows an app to set the system time. | +| ohos.permission.SET_TIME_ZONE | system_basic | system_grant | TRUE | Allows an app to set the system time zone. | +| ohos.permission.DOWNLOAD_SESSION_MANAGER | system_core | system_grant | TRUE | Allows an app to manage the downloaded sessions. | +| ohos.permission.COMMONEVENT_STICKY | normal | system_grant | TRUE | Allows an app to publish sticky common events. | +| ohos.permission.SYSTEM_FLOAT_WINDOW | normal | system_grant | TRUE | Allows an app to be displayed in a floating window on top of other apps. | +| ohos.permission.POWER_MANAGER | system_core | system_grant | TRUE | Allows an app to hibernate or wake up the device by calling APIs. | +| ohos.permission.REFRESH_USER_ACTION | system_basic | system_grant | TRUE | Allows an app to reset the screen timeout counter when a user input event occurs, such as pressing a key or tapping the screen. | +| ohos.permission.POWER_OPTIMIZATION | system_basic | system_grant | TRUE | Allows an app to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes.| +| ohos.permission.REBOOT_RECOVERY | system_basic | system_grant | TRUE | Allows an app to restart the device and enter Recovery mode. | +| ohos.permission.MANAGE_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows an app to manage local user accounts. | +| ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | system_basic | system_grant | TRUE | Allows access between multiple OS accounts. | +| ohos.permission.VIBRATE | normal | system_grant | TRUE | Allows an app to control motor vibration. | +| ohos.permission.CONNECT_IME_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind the **InputMethodAbility**. | +| ohos.permission.CONNECT_SCREEN_SAVER_ABILITY | system_core | system_grant | TRUE | Allows an app or service to bind the **ScreenSaverAbility**. | +| ohos.permission.READ_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to read the screen saver information, such as the list of screen savers that have been installed and the activated one. | +| ohos.permission.WRITE_SCREEN_SAVER | system_basic | system_grant | TRUE | Allows an app to modify the screen saver information, such as activating and previewing a screen saver. | +| ohos.permission.SET_WALLPAPER | normal | system_grant | TRUE | Allows an app to set a static wallpaper. | +| ohos.permission.GET_WALLPAPER | system_basic | system_grant | TRUE | Allows an app to read wallpaper files. | +| ohos.permission.CHANGE_ABILITY_ENABLED_STATE | system_basic | system_grant | TRUE | Allows an app to enable or disable an app or component. | +| ohos.permission.ACCESS_MISSIONS | system_basic | system_grant | TRUE | Allows an app to obtain information about running processes and tasks in a task stack. | +| ohos.permission.CLEAN_BACKGROUND_PROCESSES | normal | system_grant | TRUE | Allows an app to clear background processes based on their bundle names. | +| ohos.permission.KEEP_BACKGROUND_RUNNING | normal | system_grant | TRUE | Allows a service ability to keep running in the background. | +| ohos.permission.UPDATE_CONFIGURATION | system_basic | system_grant | TRUE | Allows an app to modify system settings. | +| ohos.permission.GRANT_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to grant sensitive permissions to other apps. | +| ohos.permission.REVOKE_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to revoke sensitive permissions granted to other apps. | +| ohos.permission.GET_SENSITIVE_PERMISSIONS | system_core | system_grant | TRUE | Allows an app to obtain the sensitive permissions that have been granted to other apps. | +| ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION | system_core | system_grant | TRUE | Allows an app to set the attributes of apps of other users. | +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_basic | system_grant | TRUE | Allows an app to listen for changes in other apps, when they are installed, updated, or uninstalled. | +| ohos.permission.GET_BUNDLE_INFO | normal | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | +| ohos.permission.ACCELEROMETER | normal | system_grant | TRUE | Allows an app to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. | +| ohos.permission.GYROSCOPE | normal | system_grant | TRUE | Allows an app to read data from a gyroscope sensor or uncalibrated gyroscope sensor. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | system_grant | TRUE | Allows a non-system app to obtain information about other apps. | +| ohos.permission.INSTALL_BUNDLE | system_core | system_grant | TRUE | Allows an app to install and uninstall other apps. | +| ohos.permission.MANAGE_SHORTCUTS | system_core | system_grant | TRUE | Allows an app to query and start shortcuts of other apps.| +| ohos.permission.radio.ACCESS_FM_AM | system_core | system_grant | TRUE | Allows an app to access radio services. | +| ohos.permission.SET_TELEPHONY_STATE | system_basic | system_grant | TRUE | Allows an app to change the telephone state. | +| ohos.permission.START_ABILIIES_FROM_BACKGROUND | system_basic | system_grant | TRUE | Allows an app to start Feature abilities in the background. | +| ohos.permission.BUNDLE_ACTIVE_INFO | system_basic | system_grant | TRUE | Allows an app to obtain how long other apps have been running in the foreground or background. | +| ohos.permission.START_INVISIBLE_ABILITY | system_core | system_grant | TRUE | Allows an app to start an invisible ability. | +| ohos.permission.sec.ACCESS_UDID | system_basic | system_grant | TRUE | Allows an app to obtain the Unified Device ID (UDID). | +| ohos.permission.LAUNCH_DATA_PRIVACY_CENTER | system_basic | system_grant | TRUE | Allows an app to switch from its privacy statement page to the Data & privacy page. | +| ohos.permission.MANAGE_MEDIA_RESOURCES | system_basic | system_grant | TRUE | Allows an app to obtain and manage the media resources that are being played on the device.| +| ohos.permission.PUBLISH_AGENT_REMINDER | normal | system_grant | TRUE | Allows an app to use agent-powered reminders. | +| ohos.permission.CONTROL_TASK_SYNC_ANIMATOR | system_core | system_grant | TRUE | Allows apps to use sync task animations. | +| ohos.permission.INPUT_MONITORING | system_core | system_grant | TRUE | Allows the app to listen for input events. Only the system signature apps can apply for this permission. | +| ohos.permission.MANAGE_MISSIONS | system_core | system_grant | TRUE | Allows users to manage ability task stacks. | +| ohos.permission.NOTIFICATION_CONTROLLER | system_core | system_grant | TRUE | Allows an app to manage and subscribe to notifications. Currently, only system apps can apply for this permission. | +| ohos.permission.CONNECTIVITY_INTERNAL | system_basic | system_grant | TRUE | Allows the app to obtain network information or modify network settings. Currently, only system apps can apply for this permission.| +| ohos.permission.ANSWER_CALL | system_basic | user_grant | TRUE | Allows the app to answer incoming calls. | +| ohos.permission.READ_CALENDAR | normal | user_grant | TRUE | Allows an app to read calendar data. | +| ohos.permission.READ_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to read call logs. | +| ohos.permission.READ_CELL_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read cell broadcast messages received by the device. | +| ohos.permission.READ_CONTACTS | system_basic | user_grant | TRUE | Allows an app to read contacts. | +| ohos.permission.READ_MESSAGES | system_basic | user_grant | TRUE | Allows an app to read messages. | +| ohos.permission.RECEIVE_MMS | system_basic | user_grant | TRUE | Allows the app to receive and process MMS messages. | +| ohos.permission.RECEIVE_SMS | system_basic | user_grant | TRUE | Allows the app to receive and process SMS messages. | +| ohos.permission.RECEIVE_WAP_MESSAGES | system_basic | user_grant | TRUE | Allows the app to receive and process WAP messages. | +| ohos.permission.MICROPHONE | normal | user_grant | TRUE | Allows an app to access the microphone. | +| ohos.permission.SEND_MESSAGES | system_basic | user_grant | TRUE | Allows an app to send messages. | +| ohos.permission.WRITE_CALENDAR | normal | user_grant | TRUE | Allows an app to add, remove, and modify calendar events. | +| ohos.permission.WRITE_CALL_LOG | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify call logs. | +| ohos.permission.WRITE_CONTACTS | system_basic | user_grant | TRUE | Allows an app to add, remove, and modify contacts. | +| ohos.permission.DISTRIBUTED_DATASYNC | normal | user_grant | TRUE | Allows an app to exchange data with other devices. | +| ohos.permission.MANAGE_VOICEMAIL | system_basic | user_grant | TRUE | Allows an app to add messages in the voice mailbox. | +| ohos.permission.LOCATION_IN_BACKGROUND | normal | user_grant | FALSE | Allows an app running in the background to obtain the device location. | +| ohos.permission.LOCATION | normal | user_grant | TRUE | Allows an app to obtain the device location. | +| ohos.permission.MEDIA_LOCATION | normal | user_grant | TRUE | Allow an app to access geographical locations in the user's media file. | +| ohos.permission.CAMERA | normal | user_grant | TRUE | Allows an app to use the camera to take photos and record videos. | +| ohos.permission.READ_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from the user's external storage. | +| ohos.permission.WRITE_MEDIA | normal | user_grant | TRUE | Allows an app to read media files from and write media files into the user's external storage. | +| ohos.permission.ACTIVITY_MOTION | normal | user_grant | TRUE | Allows an app to read the current workout status of the user. | +| ohos.permission.READ_HEALTH_DATA | normal | user_grant | TRUE | Allows an app to read the health data of the user. | diff --git a/en/application-dev/security/figures/figure1.png b/en/application-dev/security/figures/figure1.png new file mode 100644 index 0000000000000000000000000000000000000000..dad4b74893a09184fd31fbf6688f6d30121e325e Binary files /dev/null and b/en/application-dev/security/figures/figure1.png differ diff --git a/en/application-dev/security/huks-guidelines.md b/en/application-dev/security/huks-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..e565b71d8c967b9b00657cd38abbe3674047d305 --- /dev/null +++ b/en/application-dev/security/huks-guidelines.md @@ -0,0 +1,143 @@ +# HUKS Development + +## When to Use + + Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys. + + +## Available APIs + +| API | Description | +| ------------------------------------------------------------ | ---------------- | +| function generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void; | Generates a private key. This method uses an asynchronous callback to return the result. | +| function generateKey(keyAlias: string, options: HuksOptions) : Promise; | Generates a private key. This method uses a promise to return the result. | +| function exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void; | Exports the public key. This method uses an asynchronous callback to return the result. | +| function exportKey(keyAlias: string, options: HuksOptions) : Promise; | Exports the public key. This method uses a promise to return the result. | +| function isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void; | Check whether a key exists. This method uses an asynchronous callback to return the result.| +| function isKeyExist(keyAlias: string, options: HuksOptions) : Promise; | Check whether a key exists. This method uses a promise to return the result.| +| function deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback) : void; | Deletes a key. This method uses an asynchronous callback to return the result. | +| function deleteKey(keyAlias: string, options: HuksOptions) : Promise; | Deletes a key. This method uses a promise to return the result. | + +## How to Develop + +1. Import the HUKS module. + + ```js + import huks from '@ohos.security.huks' + ``` + +2. Call **generateKey()** to generate a private key. + + **keyAlias** indicates the alias of the key generated. **options** indicates the parameters used for generating the key. Set **options** based on the actual situation. + + The value returned indicates whether the key is successfully generated. + + ```js + var alias = 'testAlias'; + var properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_ECC + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224 + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_NONE + }; + var options = { + properties: properties + } + var resultA = huks.generateKey(alias, options); + ``` + +3. Call **Init()** to initialize the key. + + **Alias** indicates the alias of the key to initialize, and **options** indicates the parameters used for initializing the key. + + The value returned indicates whether the **Init** operation is successful. + + ```js + var alias = 'test001' + var properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH + }; + properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE + }; + properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 + }; + var options = { + properties: properties + }; + huks.init(alias, options, function(err, data) { + if (err.code !== 0) { + console.log("test init err information: " + JSON.stringify(err)); + } else { + console.log(`test init data: ${JSON.stringify(data)}`); + } + }) + ``` + +4. Call **update()** to update the key. + + **handle** indicates the session ID for updating the key. **options** indicates the parameters used for updating the key. + + The value returned indicates whether the **Update** operation is successful. + + ```js + var properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH + }; + properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE + }; + properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 + }; + var options = { + properties: properties + }; + var result = huks.update(handle, options) + ``` + +5. Call **finish()** to complete the operation. + + **handle** indicates the session ID of the **Finish** operation. **options** indicates the parameters used for this operation. + + The value returned indicates whether the **Finish** operation is successful. + + ```js + var properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HksKeyAlg.HKS_ALG_DH + }; + properties[1] = { + tag: huks.HksTag.HKS_TAG_PURPOSE, + value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE + }; + properties[2] = { + tag: huks.HksTag.HKS_TAG_KEY_SIZE, + value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096 + }; + var options = { + properties: properties + }; + var result = huks.finish(handle, options) + ``` diff --git a/en/application-dev/security/huks-overview.md b/en/application-dev/security/huks-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..bf7de59ac4c5138c6a6ee8dcdabcd092a02e65bf --- /dev/null +++ b/en/application-dev/security/huks-overview.md @@ -0,0 +1,27 @@ +# HUKS Overview + +### Introduction + +Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys. + +### Basic Concepts + +- HUKS provides key management functions, including encryption and decryption, signing and signature verification, key agreement and derivation, and Hash-based Message Authentication Code (HMAC) calculation. +- HUKS supports the following algorithms: AES and RSA in encryption and decryption, RSA, ECC, DSA, and ED25519 in signing and signature verification, PBKDF2 in key derivation, and DH, ECDH, and X25519 in key agreement. +- HUKS uses the OpenSSL and Mbed TLS algorithm libraries. + +### Working Principles + +HUKS manages keys through the following operations: + +- **Init**: reads the key, creates a session ID, and returns the session ID to the caller. + +- **Update**: updates data by segment based on the session ID obtained. + +- **Finish**: processes all data transferred to HUKS and then releases resources. + + >![](../public_sys-resources/icon-notice.gif)**NOTICE**:
If an error occurs in the **Init**, **Update**, or **Finish** operation, you must invoke the **Abort** operation to terminate the use of the key. + + +### Constraints +N/A diff --git a/en/application-dev/security/userauth-guidelines.md b/en/application-dev/security/userauth-guidelines.md index 38dc702198546d90925a3b02d2d2d330bdfd1de7..c6a9577a3ba6911f3966fcf195aff62acfcd3460 100644 --- a/en/application-dev/security/userauth-guidelines.md +++ b/en/application-dev/security/userauth-guidelines.md @@ -1,102 +1,113 @@ # User Authentication Development +> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**
+> This development guide applies to the SDK of API Version 8 or later. + ## When to Use -OpenHarmony supports 2D and 3D facial recognition that can be used for identity authentication during device unlocking, application login, and payment. +2D and 3D facial recognition used in identity authentication scenarios such as device unlocking, application login, and payment ## Available APIs -The **userIAM\_userAuth** module provides methods for checking the support for biometric authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. Before performing biometric authentication, check whether your device supports this capability, including the authentication type, security level, and whether local authentication is used. If biometric authentication is not supported, consider using another authentication type. The following table lists methods in the APIs available for biometric authentication. +The userIAM_userAuth module provides methods for checking the support for user authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. For more details, see [API Reference](../reference/apis/js-apis-useriam-userauth.md). -**Table 1** Methods available for biometric authentication +Before performing authentication, check whether the device supports user authentication, including the authentication type and level. If user authentication is not supported, consider using another authentication type. The following table lists the APIs available for user authentication. -| Method | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| getAuthenticator(): Authenticator | Obtains an **Authenticator** object for user authentication. 6+
Obtains an **Authenticator** object to check the device's capability of user authentication, perform or cancel user authentication, and obtain the tips generated in the authentication process. 7+ | -| checkAvailability(type: AuthType, level: SecureLevel): number | Checks whether the device supports the specified authentication type and security level. | -| execute(type: AuthType, level: SecureLevel, callback: AsyncCallback\): void | Performs user authentication and returns the authentication result using an asynchronous callback. | -| execute(type: AuthType, level: SecureLevel): Promise\ | Performs user authentication and returns the authentication result using a promise. | -| cancel(): void | Cancels the current authentication. | -| on(type: "tip", callback: Callback\): void | Subscribes to the events of the specified type. | -| off(type: "tip", callback?: Callback\): void | Unsubscribes from the events of the specified type. | +**Table 1** APIs of user authentication +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| getVersion() : number | Obtains the version information of an authentication object. | +| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number | Checks whether the device supports the specified authentication type and level.| +| auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array | Performs user authentication. This method uses asynchronous callback to return the result. | +| cancelAuth(contextID : Uint8Array) : number | Cancels an authentication. | ## How to Develop Before starting the development, make the following preparations: -1. Add the **ohos.permission.ACCESS\_BIOMETRIC** permission declaration to the application permission file. -2. Add **import userIAM\_userAuth from '@ohos.userIAM.userAuth'** to the code file that provides biometric recognition. +1. Add the ohos.permission.ACCESS_BIOMETRIC permission declaration to the application permission file. +2. Add **import userIAM_userAuth from '@ohos.userIAM.userAuth'** to the code file. The development procedure is as follows: -1. Obtain an **Authenticator** singleton object. The sample code is as follows: - - ``` - let auth = userIAM_userAuth.getAuthenticator(); - ``` - -2. Check whether the device provides the authentication capability of the specified level. - - 2D facial recognition supports authentication lower than S2, and 3D facial recognition supports authentication lower than S3. The sample code is as follows: - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let checkCode = authenticator.checkAvailability("FACE_ONLY", "S2"); - if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) { - console.info("check auth support success"); - } else { - console.error("check auth support fail, code = " + checkCode); - } - ``` - -3. \(Optional\) Subscribe to tip information. The sample code is as follows: - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode +") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - authenticator.on("tip", tipCallback); - ``` - -4. Perform the authentication. The sample code is as follows: - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - authenticator.off("tip", tipCallback); - console.info("auth success"); - }).catch((code)=>{ - authenticator.off("tip", tipCallback); - console.error("auth fail, code = " + code); - }); - ``` - -5. \(Optional\) Unsubscribe from tip information if you have subscribed to tip information you have subscribed to tip information. - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let tipCallback = (tip)=>{ - console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" + - tip.tipEvent + ") info(" + tip.tipInfo + ")"); - }; - // Unsubscribe from a specified callback. - authenticator.off("tip", tipCallback); - // Unsubscribe from all callbacks. - authenticator.off("tip"); - ``` - -6. Cancel authentication. The sample code is as follows: - - ``` - let authenticator = userIAM_userAuth.getAuthenticator(); - let cancelCode = authenticator.cancel(); - if (cancelCode == userIAM_userAuth.Result.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` - +1. Obtain an **Authenticator** singleton object. The sample code is as follows: + + ```js + let auth = new userIAM_userAuth.UserAuth(); + ``` + +2. (Optional) Obtain the version information of the authenticated object. + + ```js + let auth = new userIAM_userAuth.UserAuth(); + let version = auth.getVersion(); + console.info("auth version = " + version); + ``` + +3. Check whether the device supports the authentication capabilities based on the specified authentication type and level. + + ```js + let auth = new userIAM_userAuth.UserAuth(); + let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); + // Add the logic to be executed if the specified authentication type is supported. + } else { + console.error("check auth support fail, code = " + checkCode); + // Add the logic to be executed if the specified authentication type is not supported. + } + ``` + +4. Perform an authentication. + + ```js + let auth = new userIAM_userAuth.UserAuth(); + auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == 'SUCCESS') { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } + }); + ``` + +5. Cancel the authentication. + + ```js + let auth = new userIAM_userAuth.UserAuth(); + // Obtain contextId using auth(). + let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + console.info("auth onResult result = " + result); + }, + + onAcquireInfo: (module, acquire, extraInfo) => { + console.info("auth onAcquireInfo module = " + module); + } + }); + let cancelCode = auth.cancel(contextId); + if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); + } else { + console.error("cancel auth fail"); + } + ``` diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..32ac7687a68e1702f82c6cf8c12ed4ff18bcad74 --- /dev/null +++ b/en/application-dev/ui/Readme-EN.md @@ -0,0 +1,145 @@ +# UI Development + +- [ArkUI Overview](arkui-overview.md) +- JavaScript-based Web-like Development Paradigm + - [Overview](ui-js-overview.md) + - Framework + - [File Organization](js-framework-file.md) + - ["js" Tag](js-framework-js-tag.md) + - [app.js](js-framework-js-file.md) + - Syntax + - [HML](js-framework-syntax-hml.md) + - [CSS](js-framework-syntax-css.md) + - [JavaScript](js-framework-syntax-js.md) + - [Lifecycle](js-framework-lifecycle.md) + - [Resource Limitations and Access](js-framework-resource-restriction.md) + - [Multi-Language Capability](js-framework-multiple-languages.md) + - Building the UI + - [Component Overview](ui-js-building-ui-component.md) + - Building the Layout + - [Layout Description](ui-js-building-ui-layout-intro.md) + - [Adding Title and Paragraph Text](ui-js-building-ui-layout-text.md) + - [Adding an Image](ui-js-building-ui-layout-image.md) + - [Adding a Comment](ui-js-building-ui-layout-comment.md) + - [Adding a Container](ui-js-building-ui-layout-external-container.md) + - [Adding Interactions](ui-js-building-ui-interactions.md) + - [Developing Animations](ui-js-building-ui-animation.md) + - [Defining Gesture Events](ui-js-building-ui-event.md) + - [Defining Page Routes](ui-js-building-ui-routes.md) + - Common Component Development Guidelines + - Container Components + - [List Development](ui-js-components-list.md) + - [Dialog Development](ui-js-components-dialog.md) + - [Form Development](ui-js-components-form.md) + - [Stepper Development](ui-js-components-stepper.md) + - [Tabs Development](ui-js-component-tabs.md) + - [Swiper Development](ui-js-components-swiper.md) + - Basic Components + - [Text Development](ui-js-components-text.md) + - [Input Development](ui-js-components-input.md) + - [Button Development](ui-js-components-button.md) + - [Picker Development](ui-js-components-picker.md) + - [Image Development](ui-js-components-images.md) + - [Image-animator Development](ui-js-components-image-animator.md) + - [Rating Development](ui-js-components-rating.md) + - [Slider Development](ui-js-components-slider.md) + - [Chart Development](ui-js-components-chart.md) + - [Switch Development](ui-js-components-switch.md) + - [Toolbar Development](ui-js-components-toolbar.md) + - [Menu Development](ui-js-components-menu.md) + - [Marquee Development](ui-js-components-marquee.md) + - [Qrcode Development](ui-js-components-qrcode.md) + - [Search Development](ui-js-components-search.md) + - Canvas Development + - [CanvasRenderingContext2D](ui-js-components-canvasrenderingcontext2d.md) + - [Path2D](ui-js-components-path2d.md) + - [OffscreenCanvas](ui-js-components-offscreencanvas.md) + - [Grid-container Development](ui-js-components-calendar.md) + - Svg + - [Basics](ui-js-components-svg-overview.md) + - [Graph Drawing](ui-js-components-svg-graphics.md) + - [Path Drawing](ui-js-components-svg-path.md) + - [Text Drawing](ui-js-components-svg-text.md) + - Animation Development Guidelines + - CSS Animation + - [Defining Attribute Style Animations](ui-js-animate-attribute-style.md) + - [Defining Animations with the transform Attribute](ui-js-animate-transform.md) + - [Defining Animations with the background-position Attribute](ui-js-animate-background-position-style.md) + - [Defining Animations for SVG Components](ui-js-animate-svg.md) + - JS Animation + - [Component Animation](ui-js-animate-component.md) + - Interpolator Animation + - [Animation Effect](ui-js-animate-dynamic-effects.md) + - [Animation Frame](ui-js-animate-frame.md) + - [Custom Components](ui-js-custom-components.md) +- TypeScript-based Declarative Development Paradigm + - [Overview](ui-ts-overview.md) + - Framework Overview + - File Organization + - [Directory Structure](ts-framework-directory.md) + - [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md) + - ["js" Tag](ts-framework-js-tag.md) + - Resource Access + - [Accessing Application Resources](ts-application-resource-access.md) + - [Accessing System Resources](ts-system-resource-access.md) + - [Media Resource Types](ts-media-resource-type.md) + - [Pixel Units](ts-pixel-units.md) + - [Types](ts-types.md) + - Declarative Syntax + - [Overview](ts-syntax-intro.md) + - General UI Description Specifications + - [Basic Concepts](ts-general-ui-concepts.md) + - Declarative UI Description Specifications + - [Configuration Without Parameters](ts-parameterless-configuration.md) + - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) + - [Attribute Configuration](ts-attribution-configuration.md) + - [Event Configuration](ts-event-configuration.md) + - [Child Component Configuration](ts-child-component-configuration.md) + - Componentization + - [@Component](ts-component-based-component.md) + - [@Entry](ts-component-based-entry.md) + - [@Preview](ts-component-based-preview.md) + - [@Builder](ts-component-based-builder.md) + - [@Extend](ts-component-based-extend.md) + - [@CustomDialog](ts-component-based-customdialog.md) + - [@Styles](ts-component-based-styles.md) + - About UI State Management + - [Basic Concepts](ts-ui-state-mgmt-concepts.md) + - Managing Component States + - [@State](ts-component-states-state.md) + - [@Prop](ts-component-states-prop.md) + - [@Link](ts-component-states-link.md) + - Managing Application States + - [AppStorage](ts-application-states-appstorage.md) + - [PersistentStorage](ts-application-states-apis-persistentstorage.md) + - [Environment](ts-application-states-apis-environment.md) + - Managing Other States + - [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md) + - [@Consume and @Provide](ts-other-states-consume-provide.md) + - [@Watch](ts-other-states-watch.md) + - About Rendering Control Syntax + - [if/else](ts-rending-control-syntax-if-else.md) + - [ForEach](ts-rending-control-syntax-foreach.md) + - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) + - About @Component + - [build Function](ts-function-build.md) + - [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md) + - [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md) + - [Component Creation and Re-initialization](ts-component-creation-re-initialization.md) + - [About Syntactic Sugar](ts-syntactic-sugar.md) + - Common Component Development Guidelines + - [Button](ui-ts-basic-components-button.md) + - [Web](ui-ts-components-web.md) + - Common Layout Development Guidelines + - [Flex Layout](ui-ts-layout-flex.md) + - [Grid Layout](ui-ts-layout-grid-container.md) + - [Media Query](ui-ts-layout-mediaquery.md) + - Experiencing the Declarative UI + - [Creating a Declarative UI Project](ui-ts-creating-project.md) + - [Getting to Know Components](ui-ts-components.md) + - [Creating a Simple Page](ui-ts-creating-simple-page.md) + - Defining Page Layout and Connection + - [Building a Food Data Model](ui-ts-building-data-model.md) + - [Building a Food Category List Layout](ui-ts-building-category-list-layout.md) + - [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md) + - [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md) diff --git a/en/application-dev/ui/arkui-overview.md b/en/application-dev/ui/arkui-overview.md index a5ba95916cfd3fad3e6eebe945ea6f22f6aa2aea..43bff6f16355673a8bc4b027680e427b9801d4d3 100644 --- a/en/application-dev/ui/arkui-overview.md +++ b/en/application-dev/ui/arkui-overview.md @@ -13,42 +13,20 @@ ArkUI is a UI development framework that provides what you'll need to develop ap - Page: the smallest unit for ArkUI application scheduling. You can design multiple pages for your application, manage their files on a per-page basis, and schedule page redirection through routing APIs, so as to implement decoupling of application functions. -## Key Capabilities - -- Diverse components: In addition to a wide range of basic components, such as components for text display, image display, and keypress interaction, ArkUI provides media components that support video playback. Better yet, it also provides polymorphic components, which can adapt to styles of different devices. - -- Flexible layouts: Creating a responsive UI in ArkUI is easy, with our carefully-designed layout approaches: Besides the classic flexible layout capability, you also have access to the list, grid, and atomic layouts that auto-adapt to screen resolutions. +## Key Features +- UI components: In addition to a wide range of basic components, such as components for text display, image display, and keypress interaction, ArkUI provides media components that support video playback. Better yet, it also provides polymorphic components, which can adapt to styles of different devices. +- Layout: Creating a responsive UI in ArkUI is easy, with our carefully-designed layout approaches: Besides the classic flexible layout capability, you also have access to the list, grid, and atomic layouts that auto-adapt to screen resolutions. - Animation: Apart from animations embedded in components, ArkUI offers additional animation features: attribute animation, transition animation, and custom animation. - -- UI interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability. - - Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts. - +- Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability. - Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style. +- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. - -## Development Paradigms - -ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. - - -### Web-like Development Paradigm - -The web-like development paradigm uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. It could be helpful if you are developing small- and medium-sized applications with simple UIs. - - -### Declarative Development Paradigm - -The declarative development paradigm uses the TypeScript programming language and extends the declarative UI syntax, providing UI drawing capabilities from three dimensions: component, animation, and state management. The programming mode used is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. With type annotations in TypeScript, you can enforce type checking at compile time. If you are developing large applications, the declarative development paradigm is more applicable. - - -### Web-like Development Paradigm vs. Declarative Development Paradigm - - | Development Paradigm | Language | UI Update Mode | Applicable To | Intended Audience | -| -------- | -------- | -------- | -------- | -------- | -| Web-like development paradigm | JavaScript | Data-driven | Applets and service widgets with simple UIs | Frontend web developers | -| Declarative development paradigm | Extended TypeScript (eTS) | Data-driven | Applications involving technological sophistication and teamwork | Mobile application and system application developers | +| Development Paradigm | Description | Applicable To | Intended Audience | +| -------- | -------- | -------- | -------- | +| Web-like development paradigm | Uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. | Small- and medium-sized applications and service widgets with simple UIs | Frontend web developers | +| Declarative development paradigm | Uses the TypeScript programming language and extends the declarative UI syntax, providing UI drawing capabilities from three dimensions: component, animation, and state management. The programming mode used is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. With type annotations in TypeScript, you can enforce type checking at compile time. | Applications involving technological sophistication and teamwork | Mobile application and system application developers | ### Framework Structure diff --git a/en/application-dev/ui/figures/en-us_image_0000001148858818.png b/en/application-dev/ui/figures/en-us_image_0000001148858818.png new file mode 100644 index 0000000000000000000000000000000000000000..3be38a7df454954c455b44bb1fbb6b2158be3785 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001148858818.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001167746622.png b/en/application-dev/ui/figures/en-us_image_0000001167746622.png new file mode 100644 index 0000000000000000000000000000000000000000..e53f6d7e1c8b3060ae000d78555ea0b33ffc97bf Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001167746622.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001168059158.png b/en/application-dev/ui/figures/en-us_image_0000001168059158.png new file mode 100644 index 0000000000000000000000000000000000000000..205d18f50424811f04dcecc1b6a95c52530c6527 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001168059158.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001168956332.png b/en/application-dev/ui/figures/en-us_image_0000001168956332.png new file mode 100644 index 0000000000000000000000000000000000000000..adb255e05d2f54161e79e0f0a21ddc6b04552793 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001168956332.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001190466492.png b/en/application-dev/ui/figures/en-us_image_0000001190466492.png new file mode 100644 index 0000000000000000000000000000000000000000..aebc1b5e3afbc74a161bdc481b1578ef79105a87 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001190466492.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001215645452.png b/en/application-dev/ui/figures/en-us_image_0000001215645452.png new file mode 100644 index 0000000000000000000000000000000000000000..21478ddee0ac2a56230eb67406ba7ddb4600ee74 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001215645452.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001215796030.png b/en/application-dev/ui/figures/en-us_image_0000001215796030.png new file mode 100644 index 0000000000000000000000000000000000000000..a449a54d3ebbb0fe35754a0b6191e090a9f57fb6 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001215796030.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001215965420.png b/en/application-dev/ui/figures/en-us_image_0000001215965420.png new file mode 100644 index 0000000000000000000000000000000000000000..69ab2b53dc50fbe5f146b336993f86bf1e4a5f24 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001215965420.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001217236574.png b/en/application-dev/ui/figures/en-us_image_0000001217236574.png new file mode 100644 index 0000000000000000000000000000000000000000..0b45eda696b180bb917b10db8eb803e7babd1538 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001217236574.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218108718.png b/en/application-dev/ui/figures/en-us_image_0000001218108718.png new file mode 100644 index 0000000000000000000000000000000000000000..2fd6c145acd07026766c368d2e20724b0d1f8a04 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218108718.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218259634.png b/en/application-dev/ui/figures/en-us_image_0000001218259634.png new file mode 100644 index 0000000000000000000000000000000000000000..a54bd7cd05accb496c691b2527b08b0a11cd8c66 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218259634.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218259636.png b/en/application-dev/ui/figures/en-us_image_0000001218259636.png new file mode 100644 index 0000000000000000000000000000000000000000..3d767cc276109fce015bb59bb0527b7830d23f54 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218259636.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218419614.png b/en/application-dev/ui/figures/en-us_image_0000001218419614.png new file mode 100644 index 0000000000000000000000000000000000000000..101f60e44760d98db7a904189f387e2b3557cf32 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218419614.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218419616.png b/en/application-dev/ui/figures/en-us_image_0000001218419616.png new file mode 100644 index 0000000000000000000000000000000000000000..746eb1f0ddc9ac1581f191b1e76d8d028dfd418e Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218419616.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218579606.png b/en/application-dev/ui/figures/en-us_image_0000001218579606.png new file mode 100644 index 0000000000000000000000000000000000000000..c8697767f19ae5cc5f7b30c4cbc2a23ffafb0844 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218579606.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218579608.png b/en/application-dev/ui/figures/en-us_image_0000001218579608.png new file mode 100644 index 0000000000000000000000000000000000000000..74526d5efee72c20ce09c731842c0d1c56159a97 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218579608.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218579610.png b/en/application-dev/ui/figures/en-us_image_0000001218579610.png new file mode 100644 index 0000000000000000000000000000000000000000..1f407b77a24e90c854f25472e37c97e1cd40287b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218579610.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739566.png b/en/application-dev/ui/figures/en-us_image_0000001218739566.png new file mode 100644 index 0000000000000000000000000000000000000000..4384ea3a2997c4417eee0fbe0e6475c4925b5c36 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218739566.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739568.png b/en/application-dev/ui/figures/en-us_image_0000001218739568.png new file mode 100644 index 0000000000000000000000000000000000000000..a66ff857ba7629951a39a1c2cc19c7b6fb43b9e1 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218739568.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739570.png b/en/application-dev/ui/figures/en-us_image_0000001218739570.png new file mode 100644 index 0000000000000000000000000000000000000000..006efca8f390adea7edb0b4f54609c04fd0bd098 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001218739570.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001222967800.png b/en/application-dev/ui/figures/en-us_image_0000001222967800.png new file mode 100644 index 0000000000000000000000000000000000000000..00964c1cfa5f006f2e8ac064133e23a2d8fc92aa Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001222967800.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683112.gif b/en/application-dev/ui/figures/en-us_image_0000001231683112.gif new file mode 100644 index 0000000000000000000000000000000000000000..8e64d09f33bcbba8117775ea6f5946cc4556d0c3 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683112.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683116.png b/en/application-dev/ui/figures/en-us_image_0000001231683116.png new file mode 100644 index 0000000000000000000000000000000000000000..11dac18df74e1fd4d09adc43bb264253294df23f Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683116.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683124.png b/en/application-dev/ui/figures/en-us_image_0000001231683124.png new file mode 100644 index 0000000000000000000000000000000000000000..d4301a19383a2abbfb7038275e59adc901046307 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683124.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683128.gif b/en/application-dev/ui/figures/en-us_image_0000001231683128.gif new file mode 100644 index 0000000000000000000000000000000000000000..52af9a2cddfa15e4f08358a0023f456b35d535c6 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683128.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683144.gif b/en/application-dev/ui/figures/en-us_image_0000001231683144.gif new file mode 100644 index 0000000000000000000000000000000000000000..cfe44e409c1ddf0f7a70b59367a7885033a2b42f Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683144.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683148.gif b/en/application-dev/ui/figures/en-us_image_0000001231683148.gif new file mode 100644 index 0000000000000000000000000000000000000000..353e2ffb9a84cba7616291730c7c0c670adc2b13 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683148.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683152.png b/en/application-dev/ui/figures/en-us_image_0000001231683152.png new file mode 100644 index 0000000000000000000000000000000000000000..acdf7a05ea58d00687571fbcb496372b64ab1c87 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683152.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683156.png b/en/application-dev/ui/figures/en-us_image_0000001231683156.png new file mode 100644 index 0000000000000000000000000000000000000000..8df470cc4c0e146972977c1b7dadecc8cbc67838 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683156.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683164.gif b/en/application-dev/ui/figures/en-us_image_0000001231683164.gif new file mode 100644 index 0000000000000000000000000000000000000000..2dd2706317ddfaf317fc2abfc5cbb0a5a5a927cf Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683164.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231683172.png b/en/application-dev/ui/figures/en-us_image_0000001231683172.png new file mode 100644 index 0000000000000000000000000000000000000000..5c1dc425e1a607a846d3884a9118387accb031a4 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231683172.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843076.gif b/en/application-dev/ui/figures/en-us_image_0000001231843076.gif new file mode 100644 index 0000000000000000000000000000000000000000..b8e2940f1660157ba412beac4db6614b4714d599 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843076.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843084.png b/en/application-dev/ui/figures/en-us_image_0000001231843084.png new file mode 100644 index 0000000000000000000000000000000000000000..bd0b2b46d44aced7d075ba36196aa02c43b362c3 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843084.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843088.gif b/en/application-dev/ui/figures/en-us_image_0000001231843088.gif new file mode 100644 index 0000000000000000000000000000000000000000..f7f05ac39da2bd2f04a7257e1c36eb87ad811783 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843088.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843096.png b/en/application-dev/ui/figures/en-us_image_0000001231843096.png new file mode 100644 index 0000000000000000000000000000000000000000..b9d99e465fd01f8a427bd2c0b7758045241b8227 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843096.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843100.gif b/en/application-dev/ui/figures/en-us_image_0000001231843100.gif new file mode 100644 index 0000000000000000000000000000000000000000..88c62f08669f2ec3533db708d49d18a069501644 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843100.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843104.png b/en/application-dev/ui/figures/en-us_image_0000001231843104.png new file mode 100644 index 0000000000000000000000000000000000000000..0a5d725eba5254e9a489204bf2a7c06170aa3a2e Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843104.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843116.gif b/en/application-dev/ui/figures/en-us_image_0000001231843116.gif new file mode 100644 index 0000000000000000000000000000000000000000..d6a46140a41a112790210c58502fbc3df6e65f20 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843116.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843128.gif b/en/application-dev/ui/figures/en-us_image_0000001231843128.gif new file mode 100644 index 0000000000000000000000000000000000000000..f6469e9e80464270e28bc6c682ff3e9bf8420a5f Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843128.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001231843132.gif b/en/application-dev/ui/figures/en-us_image_0000001231843132.gif new file mode 100644 index 0000000000000000000000000000000000000000..aba5bd689955bb90c779ba3c231d698d9fb53eac Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001231843132.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232002968.png b/en/application-dev/ui/figures/en-us_image_0000001232002968.png new file mode 100644 index 0000000000000000000000000000000000000000..b9c766a3189861fae9fbcf07f5912bef0d8562c8 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232002968.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232002972.gif b/en/application-dev/ui/figures/en-us_image_0000001232002972.gif new file mode 100644 index 0000000000000000000000000000000000000000..8a6952f9e8398edabbe28e8daace7c6be172531a Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232002972.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232002988.gif b/en/application-dev/ui/figures/en-us_image_0000001232002988.gif new file mode 100644 index 0000000000000000000000000000000000000000..f62f884f93ef38a79a6a4653f8681b765cc87aa9 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232002988.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003000.gif b/en/application-dev/ui/figures/en-us_image_0000001232003000.gif new file mode 100644 index 0000000000000000000000000000000000000000..9983db70e3477057acdcbbdaba56dea290f6a303 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003000.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003004.gif b/en/application-dev/ui/figures/en-us_image_0000001232003004.gif new file mode 100644 index 0000000000000000000000000000000000000000..6c67ff8bc8394cddb79b5ac4d1b2c130ae6a6bb8 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003004.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003008.gif b/en/application-dev/ui/figures/en-us_image_0000001232003008.gif new file mode 100644 index 0000000000000000000000000000000000000000..b5bce1b8e09e0c47231c11250c6d676806bcd53c Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003008.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003012.gif b/en/application-dev/ui/figures/en-us_image_0000001232003012.gif new file mode 100644 index 0000000000000000000000000000000000000000..260966e4fe59e4e6f80b501251f478bbb7126dce Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003012.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003020.gif b/en/application-dev/ui/figures/en-us_image_0000001232003020.gif new file mode 100644 index 0000000000000000000000000000000000000000..ba4c74a1f562b0abe65681e30f3228f54cb53a74 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003020.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003024.gif b/en/application-dev/ui/figures/en-us_image_0000001232003024.gif new file mode 100644 index 0000000000000000000000000000000000000000..491e4d141faffa0cf052d3adfb32eaa3fda61c8e Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003024.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232003028.gif b/en/application-dev/ui/figures/en-us_image_0000001232003028.gif new file mode 100644 index 0000000000000000000000000000000000000000..7293aff8d5971a6b026c751570eefbca029bb06b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232003028.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162284.gif b/en/application-dev/ui/figures/en-us_image_0000001232162284.gif new file mode 100644 index 0000000000000000000000000000000000000000..8b0e1d5a97c59fb1b0b1b243d5b0a30f1b8824e2 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162284.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162288.png b/en/application-dev/ui/figures/en-us_image_0000001232162288.png new file mode 100644 index 0000000000000000000000000000000000000000..d4d117430d11520fdcbe3cd1343182a7f169c7fe Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162288.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162292.gif b/en/application-dev/ui/figures/en-us_image_0000001232162292.gif new file mode 100644 index 0000000000000000000000000000000000000000..3b5681fe5f430af62ef6d94b37bf6cc5a2a2ee58 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162292.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162312.gif b/en/application-dev/ui/figures/en-us_image_0000001232162312.gif new file mode 100644 index 0000000000000000000000000000000000000000..91d6134b97b6e9073540ee7b06ecf6e31952c9b5 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162312.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162316.png b/en/application-dev/ui/figures/en-us_image_0000001232162316.png new file mode 100644 index 0000000000000000000000000000000000000000..03a4a72905b6e852a00cdbbe17918cdeda28e5bf Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162316.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162320.gif b/en/application-dev/ui/figures/en-us_image_0000001232162320.gif new file mode 100644 index 0000000000000000000000000000000000000000..d8f8221489fd409670bfa9b3d0694a54552d5cbd Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162320.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162324.png b/en/application-dev/ui/figures/en-us_image_0000001232162324.png new file mode 100644 index 0000000000000000000000000000000000000000..7b3260b58addc8949c1ed409fb183ac91f986ebf Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162324.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162328.gif b/en/application-dev/ui/figures/en-us_image_0000001232162328.gif new file mode 100644 index 0000000000000000000000000000000000000000..fae5d684f722d9f65d55fdfc6b249c4322185cfe Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162328.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001232162340.png b/en/application-dev/ui/figures/en-us_image_0000001232162340.png new file mode 100644 index 0000000000000000000000000000000000000000..86187142668379cc81fcc9f163e3218a078cc8cc Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001232162340.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001235146483.png b/en/application-dev/ui/figures/en-us_image_0000001235146483.png new file mode 100644 index 0000000000000000000000000000000000000000..0bebd24640b896d465c3f130dcf69f10abab3def Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001235146483.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001235626467.png b/en/application-dev/ui/figures/en-us_image_0000001235626467.png new file mode 100644 index 0000000000000000000000000000000000000000..189cc8a1e959a162f22d1b9b0dd9573614cb0673 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001235626467.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001260373911.png b/en/application-dev/ui/figures/en-us_image_0000001260373911.png new file mode 100644 index 0000000000000000000000000000000000000000..223fab73b7c40f7b1bdc5cc05d2d8a91589b88d4 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001260373911.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001260555857.png b/en/application-dev/ui/figures/en-us_image_0000001260555857.png new file mode 100644 index 0000000000000000000000000000000000000000..e63baa89d7b6f4c816ca6e4386851498d47eac36 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001260555857.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001261605867.png b/en/application-dev/ui/figures/en-us_image_0000001261605867.png new file mode 100644 index 0000000000000000000000000000000000000000..096d7f530cc2d82391be453a7a5dbe659ba15513 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001261605867.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001262748569.png b/en/application-dev/ui/figures/en-us_image_0000001262748569.png new file mode 100644 index 0000000000000000000000000000000000000000..7af6c8cc92db32d22b3f2022ab567ca9c8978b63 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001262748569.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263019457.png b/en/application-dev/ui/figures/en-us_image_0000001263019457.png new file mode 100644 index 0000000000000000000000000000000000000000..dea13c34b80626c7fe1a0036afbe69d5f236910c Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263019457.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263019461.png b/en/application-dev/ui/figures/en-us_image_0000001263019461.png new file mode 100644 index 0000000000000000000000000000000000000000..b79b7923adca0d6e2a211c29ef0d34b70bf02583 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263019461.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263019463.png b/en/application-dev/ui/figures/en-us_image_0000001263019463.png new file mode 100644 index 0000000000000000000000000000000000000000..10a7a63c5c41b636fa5a61b5a13ad7ed97c3d1fb Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263019463.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263074739.png b/en/application-dev/ui/figures/en-us_image_0000001263074739.png new file mode 100644 index 0000000000000000000000000000000000000000..e2f0ff5761d3c5a19a300f7c891a717e13c2374d Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263074739.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263139409.png b/en/application-dev/ui/figures/en-us_image_0000001263139409.png new file mode 100644 index 0000000000000000000000000000000000000000..395631e2ed4572806bd93bcdb8ff86486e0b5bdf Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263139409.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263139411.png b/en/application-dev/ui/figures/en-us_image_0000001263139411.png new file mode 100644 index 0000000000000000000000000000000000000000..3e481248c0e16f3311644a35fa3c71269a3e7877 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263139411.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263259399.png b/en/application-dev/ui/figures/en-us_image_0000001263259399.png new file mode 100644 index 0000000000000000000000000000000000000000..dc4a266c02708116362da21577d5b1e582a011fd Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263259399.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263259401.png b/en/application-dev/ui/figures/en-us_image_0000001263259401.png new file mode 100644 index 0000000000000000000000000000000000000000..b233260ab8bf15c918389226a7773541399311a4 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263259401.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263339459.png b/en/application-dev/ui/figures/en-us_image_0000001263339459.png new file mode 100644 index 0000000000000000000000000000000000000000..99e18123d53b88779948b34c6c566005d989358b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263339459.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263339461.png b/en/application-dev/ui/figures/en-us_image_0000001263339461.png new file mode 100644 index 0000000000000000000000000000000000000000..183d9468ca3901183b3fa55facbc976418e7a5f1 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001263339461.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803133.png b/en/application-dev/ui/figures/en-us_image_0000001275803133.png new file mode 100644 index 0000000000000000000000000000000000000000..ffe4b54ecb499aa26d5b48eea623434985646292 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803133.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803137.gif b/en/application-dev/ui/figures/en-us_image_0000001275803137.gif new file mode 100644 index 0000000000000000000000000000000000000000..c80d86b0508ad15cd944314d0a2b3b59dcd9bcd6 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803137.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803145.png b/en/application-dev/ui/figures/en-us_image_0000001275803145.png new file mode 100644 index 0000000000000000000000000000000000000000..45a96cb24680a3cf2cdd91d315314822701c4176 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803145.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803149.png b/en/application-dev/ui/figures/en-us_image_0000001275803149.png new file mode 100644 index 0000000000000000000000000000000000000000..5a0fa14321998b5fc33b0965dcc0ca0ae315dd09 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803149.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803153.gif b/en/application-dev/ui/figures/en-us_image_0000001275803153.gif new file mode 100644 index 0000000000000000000000000000000000000000..fec6caa122160183c3cc049e803710301fd63d9f Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803153.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803169.gif b/en/application-dev/ui/figures/en-us_image_0000001275803169.gif new file mode 100644 index 0000000000000000000000000000000000000000..439eea01e278280086248901e4ac51923d5e4979 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803169.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803173.gif b/en/application-dev/ui/figures/en-us_image_0000001275803173.gif new file mode 100644 index 0000000000000000000000000000000000000000..abec4486ad5f444b32aa20b88a3a6d1975254cd0 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803173.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803177.gif b/en/application-dev/ui/figures/en-us_image_0000001275803177.gif new file mode 100644 index 0000000000000000000000000000000000000000..c310e7cfd714246b95eab7f030c33490bef98d86 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803177.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803181.gif b/en/application-dev/ui/figures/en-us_image_0000001275803181.gif new file mode 100644 index 0000000000000000000000000000000000000000..9b0bdbf57b14db63cf4935e1a578e78da5380a8a Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803181.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803189.gif b/en/application-dev/ui/figures/en-us_image_0000001275803189.gif new file mode 100644 index 0000000000000000000000000000000000000000..ab6d5e3bde1e3218eaa1156137c7fd6ffc298882 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803189.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275803193.png b/en/application-dev/ui/figures/en-us_image_0000001275803193.png new file mode 100644 index 0000000000000000000000000000000000000000..a5db8f42d350aa79613ac657db2630d0d60d3d3c Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275803193.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275922965.gif b/en/application-dev/ui/figures/en-us_image_0000001275922965.gif new file mode 100644 index 0000000000000000000000000000000000000000..0c3c7fccb059ad03b084728307963082dc6f8365 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275922965.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275922969.gif b/en/application-dev/ui/figures/en-us_image_0000001275922969.gif new file mode 100644 index 0000000000000000000000000000000000000000..ea5aa768532ea01f6828bd6bf211c4c2fe1e0d22 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275922969.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275922977.gif b/en/application-dev/ui/figures/en-us_image_0000001275922977.gif new file mode 100644 index 0000000000000000000000000000000000000000..13c21f4cbd450e5670bfeaf1041826fe3cc07f06 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275922977.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275922997.gif b/en/application-dev/ui/figures/en-us_image_0000001275922997.gif new file mode 100644 index 0000000000000000000000000000000000000000..30dbdba7bf2036b51395507d4a1996b5adaf5436 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275922997.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275923005.gif b/en/application-dev/ui/figures/en-us_image_0000001275923005.gif new file mode 100644 index 0000000000000000000000000000000000000000..8bd5e2f2f7f60ad28107af3dc67ff5ee75af2b0d Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275923005.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275923017.png b/en/application-dev/ui/figures/en-us_image_0000001275923017.png new file mode 100644 index 0000000000000000000000000000000000000000..08f11bc53e9a0e6430b06ae77fde645585ee711b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275923017.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001275923021.gif b/en/application-dev/ui/figures/en-us_image_0000001275923021.gif new file mode 100644 index 0000000000000000000000000000000000000000..5813dfac315791a87d9bd9c70a9587e6b779614c Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001275923021.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003481.gif b/en/application-dev/ui/figures/en-us_image_0000001276003481.gif new file mode 100644 index 0000000000000000000000000000000000000000..5198c5a81cf4427f1014489336d730d846e15f9d Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003481.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003485.gif b/en/application-dev/ui/figures/en-us_image_0000001276003485.gif new file mode 100644 index 0000000000000000000000000000000000000000..28b2a163673a71e95a40284d2b045005594623e6 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003485.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003489.gif b/en/application-dev/ui/figures/en-us_image_0000001276003489.gif new file mode 100644 index 0000000000000000000000000000000000000000..0554bd02b6ce8c1d835a3cde3bf2427d8dd15bda Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003489.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003501.gif b/en/application-dev/ui/figures/en-us_image_0000001276003501.gif new file mode 100644 index 0000000000000000000000000000000000000000..aa9bba2a489f516d80f7eed07bc67e549d1a25c3 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003501.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003505.gif b/en/application-dev/ui/figures/en-us_image_0000001276003505.gif new file mode 100644 index 0000000000000000000000000000000000000000..1b6a6d7cce2951696d624ea3cf645570231bc0d7 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003505.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003513.gif b/en/application-dev/ui/figures/en-us_image_0000001276003513.gif new file mode 100644 index 0000000000000000000000000000000000000000..d93306857a1ce4a304bc83a664ee270105f39017 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003513.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003517.gif b/en/application-dev/ui/figures/en-us_image_0000001276003517.gif new file mode 100644 index 0000000000000000000000000000000000000000..407541949a9a7d9308ca61be4dfc2ecf91709d49 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003517.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003525.gif b/en/application-dev/ui/figures/en-us_image_0000001276003525.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d4ed8967a4f4d4d163c560536ee537feddef49a Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003525.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003537.png b/en/application-dev/ui/figures/en-us_image_0000001276003537.png new file mode 100644 index 0000000000000000000000000000000000000000..1898cb7e3d137e02211afb6425147bc4754600d5 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003537.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003541.gif b/en/application-dev/ui/figures/en-us_image_0000001276003541.gif new file mode 100644 index 0000000000000000000000000000000000000000..7d8da86f2f1cf71ca9bc5d6cb65564bb64ae5fd1 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276003541.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276162713.gif b/en/application-dev/ui/figures/en-us_image_0000001276162713.gif new file mode 100644 index 0000000000000000000000000000000000000000..531e20ab79714795da80341f363a71f5c426f034 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276162713.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276162717.gif b/en/application-dev/ui/figures/en-us_image_0000001276162717.gif new file mode 100644 index 0000000000000000000000000000000000000000..1167fd1b33a3f955c037e59aff6b86275605bdfd Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276162717.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276162725.png b/en/application-dev/ui/figures/en-us_image_0000001276162725.png new file mode 100644 index 0000000000000000000000000000000000000000..a018ed2562de8d5f23c7422f451b763086a72390 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276162725.png differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276162745.gif b/en/application-dev/ui/figures/en-us_image_0000001276162745.gif new file mode 100644 index 0000000000000000000000000000000000000000..ac5857ad2e4888bfda20044fb84dbd100ed68d5b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276162745.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276162773.gif b/en/application-dev/ui/figures/en-us_image_0000001276162773.gif new file mode 100644 index 0000000000000000000000000000000000000000..9e313e1e87059572aa036b06881381da7b070641 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001276162773.gif differ diff --git a/en/application-dev/ui/js-framework-multiple-languages.md b/en/application-dev/ui/js-framework-multiple-languages.md index 0405f3f9a0a22cfb83c713356af6f11e4cd33580..00b7ba08682e9de4027872089dc5b5decb39ada0 100644 --- a/en/application-dev/ui/js-framework-multiple-languages.md +++ b/en/application-dev/ui/js-framework-multiple-languages.md @@ -20,19 +20,19 @@ language[-script-region].json The following table describes the requirements for the qualifiers of resource file names. - Table1 Requirements for qualifier values +Table 1 Requirements for qualifier values -| Qualifier Type | Description and Value Range | +| Qualifier Type | Description and Value Range | | -------- | -------- | -| Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, zh indicates Chinese, en indicates English, and mai indicates Maithili.
For details about the value range, refer to ISO 639 (codes for the representation of names of languages). | -| Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, Hans indicates simplified Chinese and Hant indicates traditional Chinese.
For details about the value range, refer to ISO 15924 (codes for the representation of names of scripts). | -| Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, CN indicates China and GB indicates the United Kingdom.
For details about the value range, refer to ISO 3166-1 (codes for the representation of names of countries and their subdivisions). | +| Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, zh indicates Chinese, en indicates English, and mai indicates Maithili.
For details about the value range, refer to ISO 639 (codes for the representation of names of languages). | +| Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, Hans indicates simplified Chinese and Hant indicates traditional Chinese.
For details about the value range, refer to ISO 15924 (codes for the representation of names of scripts). | +| Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, CN indicates China and GB indicates the United Kingdom.
For details about the value range, refer to ISO 3166-1 (codes for the representation of names of countries and their subdivisions). | If there is no resource file of the locale that matches the system language, content in the en-US.json file will be used by default. The format of the resource file content is as follows: - en-US.json +**en-US.json** ``` { @@ -55,8 +55,7 @@ Different languages have different matching rules for singular and plural forms. The following example takes en-US.json and ar-AE.json as examples: - -en-US.json +**en-US.json** ``` @@ -97,18 +96,18 @@ Multi-language syntax used on application development pages (including simple fo - Simple formatting Use the $t function to reference to resources of different locales. The $t function is available for both .hml and .js files. The system displays content based on a resource file path specified via $t and the specified resource file whose locale matches the current system language. - Table2 Simple formatting + Table 2 Simple formatting | Attribute | Type | Parameter | Mandatory | Description | | -------- | -------- | -------- | -------- | -------- | | $t | Function | See Table3 | Yes | Sets the parameters based on the system language, for example, this.$t('strings.hello'). | - Table3 $t function parameters + Table 3 $t function parameters - | Parameter | Type | Mandatory | Description | + | Parameter | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | path | string | Yes | Path of the language resource key | - | params | Array\|Object | No | Content used to replace placeholders during runtime. There are two types of placeholders available:
- Named placeholder, for example, {name}. The actual content must be of the object type, for example, $t('strings.object', { name: 'Hello world' }).
- Digit placeholder, for example, {0}. The actual content must be of the array type, for example, $t('strings.array', ['Hello world']. | + | path | string | Yes | Path of the language resource key | + | params | Array\|Object | No | Content used to replace placeholders during runtime. There are two types of placeholders available:
- Named placeholder, for example, {name}. The actual content must be of the object type, for example, \```$t('strings.object', {name:'Hello world'})```.
- Digit placeholder, for example, {0}. The actual content must be of the array type, for example, \```$t('strings.array', [Hello world']```. | - Example code for simple formatting @@ -156,18 +155,18 @@ Multi-language syntax used on application development pages (including simple fo ``` - Singular-plural formatting - Table4 Singular-plural formatting + Table 4 Singular-plural formatting | Attribute | Type | Parameter | Mandatory | Description | | -------- | -------- | -------- | -------- | -------- | - | $tc | Function | See Table 5. | Yes | Converts between the singular and plural forms based on the system language, for example, this.$tc('strings.people').
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:
> The resource content is distinguished by the following JSON keys: zero, one, two, few, many, and other. | + | $tc | Function | See Table 5. | Yes | Converts between the singular and plural forms based on the system language, for example, this.$tc('strings.people').
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The resource content is distinguished by the following JSON keys: zero, one, two, few, many, and other. | - Table5 $tc function parameters + Table 5 $tc function parameters - | Parameter | Type | Mandatory | Description | + | Parameter | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | - | path | string | Yes | Path of the language resource key | - | count | number | Yes | Number | + | path | string | Yes | Path of the language resource key | + | count | number | Yes | Number | - Sample code for singular-plural formatting diff --git a/en/application-dev/ui/ui-js-building-ui-event.md b/en/application-dev/ui/ui-js-building-ui-event.md index 02b1d1a13b6358ce5cef34373bdbe971b345a3fb..f963c80bd2ae34db7d9c1878a823c89b8dd3a1c3 100644 --- a/en/application-dev/ui/ui-js-building-ui-event.md +++ b/en/application-dev/ui/ui-js-building-ui-event.md @@ -1,29 +1,24 @@ -# Defining Events +# Defining Gesture Events +A gesture represents a semantic action (for example, tap, drag, or longpress) that can trigger one or more events. A gesture lifecycle may consist of multiple events from the start to the end of the gesture. Supported events are as follows: -Events mainly include gesture events for touchscreen devices. +**Touch** +- **touchstart**: Triggered when the touch starts -## Gesture Events +- **touchmove**: Triggered when the touch moves -A gesture represents a semantic action (for example, tap, drag, or longpress) that can trigger one or more events. A gesture lifecycle may consist of multiple events from the start to the end of the gesture. Supported events: +- **touchcancel**: Triggered when the touch is interrupted, for example, by an incoming call notification or pop-up message - Touch -- touchstart: Triggered when the touch starts +- **touchend**: Triggered when the touch ends -- touchmove: Triggered when the touch moves +**Click** -- touchcancel: Triggered when the touch is interrupted, for example, by an incoming call notification or pop-up message +**click**: Triggered when a user taps the screen quickly. -- touchend: Triggered when the touch ends +**Longpress** -Click - -click: Triggered when a user taps the screen quickly. - -Longpress - -longpress: Triggered when a user keeps tapping the screen at the same position for a while. +**longpress**: Triggered when a user keeps tapping the screen at the same position for a while. The following is an example: diff --git a/en/application-dev/ui/ui-js-component-tabs.md b/en/application-dev/ui/ui-js-component-tabs.md index 0e20aaea35129a98b219d5eaac252dfda7e420d4..7986d52513a4e62c9f6a9018c9474174c13e7937 100644 --- a/en/application-dev/ui/ui-js-component-tabs.md +++ b/en/application-dev/ui/ui-js-component-tabs.md @@ -1,19 +1,19 @@ # <tabs> Development -The <tabs> component is a common UI component for navigation. It allows quick access to different functions of an app. For details, see [tabs](../reference/arkui-js/js-components-container-tabs.md). +The **<tabs>** component is a common UI component for navigation. It allows quick access to different functions of an app. For details, see [tabs](../reference/arkui-js/js-components-container-tabs.md). ## Creating Tabs -Create a <tabs> component in the .hml file under pages/index. +Create a **<tabs>** component in the .hml file under **pages/index**. ```
- + item1 item2 @@ -25,7 +25,7 @@ Create a <tabs> component in the .hml file under pages/index. content2
- + ``` @@ -51,13 +51,13 @@ Create a <tabs> component in the .hml file under pages/index. ## Setting the Tabs Orientation -By default, the active tab of a <tabs> component is the one with the specified index. To show the <tabs> vertically, set the vertical attribute to true. +By default, the active tab of a **<tabs>** component is the one with the specified **index**. To show the **<tabs>** vertically, set the **vertical** attribute to **true**. ```
- + item1 item2 @@ -76,7 +76,7 @@ By default, the active tab of a <tabs> component is the one with the speci ![en-us_image_0000001222967756](figures/en-us_image_0000001222967756.gif) -Set the mode attribute to enable the child components of the to be evenly distributed. Set the scrollable attribute to disable scrolling of the . +Set the **mode** attribute to enable the child components of the **<tab-bar>** to be evenly distributed. Set the **scrollable** attribute to disable scrolling of the **<tab-content>**. ``` @@ -102,9 +102,9 @@ Set the mode attribute to enable the child components of the to be eve ![en-us_image_0000001267647857](figures/en-us_image_0000001267647857.gif) -## Setting the Style +## Setting Styles - Set the background color, border, and tab-content layout of the <tabs> component. + Set the background color, border, and tab-content layout of the **<tabs>** component. ``` @@ -150,7 +150,8 @@ Set the mode attribute to enable the child components of the to be eve margin-top: 10px; height: 300px; color: blue; - justify-content: center; align-items: center; + justify-content: center; + align-items: center; } ``` @@ -159,13 +160,13 @@ Set the mode attribute to enable the child components of the to be eve ## Displaying the Tab Index -Add the change event for the <tabs> component to display the index of the current tab after tab switching. +Add the **change** event for the **<tabs>** component to display the index of the current tab after tab switching. ```
- + item1 item2 @@ -198,15 +199,15 @@ export default { ![en-us_image_0000001222807772](figures/en-us_image_0000001222807772.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - A <tabs> can wrap at most one [](../reference/arkui-js/js-components-container-tab-bar.md) and at most one [](../reference/arkui-js/js-components-container-tab-content.md). +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - A **<tabs>** can wrap at most one [**<tab-bar>**](../reference/arkui-js/js-components-container-tab-bar.md) and at most one [**<tab-content>**](../reference/arkui-js/js-components-container-tab-content.md). ## Example Scenario In this example, you can switch between tabs and the active tab has the title text in red with an underline below. -Use the <tabs>, , and components to implement tab switching. Then define the arrays and attributes. Add the change event to change the attribute values in the arrays so that the active tab has a different font color and an underline. +Use the **<tabs>**, **<tab-bar>**, and **<tab-content>** components to implement tab switching. Then define the arrays and attributes. Add the **change** event to change the attribute values in the arrays so that the active tab has a different font color and an underline. ``` diff --git a/en/application-dev/ui/ui-js-components-button.md b/en/application-dev/ui/ui-js-components-button.md index 1507ce9c9843bb535efbb8cbd8ebafde66bd93e5..3911378bdee4244218295152478370c746ee87cc 100644 --- a/en/application-dev/ui/ui-js-components-button.md +++ b/en/application-dev/ui/ui-js-components-button.md @@ -1,12 +1,12 @@ # <button> Development -The<button>component can be used to set a capsule, circle, text, arc, or download button. For details, see [button](../reference/arkui-js/js-components-basic-button.md). +The **<button>** component can be used to set a capsule, circle, text, arc, or download button. For details, see [button](../reference/arkui-js/js-components-basic-button.md). -## Creating a <button> Component +## Creating a <button> Component -Create a <button> component in the .hml file under pages/index. +Create a **<button>** component in the .hml file under **pages/index**. ``` @@ -20,6 +20,8 @@ Create a <button> component in the .hml file under pages/index. ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -32,7 +34,9 @@ Create a <button> component in the .hml file under pages/index. ## Setting the Button Type -Set the type attribute of the <input> component to button, date, or any of the supported values. +Set the **type** attribute of the **<input>** component to **button**, **date**, or any of the supported values. + + ``` @@ -42,9 +46,13 @@ Set the type attribute of the <input> component to button, date, or any of
``` + + ``` /* xxx.css */ .container { + width: 100%; + height: 100%; background-color: #F1F3F5; flex-direction: column; align-items: center; @@ -70,17 +78,19 @@ Set the type attribute of the <input> component to button, date, or any of ![en-us_image_0000001222967744](figures/en-us_image_0000001222967744.png) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > - For capsule buttons, border-related styles are not supported. > > - For circle buttons, text-related styles are not supported. > -> - For text buttons, the text size is adaptive, and radius, width, and height cannot be set. The background-color style is not supported when the background is completely transparent. +> - For text buttons, the text size is adaptive, and **radius**, **width**, and **height** cannot be set. The **background-color** style is not supported when the background is completely transparent. > -> - If the icon used by the<button>component is from the cloud, you must declare the ohos.permission.INTERNET permission in the config.json file under the resources folder. +> - If the icon used by the **<button>** component is from the cloud, you must declare the **ohos.permission.INTERNET** permission in the **config.json** file under the **resources** folder. + + +Sample code for declaring the **ohos.permission.INTERNET** permission in the **config.json** file under the **resources** folder: -Sample code for declaring the ohos.permission.INTERNET permission in the config.json file under the resources folder: ``` @@ -94,7 +104,7 @@ Sample code for declaring the ohos.permission.INTERNET permission in the config. ## Showing the Download Progress -Add the progress method to the<button>component to display the download progress in real time. +Add the **progress** method to the **<button>** component to display the download progress in real time. ``` @@ -171,15 +181,16 @@ export default { ![en-us_image_0000001223287652](figures/en-us_image_0000001223287652.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> -> The setProgress method supports only buttons of the download type. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The **setProgress** method supports only buttons of the download type. ## Example Scenario Switch between the button types for different types of text. + + ```
@@ -197,6 +208,8 @@ Switch between the button types for different types of text.
``` + + ``` /* xxx.css */ .container { @@ -243,6 +256,8 @@ Switch between the button types for different types of text. } ``` + + ``` // xxx.js export default { diff --git a/en/application-dev/ui/ui-js-components-calendar.md b/en/application-dev/ui/ui-js-components-calendar.md new file mode 100644 index 0000000000000000000000000000000000000000..0f1d7fb32e2723899ff8094f1da1921c2c2ce7d5 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-calendar.md @@ -0,0 +1,244 @@ +# <grid-container> Development + + +The **<grid-container>** component is the root container of the grid layout. Within the root container, you can use **<grid-row>** and **<grid-col>** for the grid layout. For details, see [grid-container](../reference/arkui-js/js-components-grid-container.md). + + +## Creating a <grid-container> Component + +Create a **<grid-container>** component in the .hml file under **pages/index** and add a [**<grid-row>**](../reference/arkui-js/js-components-grid-row.md) child component. + + +``` + +
+ + + + + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + width: 100%; + justify-content: center; + align-items: center; +} +``` + +![en-us_image_0000001276162725](figures/en-us_image_0000001276162725.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> **<grid-container>** supports only **<grid-row>** as a child component. + + +## Methods + +Click the **<grid-container>** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**). + + +``` + +
+ + + + + + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + width: 100%; + justify-content: center; + align-items: center; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + data:{ + gutterWidth:'', + columnWidth:'', + columns:'', + }, + getColumns(){ + this.$element('mygrid').getColumnWidth((result)=>{ + this.columnWidth = result; + }) + this.$element('mygrid').getGutterWidth((result)=>{ + this.gutterWidth = result; + }) + this.$element('mygrid').getColumns((result)=>{ + this.columns= result; + }) + setTimeout(()=>{ + prompt.showToast({duration:5000,message:'columnWidth:'+this.columnWidth+',gutterWidth:'+ + this.gutterWidth+',getColumns:'+this.columns}) + }) + }, + getSizeType(){ + this.$element('mygrid').getSizeType((result)=>{ + prompt.showToast({duration:2000,message:'get size type:'+result}) + }) + }, +} +``` + +![en-us_image_0000001231843088](figures/en-us_image_0000001231843088.gif) + + +## Adding <grid-col> + +After adding a **<grid-row>** child component to **<grid-container>**, add a **<grid-col>** child component to **<grid-row>** to form a layout. + + +``` + +
+ + + +
+ top +
+
+
+ + +
+ left +
+
+ +
+ right +
+
+
+ + +
+ bottom +
+
+
+
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + width: 100%; + justify-content: center; + align-items: center; +} +text{ + color: white; + font-size: 40px; + +``` + +![en-us_image_0000001231683124](figures/en-us_image_0000001231683124.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> **<grid-row>** supports only **<grid-col>** as a child component. You can add content only to **<grid-col>**. + + +## Example Scenario + +In this example, the content in the list is output cyclically to create a grid layout. When the user pulls down the screen, the **refresh** method is triggered. In this case, a piece of data is added to the list and **setTimeout** is set to refresh the request data. + + +``` + +
+ + + + +
+ +
+
+ +
+ image{{item.id}} +
+
+
+
+
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + width: 100%; +} +text{ + color: #0a0aef; + font-size: 60px; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + data:{ + list:[ + {src:'common/images/1.png',id:'1'}, + {src:'common/images/2.png',id:'2'}, + {src:'common/images/3.png',id:'3'} + ], + fresh:false + }, + refresh(e) { + prompt.showToast({ + message: 'refreshing' + }) + var that = this; + that.fresh = e.refreshing; + setTimeout(function () { + that.fresh = false; + that.list.unshift({src: 'common/images/4.png',id:'4'}); + prompt.showToast({ + message: 'succeed' + }) + }, 2000) + } +} +``` + + +![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif) diff --git a/en/application-dev/ui/ui-js-components-canvas.md b/en/application-dev/ui/ui-js-components-canvas.md new file mode 100644 index 0000000000000000000000000000000000000000..87b813cca0bae6f27a417f43b81f03f098350a35 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-canvas.md @@ -0,0 +1,121 @@ +# <canvas> Development + + +The **<canvas>** component provides a canvas for drawing customized graphics. For details, see [canvas](../reference/arkui-js/js-components-canvas-canvas.md). + + +## Creating a <canvas> Component + +Create a **<canvas>** component in the .hml file under **pages/index**. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + background-color: #00ff73; +} +``` + +![en-us_image_0000001232162316](figures/en-us_image_0000001232162316.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The default background color of the **<canvas>** component is the same as that of the parent component. +> +> - The default width and height of **<canvas>** are 300 px and 150 px, respectively. + + +## Adding Styles + +Set **width**, **height**, **background-color**, and **border** of the **<canvas>** component. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 500px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +``` + +![en-us_image_0000001231843104](figures/en-us_image_0000001231843104.png) + + +## Adding Events + +Add the long press event to the **<canvas>** component. When the event is triggered, the value of **dataUrl** (image information returned by the **toDataURL** method) of the **<canvas>** component can be obtained and printed in the text area below. + + +``` + +
+ + dataURL + {{dataURL}} +
+``` + + +``` +/* xxx.css */.container{ flex-direction: column; justify-content: center; align-items: center; background-color: #F1F3F5;}canvas{ width: 500px; height: 500px; background-color: #fdfdfd; border: 5px solid red; + margin-bottom: 50px; +}.content{ border: 5px solid blue; padding: 10px; width: 90%; height: 400px; overflow: scroll;} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + dataURL:null, + antialia: false, + porc:'open', + }, + onShow(){ + let el = this.$refs.canvas1; + let ctx = el.getContext("2d"); + ctx.strokeRect(100,100,300,300); + }, + getUrl(){ + let el = this.$refs.canvas1; + let dataUrl = el.toDataURL(); + this.dataURL = dataUrl; + prompt.showToast({duration:2000,message:"long press,get dataURL"}); + } +} +``` + +![en-us_image_0000001276003513](figures/en-us_image_0000001276003513.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The **<canvas>** component cannot be created in **onInit** or **onReady**. diff --git a/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md b/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md new file mode 100644 index 0000000000000000000000000000000000000000..67922ab27f55e9cc20b1e2447e605dc83ff18df4 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-canvasrenderingcontext2d.md @@ -0,0 +1,826 @@ +# CanvasRenderingContext2D + + +Use **CanvasRenderingContext2D** to draw objects such as graphics, texts, line segments, and images on the **<canvas>** component. For details, see [CanvasRenderingContext2D](../reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md). + + +## Drawing Line Segments + +Use **moveTo** and **lineTo** to draw a line segment. Use the **closePath** method to end current path, obtaining a closed path. Set **quadraticCurveTo** (quadratic bezier curve) or **bezierCurveTo** (cubic bezier curve) to draw a graphic. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +select{ + margin-top: 50px; + width: 250px; + height: 100px; + background-color: white; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + el: null, + ctx: null, + }, + onShow(){ + this.el = this.$refs.canvas1; + this.ctx = this.el.getContext("2d",{antialias: true}); + // Clear the contents on the canvas. + this.ctx.clearRect(0, 0, 600, 500); + // Create a drawing path. + this.ctx.beginPath(); + // Square off the endpoints of the line. + this.ctx.lineCap = 'butt'; + // Border width + this.ctx.lineWidth = 15; + // Create a drawing path. + this.ctx.beginPath(); + // Move a drawing path from the current point to a target position. + this.ctx.moveTo(200, 100); + // Connect the current point to a target position. + this.ctx.lineTo(400, 100); + // Stroke a path. + this.ctx.stroke(); + this.ctx.beginPath(); + // Round the endpoints of the line. + this.ctx.lineCap = 'round'; + this.ctx.moveTo(200, 200); + this.ctx.lineTo(400, 200); + this.ctx.stroke(); + // Square off the endpoints of the line. + this.ctx.beginPath(); + this.ctx.lineCap = 'square'; + this.ctx.moveTo(200, 300); + this.ctx.lineTo(400, 300); + this.ctx.stroke(); + }, + change(e){ + if(e.newValue == 'value1'){ + this.el = this.$refs.canvas1; + this.ctx = this.el.getContext("2d",{antialias: true}); + this.ctx.clearRect(0, 0, 600, 500); + // Top + this.ctx.beginPath(); + this.ctx.lineCap = 'butt'; + this.ctx.moveTo(200, 100); + this.ctx.lineTo(400, 100); + this.ctx.stroke(); + // Center + this.ctx.beginPath(); + this.ctx.lineCap = 'round'; + this.ctx.moveTo(200, 200); + this.ctx.lineTo(400, 200); + this.ctx.stroke(); + // Bottom + this.ctx.beginPath(); + this.ctx.lineCap = 'square'; + this.ctx.moveTo(200, 300); + this.ctx.lineTo(400, 300); + this.ctx.stroke(); + }else if(e.newValue == 'value2'){ + this.ctx.clearRect(0, 0, 600, 500); + // Top + this.ctx.beginPath(); + this.ctx.moveTo(100, 150); + // Path of the quadratic bezier curve + this.ctx.quadraticCurveTo(300, 50, 500, 150); + this.ctx.stroke(); + // Left + this.ctx.beginPath(); + this.ctx.moveTo(200, 150); + this.ctx.quadraticCurveTo(250, 250, 250, 400); + this.ctx.stroke(); + // Right + this.ctx.beginPath(); + this.ctx.moveTo(400, 150); + this.ctx.quadraticCurveTo(350, 250, 350, 400); + this.ctx.stroke(); + }else if(e.newValue == 'value3'){ + this.ctx.clearRect(0, 0, 600, 500); + // Bottom + this.ctx.beginPath(); + this.ctx.moveTo(100, 200); + // Path of the cubic bezier curve + this.ctx.bezierCurveTo(150, 100, 200, 100,250, 200); + this.ctx.stroke(); + // Left + this.ctx.beginPath(); + this.ctx.moveTo(350, 200); + this.ctx.bezierCurveTo(400, 100, 450, 100,500, 200); + this.ctx.stroke(); + // Right + this.ctx.beginPath(); + this.ctx.moveTo(200, 350); + this.ctx.bezierCurveTo(250, 500, 350, 500, 400, 350); + this.ctx.stroke(); + }else if(e.newValue == 'value4'){ + this.ctx.clearRect(0, 0, 600, 500); + this.ctx.beginPath(); + this.ctx.moveTo(100, 200); + // Arc + this.ctx.arcTo(150, 300, 350, 300, 150); + this.ctx.stroke(); + this.ctx.beginPath(); + // Ellipse + this.ctx.ellipse(400, 250, 50, 100, Math.PI * 0.25, Math.PI * 0.5 , Math.PI , 1); + this.ctx.stroke(); + }else if(e.newValue == 'value5'){ + this.ctx.clearRect(0, 0, 600, 500); + // Upper left + this.ctx.beginPath(); + // Draw a sector centered at the common endpoint of connected line segments. + this.ctx.lineJoin = 'round'; + this.ctx.moveTo(100, 100); + this.ctx.lineTo(200, 200); + this.ctx.lineTo(100, 250); + this.ctx.stroke(); + // lower left + this.ctx.beginPath(); + // Fill a triangular between the common endpoint of connected segments. + this.ctx.lineJoin = 'bevel'; + this.ctx.moveTo(100, 300); + this.ctx.lineTo(200, 400); + this.ctx.lineTo(100, 450); + this.ctx.stroke(); + // Top right + this.ctx.beginPath(); + // Distance between the internal angle and exterior angle at the intersection of lines + this.ctx.lineJoin = 'miter'; + this.ctx.miterLimit = 3; + this.ctx.moveTo(400, 100); + this.ctx.lineTo(450, 200); + this.ctx.lineTo(400, 250); + // Draw a closed path. + this.ctx.closePath(); + this.ctx.stroke(); + // Lower right + this.ctx.beginPath(); + this.ctx.lineJoin = 'miter'; + this.ctx.miterLimit = 10; + this.ctx.moveTo(400, 300); + this.ctx.lineTo(450, 400); + this.ctx.lineTo(400, 450); + this.ctx.closePath(); + this.ctx.stroke(); + } + }, +} +``` + +![en-us_image_0000001232162320](figures/en-us_image_0000001232162320.gif) + + +## Drawing Border + +Globally define the canvas (**el**) and brush (**ctx**), and create a rectangle with the border width of 5 upon initialization. Change the border width (**lineWidth**), color (**strokeStyle**), and line dash level (**setLineDash**). Add the **change** event to the **<select>** component. The **change** event will be triggered upon selection and the changed image will be displayed. + + + +``` + +
+ + +
+``` + + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +select{ + margin-top: 50px; + width: 250px; + height: 100px; + background-color: white; +} +``` + + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + el: null, + ctx: null, + }, + onShow(){ + this.el = this.$refs.canvas1; + this.ctx = this.el.getContext("2d",{antialias: true}); + this.ctx.lineWidth = 5; + this.ctx.strokeRect(200, 150, 200, 200); + }, + change(e){ + if(e.newValue == 'value1'){ + // Clear the contents on the canvas. + this.ctx.clearRect(0,0,600,500); + // Border width + this.ctx.lineWidth = 5; + // Border color + this.ctx.strokeStyle = '#110000'; + // Line dash level of the border + this.ctx.setLineDash([0,0]); + // Draw a stroked rectangle. + this.ctx.strokeRect(200, 150, 200, 200); + }else if(e.newValue == 'value2'){ + this.ctx.clearRect(0,0,600,500); + this.ctx.lineWidth = 30; + this.ctx.strokeStyle = '#0000ff'; + this.ctx.setLineDash([0,0]); + // Draw a circle. + this.ctx.arc(300, 250, 150,0,6.28); + // Draw borders. + this.ctx.stroke(); + }else if(e.newValue == 'value3'){ + this.ctx.clearRect(0,0,600,500); + this.ctx.lineWidth = 5; + this.ctx.setLineDash([5,5]); + this.ctx.strokeRect(200, 150, 200, 200); + }else if(e.newValue == 'value4'){ + this.ctx.clearRect(0,0,600,500); + // Draw and fill a rectangle. + this.ctx.fillStyle = '#0000ff'; + this.ctx.fillRect(200, 150, 200, 200); + } + }, +} +``` + + +![en-us_image_0000001232003004](figures/en-us_image_0000001232003004.gif) + + +## Setting Gradient Fill Colors + +Add the **createLinearGradient** and **createRadialGradient** attributes to create a gradient container, use the **addColorStop** method to add multiple color blocks to form a gradient color, and set **fillStyle** as **gradient** to apply the gradient color to a rectangle. Then set the shadow blur level by using **shadowBlur**, the shadow color by using **shadowColor**, and the shadow offset by using **shadowOffset**. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +select{ + margin-top: 50px; + width: 250px; + height: 100px; + background-color: white; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + el: null, + ctx: null, + }, + onShow(){ + this.el = this.$refs.canvas1; + this.ctx = this.el.getContext("2d",{antialias: true}); + // Create a linear gradient. + let gradient = this.ctx.createLinearGradient(100,100, 400,300); + // Add gradient colors. + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.7, 'white'); + gradient.addColorStop(1.0, 'green'); + // Apply the gradient. + this.ctx.fillStyle = gradient; + this.ctx.fillRect(100, 100, 400, 300); + }, + change(e){ + if(e.newValue == 'value1'){ + // Clear the contents on the canvas. + this.ctx.clearRect(0,0,600,500); + let gradient = this.ctx.createLinearGradient(100,100, 400,300); + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.7, 'white'); + gradient.addColorStop(1.0, 'green'); + this.ctx.fillStyle = gradient; + // Set the level of shadow blur. + this.ctx.shadowBlur = 0; + // Set the distance that shadows will be offset vertically. + this.ctx.shadowOffsetY = 0; + // Set the distance that shadows will be offset horizontally. + this.ctx.shadowOffsetX = 0; + this.ctx.fillRect(100, 100, 400, 300); + }else if(e.newValue == 'value2'){ + this.ctx.clearRect(0,0,600,500); + // Create a radial gradient. + let gradient = this.ctx.createRadialGradient(300,250,20,300,250,100); + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.7, 'white'); + gradient.addColorStop(1.0, 'green'); + this.ctx.shadowBlur = 0; + this.ctx.shadowOffsetY = 0; + this.ctx.shadowOffsetX = 0; + this.ctx.fillStyle = gradient; + this.ctx.fillRect(100, 100, 400, 300); + }else if(e.newValue == 'value3'){ + this.ctx.clearRect(0,0,600,500); + let gradient = this.ctx.createLinearGradient(100,100, 400,400); + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.5, 'white'); + gradient.addColorStop(1, '#17ea35'); + // Set the level of shadow blur. + this.ctx.shadowBlur = 30; + // Set the shadow color. + this.ctx.shadowColor = 'rgb(229, 16, 16)'; + this.ctx.fillStyle = gradient; + this.ctx.fillRect(100, 100, 400, 300); + }else if(e.newValue == 'value4'){ + this.ctx.clearRect(0,0,600,500); + this.ctx.clearRect(0,0,600,500); + let gradient = this.ctx.createRadialGradient(300,250,20,300,250,200); + gradient.addColorStop(0.0, 'red'); + gradient.addColorStop(0.5, 'white'); + gradient.addColorStop(1, '#17ea35'); + // Set the level of shadow blur. + this.ctx.shadowBlur = 30; + this.ctx.shadowOffsetY = 30; + // Set the shadow color. + this.ctx.shadowColor = 'rgb(23, 1, 1)'; + this.ctx.fillStyle = gradient; + this.ctx.fillRect(100, 100, 400, 300); + } + }, +} +``` + +![en-us_image_0000001231683148](figures/en-us_image_0000001231683148.gif) + + +## Filling Texts + +Create a text and use the **fillText** method to write the text on the canvas. Use the **globalAlpha** attribute to change the baseline transparency to avoid the text being hidden by the baseline. Then set the **textAlign** and **textBaseline** attributes to determine the text position based on the baseline. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +select{ + margin-top: 50px; + width: 250px; + height: 100px; + background-color: white; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + el: null, + ctx: null, + }, + onShow(){ + this.el = this.$refs.canvas1; + this.ctx = this.el.getContext("2d",{antialias: true}); + // Create a text. + let text = "Hello World"; + // Set the font. + this.ctx.font = '30px'; + this.ctx.fillText("with:"+this.ctx.measureText(text).width, 200, 300); + // Set the fill text. + this.ctx.fillText(text, 200, 250); + }, + change(e){ + if(e.newValue == 'value1'){ + // Clear the contents on the canvas. + this.ctx.clearRect(0,0,600,500); + // Start a new path. + this.ctx.beginPath(); + // Initialize the textAlign value. + this.ctx.textAlign = 'left'; + // Initialize textBaseline. + this.ctx.textBaseline = 'alphabetic'; + // Set the font. + this.ctx.font = '30px'; + let text = "Hello World"; + // Obtain the font width. + this.ctx.fillText("with:"+this.ctx.measureText(text).width, 200, 300); + // Set the fill text. + this.ctx.fillText(text, 200, 250); + }else if(e.newValue == 'value2'){ + this.ctx.clearRect(0,0,600,500); + this.ctx.beginPath(); + // Set the Alpha value. + this.ctx.globalAlpha = 0.1; + // Set the line width. + this.ctx.lineWidth = 10; + // Set the line segment color. + this.ctx.strokeStyle = '#0000ff'; + // Move from the current point to a target position. + this.ctx.moveTo(0, 240); + // Connect the current point to a target position. + this.ctx.lineTo(600, 240); + this.ctx.stroke(); + this.ctx.font = '35px'; + this.ctx.globalAlpha = 1; + // Initialize the textAlign value. + this.ctx.textAlign = 'left'; + // Set textBaseline. + this.ctx.textBaseline = 'top'; + this.ctx.fillText('Top', 50, 240); + this.ctx.textBaseline = 'bottom'; + this.ctx.fillText('Bottom', 200, 240); + this.ctx.textBaseline = 'middle'; + this.ctx.fillText('Middle', 400, 240); + }else if(e.newValue == 'value3'){ + // Clear the contents on the canvas. + this.ctx.clearRect(0,0,600,500); + this.ctx.beginPath(); + this.ctx.globalAlpha = 0.1; + this.ctx.lineWidth = 10; + this.ctx.strokeStyle = '#0000ff'; + this.ctx.moveTo(300, 0); + this.ctx.lineTo(300, 500); + this.ctx.stroke(); + this.ctx.font = '35px'; + this.ctx.globalAlpha = 1; + // Initialize textBaseline. + this.ctx.textBaseline = 'alphabetic'; + // Set textAlign. + this.ctx.textAlign = 'left'; + this.ctx.fillText('textAlign=left',300, 100); + this.ctx.textAlign = 'center'; + this.ctx.fillText('textAlign=center',300, 250); + this.ctx.textAlign = 'right'; + this.ctx.fillText('textAlign=right',300, 400); + } + } +} +``` + +![en-us_image_0000001276162745](figures/en-us_image_0000001276162745.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**. + + +## Adding Images + +After creating an image object, use the **drawImage** attribute to draw the image and set animation styles such as scaling, translating, and rotating. + + +``` + +
+
+ + change + + rotate + + scale + + translate + + transform + + setTransform + +
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; +} +canvas{ + width: 600px; + height: 300px; + margin-bottom: 100px; + background-color: #fdfdfd; + border: 5px solid red; +} +.content{ + width: 80%; + margin-top: 50px; + margin-bottom: 50px; + display: flex; + flex-wrap: wrap; + justify-content: space-around; +} +text{ + font-size: 35px; + width: 200px; + height: 80px; + color: white; + border-radius: 20px; + text-align: center; + background-color: #6060e7; + margin-bottom: 30px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + compositeOperation: 'source-over' + }, + onShow(){ + let ctx = this.$refs.canvas0.getContext("2d"); + // Create an image object. + let img = new Image(); + // Set the image path. + img.src = 'common/images/2.png'; + // Set the image width. + img.width= 150; + // Set the image height. + img.height=150; + // Create an image tiling container. + var pat = ctx.createPattern(img, 'repeat'); + ctx.fillStyle = pat; + ctx.fillRect(0, 0, 600, 300); + }, + change(){ + // Obtain the brush after the canvas is created. + let ctx = this.$refs.canvas1.getContext("2d"); + ctx.clearRect(0,0,600,1000); + if(this.compositeOperation == "source-over"){ + this.compositeOperation = "destination-over"; + }else{ + this.compositeOperation = "source-over"; + } + ctx.globalCompositeOperation = this.compositeOperation; + let img = new Image(); + img.src = 'common/images/2.png'; + // Invoked when the image is successfully obtained. + img.onload = function() { + ctx.drawImage(img, 150, 20, 200, 200); + }; + let img1 = new Image(); + img1.src = 'common/images/3.png'; + img1.onload = function() { + // Draw an image. + ctx.drawImage(img1, 250, 80, 200, 200); + }; + // A method is triggered when the image fails to be obtained. + img1.onerror = function() { + prompt.showToast({message:"error",duration:2000}) + }; + }, + rotate(){ + let ctx = this.$refs.canvas2.getContext("2d"); + ctx.clearRect(0,0,600,300); + // Rotate the image. + ctx.rotate(10 * Math.PI / 180); + let img = new Image(); + img.src = 'common/images/2.png'; + img.onload = function() { + ctx.drawImage(img, 300, 0, 100, 100); + }; + }, + scale(){ + let ctx = this.$refs.canvas3.getContext("2d"); + ctx.clearRect(0,0,600,200); + // Scale the image. + ctx.scale(1.3,1.2); + let img = new Image(); + img.src = 'common/images/2.png'; + img.onload = function() { + ctx.drawImage(img, 0, 0, 50, 50); + }; + }, + translate(){ + let ctx = this.$refs.canvas4.getContext("2d"); + ctx.clearRect(0,0,600,300); + ctx.translate(10,0); + let img = new Image(); + img.src = 'common/images/2.png'; + img.onload = function() { + ctx.drawImage(img, 0, 50, 300, 200); + }; + }, + transform(){ + let ctx = this.$refs.canvas5.getContext("2d"); + ctx.clearRect(0,0,600,300); + ctx.transform(1.1, 0.1, 0.1, 1, 10, 0); + let img = new Image(); + img.src = 'common/images/2.png'; + img.onload = function() { + ctx.drawImage(img, 0, 50, 100, 100); + }; + }, + setTransform(){ + let ctx = this.$refs.canvas6.getContext("2d"); + ctx.clearRect(0,0,600,300); + ctx.setTransform(1.1, 0.1, 0.1, 1, 10, 0); + let img = new Image(); + img.src = 'common/images/2.png'; + img.onload = function() { + ctx.drawImage(img, 0, 50, 100, 100); + }; + }, +} +``` + +![en-us_image_0000001232003008](figures/en-us_image_0000001232003008.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - Unlike the **transform()** function, the **setTransform()** function resets the existing transformation matrix and creates a transformation matrix even if it uses the same parameters. +> +> - The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. +> x' = scaleX \* x + skewY \* y + translateX +> +> y' = skewX \* x + scaleY \* y + translateY + + +## Adding Methods + +Use the **save** method to save the brush style, and use the **restore** method to restore the saved settings. In the following example, set the brush to red. After the brush setting is saved, clear the canvas and change the brush to blue. In this moment, directly using the brush will get a blue rectangle; using the brush after the restore operation will get a red rectangle. + + +``` + +
+
+ +
+
+ save + clear + restore +
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; +} +canvas{ + margin-top: 300px; + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +.content{ + width: 80%; + margin-top: 50px; + margin-bottom: 50px; + display: flex; + flex-wrap: wrap; + justify-content: space-around; +} +text{ + width: 150px; + height: 80px; + color: white; + border-radius: 20px; + text-align: center; + background-color: #6060e7; + margin-bottom: 30px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + ctx: '', + }, + onShow(){ + this.ctx = this.$refs.canvas.getContext("2d"); + this.ctx.fillStyle = "red" + this.ctx.fillRect(200, 150, 200, 200); + }, + save(){ + // Save the brush setting. + this.ctx.save(); + prompt.showToast({message:"save succeed"}); + }, + clear(){ + this.ctx.clearRect(0,0,600,500); + // Change the brush color. + this.ctx.fillStyle = "#2133d2"; + }, + restore(){ + this.ctx.beginPath(); + // Restore the brush setting. + this.ctx.restore(); + this.ctx.fillRect(200, 150, 200, 200); + }, +} +``` + +![en-us_image_0000001231683144](figures/en-us_image_0000001231683144.gif) diff --git a/en/application-dev/ui/ui-js-components-chart.md b/en/application-dev/ui/ui-js-components-chart.md new file mode 100644 index 0000000000000000000000000000000000000000..b300b2a1cb977b7253dadad41adbad9a29a320bf --- /dev/null +++ b/en/application-dev/ui/ui-js-components-chart.md @@ -0,0 +1,620 @@ +# <chart> Development + + +The **<chart>** component displays line charts, gauge charts, and bar charts. For details, see [chart](../reference/arkui-js/js-components-basic-chart.md). + + +## Creating a <chart> Component + +Create a **<chart>** component in the .hml file under **pages/index**. + + + +``` + +
+ +
+``` + + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.chart-data { + width: 700px; + height: 600px; +} +``` + + + +``` +/* xxx.js */ +export default { + data: { + lineData: [ + { + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716] + } + ], + lineOps: { + xAxis: { + min: 0, + max: 20, + display: false, + }, + yAxis: { + min: 0, + max: 1000, + display: false, + }, + series: { + lineStyle: { + width: 15, + }, + } + }, + } +} +``` + + +![en-us_image_0000001231683156](figures/en-us_image_0000001231683156.png) + + +## Setting the Chart Type + +Define the chart type using the **type** attribute, for example, setting a chart to a bar chart. + + +``` + +
+
+
+ + {{ title }} + +
+ + + + + Line chart + Bar chart + Gauge chart + + +
+ + +
+
+ + +
+
+ +
+
+
+
+
+
+
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + background-color: #F1F3F5; +} +.chart-data { + width: 700px; + height: 600px; +} +.title{ + margin-left: 50px; + margin-top: 50px; + font-size: 50px; +} +.line-block{ + align-items: center; + justify-content: center; +} +.bar-block{ + align-items: center; + justify-content: center; +} +.chart-block{ + width: 90%; + margin-left: 30px; +} +``` + + +``` +/* xxx.js */ +export default { + data: { + title:"Type display", + barData: [ + { + fillColor: '#3848e8', + data: [763, 550, 551, 554, 731, 654, 525, 696, 595], + } + ], + lineData: [ + { + strokeColor: '#0081ff', + fillColor: '#cce5ff', + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], + gradient: true, + } + ], + lineOps: { + xAxis: { + min: 0, + max: 20, + display: false, + }, + yAxis: { + min: 0, + max: 1000, + display: false, + }, + series:{ + lineStyle: { + width: "5px", + smooth: true, + }, + headPoint: { + shape:"circle", + size: 20, + strokeWidth: 5, + fillColor: '#ffffff', + strokeColor: '#007aff', + display: true, + }, + loop:{ + margin: 2, + gradient: true + } + }, + }, + barOps: { + xAxis: { + min: 0, + max: 20, + display: false, + axisTick: 10, + }, + yAxis: { + min: 0, + max: 1000, + }, + }, + }, +} +``` + +![en-us_image_0000001275803181](figures/en-us_image_0000001275803181.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The **<chart>** component does not display the value of each point. + + +## Setting the Chart Attributes + +In the **options** attribute of the **<chart>** component, you can set the x-axis, y-axis, and data series parameters. In the **datasets** attribute, you can set the line color, fill color, gradient fill color, and drawing point set. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.chart-data { + width: 700px; + height: 600px; +} +``` + + +``` +/* xxx.js */ +export default { + data: { + // Line chart data + lineData: [ + { + strokeColor: '#0081ff', + fillColor: '#cce5ff', // Fill color + data: [463, 250, 251, 254, 431, 354, 225, 396, 295, 328, 491, 205, 313, 275, 475, 553, 491, 380, 357, 416], + gradient: true, + } + ], + lineOps: { + // X-axis parameters + xAxis: { + min: 0, + max: 20, + display: false, + }, + // Y-axis parameters + yAxis: { + min: 0, + max: 1000, + display: false, + }, + // Data series parameters + series: { + // Line style + lineStyle: { + width: "5px", + smooth: true, + }, + // Style and size of the white point at the start of the line + headPoint: { + shape: "circle", + size: 20, + strokeWidth: 5, + fillColor: '#ffffff', + strokeColor: '#007aff', + display: true, + }, + // Whether to start drawing again when the screen is looped. + loop: { + margin: 2, + gradient: true + } + } + }, + }, +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The **options** attribute supports the settings of bar charts and line charts but does not support those of gauge charts. +> +> - The **datasets** attribute supports the datasets for bar charts and line charts but does not support those of gauge charts. +> +> - Only line charts support **series**. + + +## Adding Data + +Use the **append** method of the **<chart>** component to dynamically add data. + + +``` + +
+ + + + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.chart-region { + height: 400px; + width: 700px; +} +.chart-data { + width: 700px; + height: 600px; +} +button { + width: 100%; + height: 50px; + background-color: #F4F2F1; + text-color: #0C81F3; + margin-top: 30px; +} +``` + + +``` +// xxx.js +export default { + data: { + lineData: [ + { + strokeColor: '#de0b6e', + fillColor: '#bb09a3', + data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], + gradient: true, + } + ], + lineOps: { + xAxis: { + min: 0, + max: 20, + display: false, + }, + yAxis: { + min: 0, + max: 1000, + display: false, + }, + series: { + lineStyle: { + width: "5px", + smooth: true, + }, + headPoint: { + shape: "circle", + size: 20, + strokeWidth: 5, + fillColor: '#ffffff', + strokeColor: '#f8145c', + display: true, + }, + loop: { + margin: 2, + gradient: true, + } + } + }, + }, + addData() { + this.$refs.linechart.append({ + serial: 0, + data: [Math.floor(Math.random() * 400) + 200] + }) + } +} +``` + +![en-us_image_0000001275803177](figures/en-us_image_0000001275803177.gif) + + +## Example Scenario + +Select the data display status using **<switch>**. When **<switch>** is set to **true**, the timer is used to dynamically display data. + + +``` + +
+
+
+ {{ title }} + + +
+ + +
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+
+ + + {{ $item.data }} + + + + + {{ $item.value }} + + +
+
+
+
+
+
+``` + + +``` +/* xxx.css */ +.container{ + display:flex; + flex-direction:column; + background-color: #F1F3F5; +} +.line-class{ + display: flex; + flex-direction: column; +} +.title{ + font-size: 40px; + margin-left: 40px; +} +.switch-block { + margin-top: 30px; + width: 98%; + height: 80px; + display: flex; + justify-content: space-between; +} +.switch{ + font-size: 40px; +} +.bar-block { + margin-top: 80px; + margin-left: 40px; + position: relative; + width: 90%; + border-radius: 10px; + background-color: #25FAB27B; + height: 40%; + justify-content: center; +} +``` + + +``` +// xxx.js +export default { + data: { + interval: null, + title: "Data Display", + allowScale: true, + dataLength: 30, + barGroup: 3, + lineData: null, + lineOps: { + xAxis: { + min: 0, + max: 5 + }, + yAxis: { + min: 0, + max: 100 + }, + series: { + lineStyle: { + width: '1px', + }, + headPoint: { + shape: 'circle', + size: 10, + strokeWidth: 2, + fillColor: '#ffffff', + strokeColor: '#8477DF' + }, + loop: { + margin: 2 + } + } + }, + barData: [ + { + fillColor: '#97CF0A2C', + data: [20, 20,40, 56] + }, + { + fillColor: '#6D0A7ACF', + data: [52, 40, 2, 67] + }, + { + fillColor: '#6A0ACFA1', + data: [56, 2, 77, 40] + } + ], + barOps: { + xAxis: { + min: 0, + max: 20, + axisTick: 5 + }, + yAxis: { + min: 0, + max: 100 + } + } + }, + onInit() { + this.changeLine(); + }, + change(e) { + if (e.checked) { + this.interval = setInterval(() => { + this.changeLine(); + this.changeBar(); + }, 1000) + } else { + clearInterval(this.interval); + } + }, + changeLine() { + var dataArray = []; + for (var i = 0; i < this.dataLength; i++) { + var nowValue = Math.floor(Math.random() * 99 + 1); + var obj = { + "value": nowValue, + "description": nowValue + "", + "textLocation": "top", + "textColor": "#CDCACA", + "pointStyle": { + "shape": "circle", + "size": 5, + "fillColor": "#CF0A2C", + "strokeColor": "#CF0A2C" + } + }; + dataArray.push(obj); + } + this.lineData = [ + { + strokeColor: '#0081ff', + fillColor: '#FF07CDC4', + data: dataArray, + gradient: true, + } + ] + }, + changeBar() { + for (var i = 0;i < this.barGroup; i++) { + var dataArray = this.barData[i].data; + for (var j = 0;j < 4; j++) { + dataArray[j] = Math.floor(Math.random() * 99 + 1); + } + } + this.barData = this.barData.splice(0, this.barGroup + 1); + }, + changes(e) { + console.log("Tab index: " + e.index); + }, +} + +``` + +![en-us_image_0000001232162328](figures/en-us_image_0000001232162328.gif) diff --git a/en/application-dev/ui/ui-js-components-dialog.md b/en/application-dev/ui/ui-js-components-dialog.md index 0c5c1303dbaa51e7c2d3987788cded4d51be8906..4c7f982b9169be8d68220a471d9aa9ad393cfc7c 100644 --- a/en/application-dev/ui/ui-js-components-dialog.md +++ b/en/application-dev/ui/ui-js-components-dialog.md @@ -1,20 +1,21 @@ # <dialog> Development -The <dialog> component is custom pop-up container for showing critical information or calling for an action. For details, see [dialog](../reference/arkui-js/js-components-container-dialog.md). +The **<dialog>** component is custom pop-up container for showing critical information or calling for an action. For details, see [dialog](../reference/arkui-js/js-components-container-dialog.md). ## Creating a <dialog> Component - Create a <dialog> component in the .hml file under pages/index and add <button> components to trigger the <dialog>. The <dialog> component supports only the width, height, margin, margin-[left|top|right|bottom], and margin-[start|end] styles. + Create a **<dialog>** component in the .hml file under **pages/index** and add **<button>** components to trigger the **<dialog>**. The **<dialog>** component supports only the **width**, **height**, **margin**, **margin-[left|top|right|bottom]**, and **margin-[start|end]** styles. ```
-
+ +
this is a dialog
-
+
``` @@ -23,6 +24,8 @@ The <dialog> component is custom pop-up container for showing critical inf ``` /* xxx.css */ .doc-page { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -67,7 +70,9 @@ export default { ## Setting Dialog Box Response -Add a cancel event that is triggered when a user touches a non-dialog area to cancel the pop-up dialog box. Add the show and close methods to display and close the dialog box, respectively. +Add a **cancel** event that is triggered when a user touches a non-dialog area to cancel the pop-up dialog box. Add the **show** and **close** methods to display and close the dialog box, respectively. + + ``` @@ -82,9 +87,13 @@ Add a cancel event that is triggered when a user touches a non-dialog area to ca
``` + + ``` /* xxx.css */ .doc-page { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -113,6 +122,8 @@ button{ } ``` + + ``` /* xxx.js */ import prompt from '@system.prompt'; @@ -133,18 +144,20 @@ export default { ![en-us_image_0000001223287720](figures/en-us_image_0000001223287720.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > - This component supports only one child component. > -> - Attributes and styles of a <dialog> component cannot be dynamically updated. +> - Attributes and styles of a **<dialog>** component cannot be dynamically updated. > -> - The <dialog> component does not support the focusable and click-effect attributes. +> - The **<dialog>** component does not support the **focusable** and **click-effect** attributes. ## Example Scenario -Use the <dialog> component to implement a schedule. When the dialog box is open, use the [<textarea>](../reference/arkui-js/js-components-basic-textarea.md) component to add an event and touch the OK button to obtain the current time and save the input text. The events in the calendar are displayed in a list. +Use the **<dialog>** component to implement a schedule. When the dialog box is open, use the [**<textarea>**](../reference/arkui-js/js-components-basic-textarea.md) component to add an event and touch the OK button to obtain the current time and save the input text. The events in the calendar are displayed in a list. + + ``` @@ -180,6 +193,8 @@ Use the <dialog> component to implement a schedule. When the dialog box is ``` + + ``` /* xxx.css */ .doc-page { @@ -248,6 +263,8 @@ Use the <dialog> component to implement a schedule. When the dialog box is } ``` + + ``` /* xxx.js */ var info = null; diff --git a/en/application-dev/ui/ui-js-components-form.md b/en/application-dev/ui/ui-js-components-form.md index 734d3dc510a597d08c5dda4d31e8c6d2b18436be..a4d3fa9c7015f240d57fdd2950a36530366d83c0 100644 --- a/en/application-dev/ui/ui-js-components-form.md +++ b/en/application-dev/ui/ui-js-components-form.md @@ -1,22 +1,22 @@ # <form> Development -The <form> component allows the content in [<input>](../reference/arkui-js/js-components-basic-input.md)components to be submitted and reset. For details, see [form](../reference/arkui-js/js-components-container-form.md). +The <form> component allows the content in [<input>](../reference/arkui-js/js-components-basic-input.md) components to be submitted and reset. For details, see [form](../reference/arkui-js/js-components-container-form.md). -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > This component is supported since API version 6. ## Creating a <form> Component - Create a <form> component in the .hml file under pages/index. + Create a **<form>** component in the .hml file under **pages/index**. ```
-
-
+
+
``` @@ -24,6 +24,8 @@ The <form> component allows the content in [<input>](../reference/ar ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -36,7 +38,7 @@ The <form> component allows the content in [<input>](../reference/ar ## Zooming In or Out on a Form - To implement the zoom effect after a form is clicked, add the click-effect attribute to the <form> component. For values of click-effect, see [Universal Attributes](../reference/arkui-js/js-components-common-attributes.md). + To implement the zoom effect after a form is clicked, add the **click-effect** attribute to the **<form>** component. For values of **click-effect**, see [Universal Attributes](../reference/arkui-js/js-components-common-attributes.md). ``` @@ -48,10 +50,23 @@ The <form> component allows the content in [<input>](../reference/ar ``` -## Setting the Form Style +## Setting Form Styles + + +Add the **background-color** and **border** attributes. + + + +``` + +
+
+ +
+
+``` -Add the background-color and border attributes. ``` /* xxx.css */ @@ -63,8 +78,7 @@ Add the background-color and border attributes. } .formClass{ width: 80%; - padding: 10px; - border: 1px solid #c3d3e7; + height: 20%; } ``` @@ -74,24 +88,24 @@ Add the background-color and border attributes. ## Adding Response Events - To submit or reset a form, add the submit and reset events. + To submit or reset a form, add the **submit** and **reset** events. ``` -
-
-
-
- - - - -
-
- - -
-
+
+ + +
+ + + + +
+
+ + +
+
``` @@ -122,7 +136,7 @@ export default{ Select an option and submit or reset the form data. -Create [<input>](../reference/arkui-js/js-components-basic-input.md) (en-us_topic_0000001173324647.xml) components, set their type attribute to checkbox and radio, and use the onsubmit and onreset events of the <form> component to submit and reset the form data. +Create [<input>](../reference/arkui-js/js-components-basic-input.md) components, set their **type** attribute to **checkbox** and **radio**, and use the **onsubmit** and **onreset** events of the **<form>** component to submit and reset the form data. ``` diff --git a/en/application-dev/ui/ui-js-components-image-animator.md b/en/application-dev/ui/ui-js-components-image-animator.md new file mode 100644 index 0000000000000000000000000000000000000000..8bfd56b70b3b23572eadf0bea1a2fbdc95f3ea55 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-image-animator.md @@ -0,0 +1,336 @@ +# <image-animator> Development + + +The **<image-animator>** component applies an animation to images. For details, see [image-animator](../reference/arkui-js/js-components-basic-image-animator.md). + + +## Creating an <image-animator> Component + +In the **pages/index** directory, create an **<image-animator>** component in the .hml file, define the component style in the .css file, and reference an image in the .js file. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.animator { + width: 500px; + height: 500px; +} +``` + + +``` +/* index.js */ +export default { + data: { + frames: [ + { + src: "/common/landscape1.jpg", + }, + { + src: "/common/landscape2.jpg", + } + ], + }, +}; +``` + +![en-us_image_0000001275922969](figures/en-us_image_0000001275922969.gif) + + +## Setting the <image-animator> Attributes + +Add the **iteration** (number of times the animation is played), **reverse** (whether the animation plays backward), **fixedsize** (whether the image size is fixed to the component size), **duration** (duration of the animation), and **fillmode** (style of the target when the animation is not playing) attributes. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; +} +.animator { + width: 500px; + height: 500px; +} +``` + + +``` +/* index.js */ +export default { + data: { + frames: [ + { + src: 'common/landscape1.jpg', + width: '250px', + height: '250px', + left: '150px', + top: '50px', + }, + { + src: 'common/landscape2.jpg', + width: '300px', + height: '300px', + left: '150px', + top: '100px', + }, + { + src: 'common/landscape1.jpg', + width: '350px', + height: '350px', + left: '150px', + top: '150px', + }, + { + src: 'common/landscape2.jpg', + width: '400px', + height: '400px', + left: '150px', + top: '200px', + }, + { + src: 'common/landscape3.jpg', + width: '450px', + height: '450px', + left: '150px', + top: '250px', + }, + { + src: 'common/landscape4.jpg', + width: '500px', + height: '500px', + left: '150px', + top: '300px', + }, + ], + }, +}; +``` + +![en-us_image_0000001276003481](figures/en-us_image_0000001276003481.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - If the **duration** attribute is set in the **images** attribute, the **duration** attribute set in the **<image-animator>** component is invalid. +> +> - If **fixedsize** is set to **true**, the **width**, **height**, **top**, and **left** settings in **images** will not take effect. +> +> - Setting **reverse** to **false** indicates that images are played from the first one to the last one. Setting **reverse** to **true** indicates that images are played from the last one to the first one. + + +## Binding Events + +Add the start, pause, stop, and resume events to the **<image-animator>** component. Specifically, the start event is triggered when the image animator starts playing; the pause event is triggered when the image animator is clicked; the resume event is triggered when the image animator is pressed and held; the stop event is triggered when the image animator stops playing. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.doc-page { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +.img { + width: 600px; + height: 600px; + border: 3px solid orange; +} +``` + + +``` +/* index.js */ +import prompt from '@system.prompt'; +export default { + data: { + imginfo: [ + { + src: 'common/landscape1.jpg', + },{ + src: 'common/landscape2.jpg', + },{ + src: 'common/landscape3.jpg', + },{ + src: 'common/landscape4.jpg', + } + ], + }, + onInit() { + }, + setpause(e) { + this.$element('img').pause() + }, + setresume(e) { + this.$element('img').resume() + }, + popstart(e) { + prompt.showToast({ + message: 'Started.' + }) + }, + poppause(e) { + prompt.showToast({ + message: 'Paused.' + }) + }, + popstop(e) { + prompt.showToast({ + message: 'Stopped.' + }) + }, + popresume(e) { + prompt.showToast({ + message: 'Resumed.' + }) + } +} +``` + +![en-us_image_0000001231843076](figures/en-us_image_0000001231843076.gif) + + +## Example Scenario + +You can click the start or stop button to change the image animation status. + +Call the start, pause, stop, and resume methods to start, pause, stop, and resume the image animation, and call the **getState** method to check the image animation status. + + +``` + +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+``` + + +``` +/* xxx.css */ +.doc-page { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +.img { + width: 600px; + height: 600px; + border: 3px solid orange; +} +button{ + width: 260px +} +.container { + width: 100%; + height: 120px; + align-items: center; + justify-content: space-around; +} +``` + + +``` +/* index.js */ +import prompt from '@system.prompt'; +export default { + data: { + rev:false, + imginfo: [ + { + src: 'common/landscape1.jpg', + },{ + src: 'common/landscape2.jpg', + },{ + src: 'common/landscape3.jpg', + },{ + src: 'common/landscape4.jpg', + } + ], + revVal:'Reverse' + }, + onInit() { + }, + startimg(e) { + this.$element('img').start() + }, + pauseimg(e) { + this.$element('img').pause() + }, + stopimg(e) { + this.$element('img').stop() + }, + resumeimg(e) { + this.$element('img').resume() + }, + getimgstate(e) { + prompt.showToast({ + message: 'Current state:' + this.$element('img').getState() + }) + }, + revimg(e) { + this.rev = !this.rev + if (this.rev) { + this.revVal ='Play Forward' + } else { + this.revVal ='Reverse' + } + } +} +``` + +![en-us_image_0000001276162717](figures/en-us_image_0000001276162717.gif) diff --git a/en/application-dev/ui/ui-js-components-images.md b/en/application-dev/ui/ui-js-components-images.md index 2efab79c2b112824278d8e2fda72fbbf5a847d85..cc817fc80044e4792ba74de79ccc24a4bd43bc2b 100644 --- a/en/application-dev/ui/ui-js-components-images.md +++ b/en/application-dev/ui/ui-js-components-images.md @@ -1,17 +1,17 @@ # <image> Development -The <image> component is used to render and display images. For details, see [image](../reference/arkui-js/js-components-basic-image.md). +The **<image>** component is used to render and display images. For details, see [image](../reference/arkui-js/js-components-basic-image.md). ## Creating an <image> Component - Create an <image> component in the .hml file under pages/index. + Create an **<image>** component in the .hml file under **pages/index**. ```
- +
``` @@ -19,6 +19,8 @@ The <image> component is used to render and display images. For details, s ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -31,7 +33,9 @@ The <image> component is used to render and display images. For details, s ## Setting the Image Style -Set the width, height, and object-fit attributes to define the width, height, and scale type of an image. +Set the **width**, **height**, and **object-fit** attributes to define the width, height, and scale type of an image. + + ``` @@ -40,31 +44,37 @@ Set the width, height, and object-fit attributes to define the width, height, an
``` + + ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; background-color:#F1F3F5; } image{ - width: 80%; height: 500px; + width: 80%; + height: 500px; border: 5px solid saddlebrown; border-radius: 20px; - object-fit: contain; + object-fit: contain; match-text-direction:true; } ``` + ![en-us_image_0000001222807796](figures/en-us_image_0000001222807796.png) ## Loading Images -When an image is successfully loaded, the complete event is triggered, and the loaded image is returned. If an exception occurs during image loading, the error event is triggered, and the image loading failure is printed. +When an image is successfully loaded, the **complete** event is triggered, and the loaded image is returned. If an exception occurs during image loading, the **error** event is triggered, and the image loading failure is printed. ``` @@ -83,6 +93,8 @@ When an image is successfully loaded, the complete event is triggered, and the l ``` /* xxx.css */ .container{ + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-self: center; @@ -123,7 +135,7 @@ export default { ## Example Scenario - In this example you touch and hold an image to gradually hide it. After the image is completely hidden, it will show in its original setting. Set a setInterval timer to change the image opacity at a specified interval so that it is hidden gradually. When the opacity changes to 0, the timer is cleared and the opacity is set to 1. + In this example you touch and hold an image to gradually hide it. After the image is completely hidden, it will show in its original setting. Set a **setInterval** timer to change the image opacity at a specified interval so that it is hidden gradually. When the opacity changes to **0**, the timer is cleared and the opacity is set to **1**. ``` @@ -143,6 +155,8 @@ export default { ``` /* xxx.css */ .page-container { + width: 100%; + height: 100%; flex-direction:column; align-self: center; justify-content: center; diff --git a/en/application-dev/ui/ui-js-components-input.md b/en/application-dev/ui/ui-js-components-input.md index 559cca5401092490afd8ea1e841ae6d3b8809bba..854d40c6d26a2ad10ded8ca02cc9785079193bcf 100644 --- a/en/application-dev/ui/ui-js-components-input.md +++ b/en/application-dev/ui/ui-js-components-input.md @@ -1,18 +1,20 @@ -# Development +# <input> Development -The component provides an interactive way to receive user input of various types, including date, checkbox, and button. For details, see [input](../reference/arkui-js/js-components-basic-input.md). +The **<input>** component provides an interactive way to receive user input of various types, including **date**, **checkbox**, and **button**. For details, see [input](../reference/arkui-js/js-components-basic-input.md). -## Creating an Component +## Creating an <input> Component -Create an component in the .hml file under pages/index. +Create an **<input>** component in the .hml file under **pages/index**. ```
- Please enter the content + + Please enter the content +
``` @@ -20,6 +22,8 @@ Create an component in the .hml file under pages/index. ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -32,7 +36,7 @@ Create an component in the .hml file under pages/index. ## Setting the Input Type -Set the type attribute of the component to button, date, or any of the supported values. +Set the **type** attribute of the **<input>** component to **button**, **date**, or any of the supported values. ``` @@ -59,6 +63,8 @@ Set the type attribute of the component to button, date, or any of the s ``` /* xxx.css */ .container { + width: 100%; + height: 100%; align-items: center; flex-direction: column; justify-content: center; @@ -102,15 +108,15 @@ export default { ![en-us_image_0000001223287672](figures/en-us_image_0000001223287672.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - For wearables, the input type can only be button, radio, or checkbox. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - For wearables, the input type can only be **button**, **radio**, or **checkbox**. > -> - The settings of checked take effect only when the input type is set to checkbox or radio. The default value of checked is false. +> - The settings of **checked** take effect only when the input type is set to **checkbox** or **radio**. The default value of **checked** is **false**. ## Event Binding - Add the search and translate events to the component. + Add the **search** and **translate** events to the **<input>** component. ``` @@ -128,6 +134,7 @@ export default { /* xxx.css */ .content { width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -170,7 +177,7 @@ export default { ## Setting the Input Error Message -Add the showError method to the component to display an error message in the event of incorrect input. +Add the **showError** method to the **<input>** component to display an error message in the event of incorrect input. ``` @@ -187,6 +194,7 @@ Add the showError method to the component to display an error message in /* xxx.css */ .content { width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -219,9 +227,13 @@ import prompt from '@system.prompt' }, buttonClick(e){ if(this.value.length > 6){ - this.$element("input").showError({ error: 'Up to 6 characters are allowed.' }); + this.$element("input").showError({ + error: 'Up to 6 characters are allowed.' + }); }else if(this.value.length == 0){ - this.$element("input").showError({ error:this.value + 'This field cannot be left empty.' }); + this.$element("input").showError({ + error:this.value + 'This field cannot be left empty.' + }); }else{ prompt.showToast({ message: "success " @@ -233,14 +245,14 @@ import prompt from '@system.prompt' ![en-us_image_0000001223127708](figures/en-us_image_0000001223127708.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - This method is available when the input type is set to text, email, date, time, number, or password. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - This method is available when the input type is set to **text**, **email**, **date**, **time**, **number**, or **password**. ## Example Scenario -Enter information by using the component of the type that suits your needs. +Enter information by using the **<input>** component of the type that suits your needs. diff --git a/en/application-dev/ui/ui-js-components-list.md b/en/application-dev/ui/ui-js-components-list.md index c2a3150d366260d91dac7997690474f37cf3955e..147f117c0fca54b3004578396f0142cfdfcf8868 100644 --- a/en/application-dev/ui/ui-js-components-list.md +++ b/en/application-dev/ui/ui-js-components-list.md @@ -1,18 +1,18 @@ # <list> Development -The <list> component provides a list container that presents a series of list items arranged in a column with the same width. Lists can be used for presenting the same type of data in a multiple and coherent row style. For details, see [list](../reference/arkui-js/js-components-container-list.md). +The **<list>** component provides a list container that presents a series of list items arranged in a column with the same width. Lists can be used for presenting the same type of data in a multiple and coherent row style. For details, see [list](../reference/arkui-js/js-components-container-list.md). ## Creating a <list> Component -Create a <list> component in the .hml file under pages/index. +Create a **<list>** component in the .hml file under **pages/index**. ```
- + @@ -24,6 +24,8 @@ Create a <list> component in the .hml file under pages/index. ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; background-color: #F1F3F5; @@ -37,21 +39,21 @@ Create a <list> component in the .hml file under pages/index. ![en-us_image_0000001223287680](figures/en-us_image_0000001223287680.png) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - <list-item-group> is a child component of the <list> component and is used to group items in a list. It can have a <list-item> nested inside, but not <list>. -> -> - <list-item> is a child component of the <list> component and is used to display items in a list. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - **<list-item-group>** is a child component of the **<list>** component and is used to group items in a list. It can have a **<list-item>** nested inside, but not **<list>**. +> +> - **<list-item>** is a child component of the **<list>** component and is used to display items in a list. ## Adding a Scrollbar -To display a scrollbar on the right side of the screen, set scrollbar to on. The side scrollbar can be used to scroll a long list or the screen up or down. +To display a scrollbar on the right side of the screen, set **scrollbar** to **on**. The side scrollbar can be used to scroll a long list or the screen up or down. ```
- + @@ -66,6 +68,8 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; background-color: #F1F3F5; } @@ -86,7 +90,7 @@ To display a scrollbar on the right side of the screen, set scrollbar to on. The ## Adding a Side Index Bar -Set a custom indexer component to add an index bar at the right boundary of a list. By default, an alphabetical indexer is used. +Set a custom **indexer** component to add an index bar at the right boundary of a list. By default, an alphabetical indexer is used. ``` @@ -114,15 +118,15 @@ Set a custom indexer component to add an index bar at the right boundary of a li ![en-us_image_0000001223127716](figures/en-us_image_0000001223127716.png) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - This indexer attribute is valid only when flex-direction is set to column and columns is set to 1. -> -> - You must include "\#" when using a customized indexer. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - This **indexer** attribute is valid only when **flex-direction** is set to **column** and **columns** is set to **1**. +> +> - You must include **"\#"** when using a customized indexer. ## Collapsing or Expanding a List -To allow a <list> component to collapse and expand, add groupcollapse and groupexpand events. +To allow a **<list>** component to collapse and expand, add **groupcollapse** and **groupexpand** events. ``` @@ -200,14 +204,16 @@ export default { ![en-us_image_0000001267887845](figures/en-us_image_0000001267887845.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - The groupcollapse and groupexpand events can be used only by the list-item-group component. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The **groupcollapse** and **groupexpand** events can be used only by the **list-item-group** component. ## Example Scenario Search for contacts by using an alphabetical indexer. + + ```
@@ -219,7 +225,7 @@ Search for contacts by using an alphabetical indexer.
{{$item.name}} - 18888888888 + 18888888888
@@ -232,6 +238,8 @@ Search for contacts by using an alphabetical indexer.
``` + + ``` /* index.css */ .doc-page { @@ -251,7 +259,7 @@ Search for contacts by using an alphabetical indexer. color: #000000; font-size: 39px; } -.number { +.phone { color: black; font-size: 25px; } @@ -265,6 +273,8 @@ Search for contacts by using an alphabetical indexer. } ``` + + ``` // xxx.js export default { diff --git a/en/application-dev/ui/ui-js-components-marquee.md b/en/application-dev/ui/ui-js-components-marquee.md new file mode 100644 index 0000000000000000000000000000000000000000..0df6b4a2a04adced403a8bc61e6427fe7f369b48 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-marquee.md @@ -0,0 +1,238 @@ +# <marquee> Development + + +The **<marquee>** component displays single-line scrolling text. For details, see [marquee](../reference/arkui-js/js-components-basic-marquee.md). + + +## Creating a <marquee> Component + +Create a **<marquee>** component in the .hml file under **pages/index**. + + +``` + +
+ This is a marquee. +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001231683172](figures/en-us_image_0000001231683172.png) + + +## Setting Attributes and Styles + +Set the **color** and **font-weight** attributes to define the color, font weight, and border style of marquee text. + + +``` + +
+ It's a racing lamp. +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.customMarquee { + width: 100%; + height: 80px; + padding: 10px; + margin: 20px; + border: 4px solid #6712f1; + border-radius: 20px; + font-size: 40px; + color: #ffffff; + font-weight: bolder; + font-family: serif; + background-color: #1567f3; +} +``` + +![en-us_image_0000001275803193](figures/en-us_image_0000001275803193.png) + +Set the **scrollamount**, **loop**, and **direction** attributes to define the maximum scroll length, number of scrolling times, and text scrolling direction. + + +``` + +
+
+ + It's a racing lamp + +
+
+ + +
+
+``` + + +``` +/* xxx.css */ +.tutorial-page { + width: 750px; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +.marqueetext { + color: #ffffff; + font-family: serif; + font-size: 37px; +} +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #6712f1; + background-color: #1567f3; + border-radius: 15px; + align-items: center; +} +button{ + width: 200px; + height: 80px; + margin-top: 100px; +} +``` + + +``` +// xxx.js +export default { + private: { + loopval: -1, + scroll: 10, + isleft: "left", + }, + onInit(){ + }, + setleft(e) { + this.isleft = "left" + }, + setright(e) { + this.isleft = "right" + }, + makestart(e) { + this.$element('testmarquee').start() + } +} +``` + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> When the value of **loop** is less than or equal to 0, the marquee scrolls continuously. If **loop** is not set, the default value **-1** is used. + +![en-us_image_0000001276162773](figures/en-us_image_0000001276162773.gif) + + +## Example Scenario + +In this example, you can control the scrolling of marquee text. + +Set **loop** to **1**. When scrolling ends, trigger a **finish** event to increase the number of scrolling times by 1 and change the font color to a random color. Then, call the **start** method to start scrolling again. + + +``` + +
+
+ + It's a racing lamp + +
+
+ + +
+
+``` + + +``` +/* xxx.css */ +.tutorial-page { + width: 750px; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; +} +.marqueetext { + font-size: 37px; +} +.mymarquee { + margin-top: 20px; + width:100%; + height: 100px; + margin-left: 50px; + margin-right: 50px; + border: 1px solid #dc0f27; + border-radius: 15px; + align-items: center; +} +button{ + width: 200px; + height: 80px; + margin-top: 100px; +} +``` + + +``` +// xxx.js +export default { + private: { + loopval: 1, + scroll: 8, + color1: 'red' + }, + onInit(){ + }, + setfinish(e) { + this.loopval= this.loopval + 1, + this.r = Math.floor(Math.random()*255), + this.g = Math.floor(Math.random()*255), + this.b = Math.floor(Math.random()*255), + this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)', + this.$element('testmarquee').start(), + this.loopval= this.loopval - 1 + }, + makestart(e) { + this.$element('testmarquee').start() + }, + makestop(e) { + this.$element('testmarquee').stop() + } +} +``` + +![en-us_image_0000001276003541](figures/en-us_image_0000001276003541.gif) diff --git a/en/application-dev/ui/ui-js-components-menu.md b/en/application-dev/ui/ui-js-components-menu.md new file mode 100644 index 0000000000000000000000000000000000000000..63c3763ac01a2247d5acb7359520fdc11e060a63 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-menu.md @@ -0,0 +1,280 @@ +# <menu> Development + + +The <menu> component serves as a temporary pop-up window to display operations that users can perform. For details, see [menu](../reference/arkui-js/js-components-basic-menu.md). + + +## Creating a <menu> Component + +Create a **<menu>** component in the .hml file under **pages/index** and add the **target**, **type**, and **title** attributes. + + +``` + +
+ show menu + + + + + +
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +.title-text{ + font-size: 35px; +} +``` + +![en-us_image_0000001232162284](figures/en-us_image_0000001232162284.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The **<menu>** component supports only the [option](../reference/arkui-js/js-components-basic-option.md) child component. +> +> - The **<menu>** component does not support the **focusable** and **disabled** attributes. + + +## Setting Styles + +Set the style for the **<menu>** component, such as the font color, size, and character spacing. + + +``` + +
+ show menu + + + + + +
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +.title-text{ + font-size: 35px; + background-color: #5a5aee; + color: white; + width: 70%; + text-align: center; + height: 85px; + border-radius: 12px; +} +menu{ + text-color: blue; + font-size: 35px; + letter-spacing: 2px; +} +option{ + color: #6a6aef; + font-size: 30px; +} +``` + +![en-us_image_0000001275803137](figures/en-us_image_0000001275803137.gif) + + +## Binding Events + +Bind the **<menu>** component with the **onselected** event (triggered when a value in the menu is selected) and the **oncancel** event (triggered when an operation is canceled). Click the **<text>** component to call the **show** method to set the coordinates of the **<menu>** component. + + +``` + +
+ show menu + + + + + +
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + width: 100%; +} +.title-text{ + font-size: 35px; + background-color: #5a5aee; + color: white; + width: 70%; + text-align: center; + height: 85px; + border-radius: 12px; + margin-top: 500px; + margin-left: 15%; +} +menu{ + text-color: blue; + font-size: 35px; + letter-spacing: 2px; +} +option{ + color: #6a6aef; + font-size: 30px; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + select(e) { + prompt.showToast({ + message: e.value + }) + }, + cancel(){ + prompt.showToast({ + message: "cancel" + }) + }, + textClick() { + this.$element("menuId").show({x:175,y:590}); + }, +} +``` + +![en-us_image_0000001276162713](figures/en-us_image_0000001276162713.gif) + + +## Example Scenario + +Click the **<toggle>** component to change the text color and select the **<menu>** component to change the size of the gradient color block. + + +``` + +
+
+ {{item.name}} +
+ width:{{width}},height:{{height}} +
+ change size + + + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + width: 100%; + justify-content: center; + align-items: center; +} +.contentToggle{ + width: 100%; + justify-content: space-around; +} +.toggle{ + padding: 10px; + height:80px; + font-size: 35px; + width: 200px; + height: 85px; +} +.size{ + width: 100%; + height: 200px; + text-align: center; + font-size: 40px; + text-align: center; +} +.text{ + width: 300px; + height: 80px; + background-color: #615def; + color: white; + font-size: 35px; + text-align: center; + margin-top: 100px; +} +menu{ + text-color: blue; + font-size: 35px; + letter-spacing: 2px; +} +option{ + color: #6a6aef; + font-size: 30px; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + data:{ + fresh: false, + width: 200, + height: 200, + color: '', + optionList:[ + {text:'200 x 200',value:2}, + {text:'300 x 300',value:3}, + {text:'500 x 500',value:5}, + ], + togglesList:[ + {name:"red", checked:false}, + {name:"blue", checked:false}, + {name: "black", checked:false}, + ], + }, + toggleClick(index){ + for(let i=0;i +
+ + +
+``` + + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +select{ + margin-top: 50px; + width: 250px; + height: 100px; + background-color: white; +} +``` + + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + el: null, + ctx: null, + offscreen: null, + offCanvas: null, + img: null, + }, + onShow(){ + this.ctx = this.$refs.canvas1.getContext("2d"); + this.offscreen = new OffscreenCanvas(600, 500); + this.offCanvas = this.offscreen.getContext("2d"); + this.img = new Image(); + this.img.src = 'common/images/2.png'; + // Invoked when the image is successfully obtained. + let _this = this; + this.img.onload = function() { + _this.offCanvas.drawImage(_this.img, 100, 100, 400, 300); + }; + this.img.onerror = function() { + prompt.showToast({message:"error",duration:2000}) + }; + var bitmap = this.offscreen.transferToImageBitmap(); + this.ctx.transferFromImageBitmap(bitmap); + }, + change(e){ + this.offCanvas.filter = e.newValue; + this.offCanvas.drawImage(this.img, 100, 100, 400, 300); + var bitmap = this.offscreen.transferToImageBitmap(); + this.ctx.transferFromImageBitmap(bitmap); + }, +} +``` + + +![en-us_image_0000001232162292](figures/en-us_image_0000001232162292.gif) + + +## Determining the Position + +Use **isPointInPath** and **isPointInStroke** to determine and show whether a coordinate is within the path area and whether a coordinate is on the edge of the path. + + +``` + +
+
+ Coordinate: {{X}}, {{Y}} + In path:{{textValue}} + In stroke:{{textValue1}} +
+ + +
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +canvas{ + width: 600px; + height: 500px; + background-color: #fdfdfd; + border: 5px solid red; +} +.content{ + flex-direction: column; + justify-content: center; + align-items: center; +} +text{ + font-size: 30px; + width: 300px; + height: 80px; + text-align: center; +} +button{ + width: 180px; + height: 75px; + margin-top: 50px; +} +``` + + +``` +// xxx.js +export default { + data: { + textValue: 0, + textValue1: 0, + X:0, + Y:250, + }, + onShow(){ + let canvas = this.$refs.canvas.getContext('2d'); + let offscreen = new OffscreenCanvas(500,500); + let offscreenCanvasCtx = offscreen.getContext("2d"); + let offscreenCanvasCtx1 = offscreen.getContext("2d"); + offscreenCanvasCtx1.arc(this.X, this.Y, 2, 0, 6.28); + offscreenCanvasCtx.lineWidth=20; + offscreenCanvasCtx.rect(200,150, 200, 200); + offscreenCanvasCtx.stroke(); + this.textValue1 = offscreenCanvasCtx.isPointInStroke(this.X, this.Y)?'true':'false'; + this.textValue = offscreenCanvasCtx.isPointInPath(this.X, this.Y)?'true':'false'; + let bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + }, + change(){ + if(this.X < 500){ + this.X = this.X+50; + }else{ + this.X = 0; + } + let canvas = this.$refs.canvas.getContext('2d'); + let offscreen = new OffscreenCanvas(500,500); + let offscreenCanvasCtx = offscreen.getContext("2d"); + let offscreenCanvasCtx1 = offscreen.getContext("2d"); + offscreenCanvasCtx1.arc(this.X, this.Y, 1, 0, 6.28) + offscreenCanvasCtx.lineWidth=20 + offscreenCanvasCtx.rect(200,150, 200, 200); + offscreenCanvasCtx.stroke(); + this.textValue1 = offscreenCanvasCtx.isPointInStroke(this.X, this.Y)?'true':'false'; + this.textValue = offscreenCanvasCtx.isPointInPath(this.X, this.Y)?'true':'false'; + let bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001276003489](figures/en-us_image_0000001276003489.gif) diff --git a/en/application-dev/ui/ui-js-components-path2d.md b/en/application-dev/ui/ui-js-components-path2d.md new file mode 100644 index 0000000000000000000000000000000000000000..d0ad0d06b482ed86376c10c53dff91c55a9901a3 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-path2d.md @@ -0,0 +1,194 @@ +# Path2D + +**<Path2D>** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. For details, see [Path2D](../reference/arkui-js/js-components-canvas-path2d.md). + + +## Drawing Line Segments + +Create a **<Path2D>** object and use line segments to create different shapes. + + + +``` + +
+ +
+``` + + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +canvas{ + width: 600px; + height: 600px; + background-color: #fdfdfd; + border: 5px solid red; +} +``` + + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + onShow(){ + let ctx = this.$refs.canvas.getContext('2d',{antialias: true}); + let path = ctx.createPath2D(); + // Roof + path.moveTo(10, 300); + path.lineTo(210,100); + path.lineTo(410, 300); + // House + path.moveTo(10, 300); + path.lineTo(410, 300); + path.lineTo(410, 600); + path.lineTo(10, 600); + path.closePath(); + // Window + path.moveTo(50, 450); + path.bezierCurveTo(70, 350, 130, 350, 150, 450); + path.closePath(); + // Door + path.moveTo(250, 450); + path.rect(250, 450, 350, 600); + path.closePath(); + // Chimney + path.moveTo(365, 250); + path.ellipse(310, 215, 30, 130,0, Math.PI * 0.04, Math.PI * 1.1, 1); + // Tree + path.moveTo(485, 450); + path.quadraticCurveTo(510, 500, 485, 600); + path.moveTo(550, 450); + path.quadraticCurveTo(525, 500, 550, 600); + path.moveTo(600, 535); + path.arc(520, 450, 85, 0, 6); + ctx.stroke(path); + }, +} +``` + + +![en-us_image_0000001232002968](figures/en-us_image_0000001232002968.png) + + +## Drawing Graphs + +Use **createPath2D** to create a path object and draw only **path1** so that only **path1** is displayed on the canvas. Click the **<text>** component to trigger the **addPath** method. The **path2** object is passed to **path1** as a parameter. After the **stroke** operation is performed on the **path1** object, **path1** and **path2** are displayed on the canvas. Click **Change** to change the value of **setTransform** to** setTransform(2, 0.1, 0.1, 2, 0,0)**. The graph is enlarged and tilted to the left. + + +``` + +
+ +
+ {{ isAdd }} + {{textName}} +
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +canvas{ + width: 600px; + height: 600px; + background-color: #fdfdfd; + border: 5px solid red; +} +.content{ + width: 80%; + margin-top: 50px; + margin-bottom: 50px; + display: flex; + flex-wrap: wrap; + justify-content: space-around; +} +text{ + width: 150px; + height: 80px; + color: white; + border-radius: 20px; + text-align: center; + background-color: #6060e7; + margin-bottom: 30px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + ctx: null, + path1: null, + path2: null, + path3: null, + isAdd: "addPath2", + isChange: true, + textName: 'change' + }, + onShow(){ + this.ctx = this.$refs.canvas.getContext('2d',{antialias:true}); + this.path1 = this.ctx.createPath2D(); + this.path1.moveTo(200, 200); + this.path1.lineTo(400, 200); + this.path1.lineTo(400, 400); + this.path1.lineTo(200, 400); + this.path1.closePath(); + this.path2 = this.ctx.createPath2D(); + this.path2.arc(300, 300, 75, 0, 6.28) + this.ctx.stroke(this.path1); + }, + addPath(){ + if(this.isAdd == "addPath2"){ + this.ctx.clearRect(0,0,600,600) + this.ctx.beginPath(); + this.path2.addPath(this.path1) + this.ctx.stroke(this.path2); + this.isAdd = "clearPath2" + }else{ + this.ctx.clearRect(0,0,600,600) + this.ctx.stroke(this.path1); + this.isAdd = "addPath2" + } + }, + setTransform(){ + if(this.isChange){ + this.ctx.clearRect(0,0,600,600) + this.path3 = this.ctx.createPath2D(); + this.path3.arc(150, 150, 100, 0, 6.28) + this.path3.setTransform(2, 0.1, 0.1, 2, 0,0); + this.ctx.stroke(this.path3); + this.isChange = !this.isChange; + this.textName = "back" + }else{ + this.ctx.clearRect(0,0,600,600) + this.path3.setTransform(0.5, -0.1, -0.1, 0.5, 0,0); + this.ctx.stroke(this.path3); + this.isChange = !this.isChange; + this.textName = "change" + } + }, +} +``` + +![en-us_image_0000001231683112](figures/en-us_image_0000001231683112.gif) diff --git a/en/application-dev/ui/ui-js-components-picker.md b/en/application-dev/ui/ui-js-components-picker.md index a2e5ff4c52c17ce2d17b4638eebcebd68f9418bf..97c965d100a6a527855e1346dc94e69284795ead 100644 --- a/en/application-dev/ui/ui-js-components-picker.md +++ b/en/application-dev/ui/ui-js-components-picker.md @@ -1,18 +1,20 @@ # <picker> Development -The <picker> component supports common, date, time, data and time, and multi-column text selectors. For details, see [picker](../reference/arkui-js/js-components-basic-picker.md). +The **<picker>** component supports common, date, time, data and time, and multi-column text selectors. For details, see [picker](../reference/arkui-js/js-components-basic-picker.md). ## Creating a <picker> Component -Create a <picker> component in the .hml file under pages/index. +Create a **<picker>** component in the .hml file under **pages/index**. ```
- picker + + picker +
``` @@ -20,6 +22,8 @@ Create a <picker> component in the .hml file under pages/index. ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -32,7 +36,7 @@ Create a <picker> component in the .hml file under pages/index. ## Setting the Picker Type -Set the type attribute of the <picker> component. For example, set it to date. +Set the **type** attribute of the **<picker>** component. For example, set it to **date**. ``` @@ -47,6 +51,8 @@ Set the type attribute of the <picker> component. For example, set it to d ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -71,14 +77,15 @@ export default { ![en-us_image_0000001267647893](figures/en-us_image_0000001267647893.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> -> When setting the value range of a common selector, you must use the data binding mode. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - When setting the value range of a common selector, you must use the data binding mode. +> +> - The **lunarswitch** attribute of the date selector is only supported on phones and tablets. ## Setting the Time Format -Set the hours attribute to specify the time format used by the time selector. Available values include 12 and 24, indicating the 12-hour format and 24-hour format, respectively. +Set the **hours** attribute to specify the time format used by the time selector. Available values include **12** and **24**, indicating the 12-hour format and 24-hour format, respectively. ``` @@ -93,6 +100,8 @@ Set the hours attribute to specify the time format used by the time selector. Av ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -107,15 +116,15 @@ Set the hours attribute to specify the time format used by the time selector. Av ![en-us_image_0000001222807808](figures/en-us_image_0000001222807808.gif) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - When hours is set to 12, the time is displayed in 12-hour format and distinguished by a.m. and p.m. -> -> - When hours is set to 24, the time is displayed in 24-hour format. +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - When **hours** is set to **12**, the time is displayed in 12-hour format and distinguished by a.m. and p.m. +> +> - When **hours** is set to **24**, the time is displayed in 24-hour format. ## Adding Response Events -To confirm and cancel selection, add change and cancel events. +To confirm and cancel selection, add **change** and **cancel** events. ``` @@ -130,6 +139,8 @@ To confirm and cancel selection, add change and cancel events. ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -170,7 +181,9 @@ export default { ## Example Scenario -Implement a health check-in application by using the <picker> component. +Implement a health check-in application by using the **<picker>** component. + + ``` @@ -202,6 +215,8 @@ Implement a health check-in application by using the <picker> component.
``` + + ``` /* index.css */ .doc-page { @@ -244,6 +259,8 @@ Implement a health check-in application by using the <picker> component. } ``` + + ``` // xxx.js import pmt from '@system.prompt' diff --git a/en/application-dev/ui/ui-js-components-qrcode.md b/en/application-dev/ui/ui-js-components-qrcode.md new file mode 100644 index 0000000000000000000000000000000000000000..e766c5843a32a0d3fe99e300d0d82a14b5818eb0 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-qrcode.md @@ -0,0 +1,170 @@ +# <qrcode> Development + + +The **<qrcode>** component is used to generate and display a QR code. For details, see [qrcode](../reference/arkui-js/js-components-basic-qrcode.md). + + +## Creating a <qrcode> Component + +Create a **<qrcode>** component in the .hml file under **pages/index**. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001275803133](figures/en-us_image_0000001275803133.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The **value** parameter must be set. + + +## Setting the Component Type + +Set the **type** attribute to select the QR code type from rectangle and circle. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +select{ + margin-top: 50px; + margin-bottom: 50px; +} +``` + + +``` +// index.js +export default { + data: { + qr_type: 'rect', + bcol_list: ['rect','circle'] + }, + settype(e) { + this.qr_type = e.newValue + }, +} +``` + +![en-us_image_0000001275922965](figures/en-us_image_0000001275922965.gif) + + +## Setting Styles + +Set the **color** and **background-color** attributes to set the color and background color of a QR code. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +qrcode{ + width: 300px; + height: 300px; + color: blue; + background-color: #ffffff; +} +``` + +![en-us_image_0000001231683116](figures/en-us_image_0000001231683116.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed. +> +> - If either **width** or **height** is set, the value is used as the length of the QR code. If neither of them is set, the default length of 200 px is used. +> + + +## Example Scenario + +In this example, you can bind a QR code to a text box, and change the QR code by replacing the content in the text box. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +qrcode{ + width: 400px; + height: 400px; +} +``` + + +``` +// index.js +export default{ + data: { + textVal: '' + }, + change(e){ + this.textVal = e.value + } +} +``` + +![en-us_image_0000001232002972](figures/en-us_image_0000001232002972.gif) diff --git a/en/application-dev/ui/ui-js-components-rating.md b/en/application-dev/ui/ui-js-components-rating.md new file mode 100644 index 0000000000000000000000000000000000000000..3986fd268b2eaae9cce51269720c78ac957c4d4b --- /dev/null +++ b/en/application-dev/ui/ui-js-components-rating.md @@ -0,0 +1,257 @@ +# <rating> Development + + +The **<rating>** component provides a rating bar used for reviews and ratings. For details, see [rating](../reference/arkui-js/js-components-basic-rating.md). + + +## Creating a <rating> Component + +Create a **<rating>** component in the .hml file under **pages/index**. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +rating { + width: 80%; + height: 150px; +} +``` + +![en-us_image_0000001231843116](figures/en-us_image_0000001231843116.gif) + + +## Setting the Rating Level + +Use the **<rating>** component to set the number of stars in a rating bar and the current rating using the **numstars** and **rating** attributes, respectively. + + +``` + +
+ + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +rating { + width: 80%; + height: 150px; +} +``` + +![en-us_image_0000001232003012](figures/en-us_image_0000001232003012.gif) + + +## Setting the Rating Style + +Use the **<rating>** component to set the background images when a rating star is unselected, selected, and partially selected using the **star-background**, **star-foreground**, and **star-secondary** attributes, respectively. + + +``` + +
+
+ + +
+
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +``` + + +``` +/* index.js */ +export default { + data: { + backstar: 'common/love.png', + secstar: 'common/love.png', + forestar: 'common/love1.png', + ratewidth: '400px', + rateheight: '150px' + }, + onInit(){ + } +} +``` + +![en-us_image_0000001275803173](figures/en-us_image_0000001275803173.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - You must set **star-background**, **star-secondary**, and **star-foreground**. Otherwise, the grey rating star applies, indicating that the image source is incorrectly set. +> +> - The **star-background**, **star-secondary**, and **star-foreground** attributes support only PNG and JPG images in the local path. + + +## Binding Events + +Add the **change** event to the <rating> component to print the current rating. + + +``` + +
+ +
+``` + + +``` +.container { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +rating { + width: 80%; + height: 150px; +} +``` + + +``` +import prompt from '@system.prompt'; +export default { + showrating(e) { + prompt.showToast({ + message:'Current Rating' + e.rating + }) + } +} +``` + +![en-us_image_0000001276003525](figures/en-us_image_0000001276003525.gif) + + +## Example Scenario + +Change the switch status to toggle between the star background images and drag the slider to adjust the rating values. + + +``` + +
+
+ +
+
+
+ Replacing a custom image + +
+
+ numstars {{stars}} + +
+
+ rating {{rate}} + +
+
+
+``` + + +``` +/* xxx.css */ +.myrating:active { + width: 500px; + height: 100px; +} +switch{ + font-size: 40px; +} +``` + + +``` +/* index.js */ +import prompt from '@system.prompt'; +export default { + data: { + backstar: '', + secstar: '', + forestar: '', + stars: 5, + ratewidth: '300px', + rateheight: '60px', + step: 0.5, + rate: 0 + }, + onInit(){ + }, + setstar(e) { + if (e.checked == true) { + this.backstar = 'common/love.png' + this.secstar = 'common/love.png' + this.forestar = 'common/love1.png' + } else { + this.backstar = '' + this.secstar = '' + this.forestar = '' + } + }, + setnumstars(e) { + this.stars = e.progress + this.ratewidth = 60 * parseInt(this.stars) + 'px' + }, + setstep(e) { + this.step = e.progress + }, + setrating(e){ + this.rate = e.progress + }, + showrating(e) { + prompt.showToast({ + message:'Current Rating' + e.rating + }) + } +} +``` + +![en-us_image_0000001275923005](figures/en-us_image_0000001275923005.gif) diff --git a/en/application-dev/ui/ui-js-components-search.md b/en/application-dev/ui/ui-js-components-search.md new file mode 100644 index 0000000000000000000000000000000000000000..853e692646d0dc45bfe69d3808ec95786b18ea7d --- /dev/null +++ b/en/application-dev/ui/ui-js-components-search.md @@ -0,0 +1,260 @@ +# <search> Development + + +The **<search>** component provides an input area for users to search. For details, see [search](../reference/arkui-js/js-components-basic-search.md). + + +## Creating a <search> Component + +Create a **<search>** component in the .hml file under **pages/index**. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001276003537](figures/en-us_image_0000001276003537.png) + + +## Setting Attributes + +Set the **hint**, **icon**, and **searchbutton** to define the hint text, icon, and search button at the end of the search box. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001275923017](figures/en-us_image_0000001275923017.png) + + +## Adding Styles + +Set **color**, **placeholder**, and **caret-color** to set the text color, hint text color, and cursor color of the search box. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +search{ + color: black; + placeholder-color: black; + caret-color: red; +} +``` + +![en-us_image_0000001232003020](figures/en-us_image_0000001232003020.gif) + + +## Binding Events + +Add the **change**, **search**, **submit**, **share**, and **translate** events to the **<search>** component to perform operations on the input information. + + +``` + +
+ + Enter text and then touch and hold what you've entered + + + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +text{ + width: 100%; + font-size: 25px; + text-align: center; + margin-bottom: 100px; +} +``` + + +``` +// index.js +import prompt from '@system.prompt' +export default { + search(e){ + prompt.showToast({ + message: e.value, + duration: 3000, + }); + }, + translate(e){ + prompt.showToast({ + message: e.value, + duration: 3000, + }); + }, + share(e){ + prompt.showToast({ + message: e.value, + duration: 3000, + }); + }, + change(e){ + prompt.showToast({ + message: e.value, + duration: 3000, + }); + }, + submit(e){ + prompt.showToast({ + message: 'submit', + duration: 3000, + }); + } +} +``` + +![en-us_image_0000001231683164](figures/en-us_image_0000001231683164.gif) + + +## Example Scenario + +In this example, you can select the **<search>**, **<textarea>**, or **<input>** component from the drop-down list box to implement the respective function. + + +``` + +
+ +
+ + +
+
+ + +
+
+ + +
+
+``` + + +``` +/* xxx.css */ +.field { + width: 80%; + color: mediumaquamarine; + font-weight: 600; + placeholder-color: orangered; +} +.slt1{ + font-size: 50px; + position: absolute; + left: 50px; + top: 50px; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + data: { + showsearch: true, + showtextarea: false, + showinput: false, + showsec: true, + }, + setfield(e) { + this.field = e.newValue + if (e.newValue == 'search') { + this.showsearch = true + this.showtextarea = false + this.showinput = false + } else if (e.newValue == 'textarea') { + this.showsearch = false + this.showtextarea = true + this.showinput = false + } else { + this.showsearch = false + this.showtextarea = false + this.showinput = true + } + }, + submit(e) { + prompt.showToast({ + message: 'Search!', + duration: 2000 + }) + }, + change(e) { + prompt.showToast({ + message: 'Content:'+ e.text, + duration: 2000 + }) + } +} +``` + +![en-us_image_0000001232003024](figures/en-us_image_0000001232003024.gif) diff --git a/en/application-dev/ui/ui-js-components-slider.md b/en/application-dev/ui/ui-js-components-slider.md new file mode 100644 index 0000000000000000000000000000000000000000..fad51ad23f82100d7078c659733c9bb07abad22a --- /dev/null +++ b/en/application-dev/ui/ui-js-components-slider.md @@ -0,0 +1,215 @@ +# <slider> Development + + +The **<slider>** component is used to quickly adjust settings, such as the volume and brightness. For details, see [slider](../reference/arkui-js/js-components-basic-slider.md). + + +## Creating a <slider> Component + +Create a **<slider>** component in the .hml file under **pages/index**. + + + +``` + +
+ +
+``` + + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + background-color: #F1F3F5; + flex-direction: column; + justify-content: center; + align-items: center; +} +``` + + +![en-us_image_0000001232162312](figures/en-us_image_0000001232162312.gif) + + +## Setting Styles and Attributes + +Use the **<slider>** component to set the background color, selected color, and slider color using the **color**, **selected-color**, and **block-color** attributes, respectively. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.sli{ + color: #fcfcfc; + scrollbar-color: aqua; + background-color: #b7e3f3; +} +``` + +![en-us_image_0000001232003000](figures/en-us_image_0000001232003000.gif) + +Add the **mix**, **max**, **value**, **step**, and **mode** attributes to set the minimum value, maximum value, initial value, step, and style of the slider. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001276003517](figures/en-us_image_0000001276003517.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> Set the **mode** attribute to specify the slider style, which takes effect only on mobile phones and tablets. It can be set to: +> +> - **outset**: The slider is on the sliding bar. +> +> - **inset**: The slider is inside the sliding bar. + + +## Binding Events + +Add the **change** event to the **<rating>** component and pass the ChangeEvent attribute when adding the event. + + +``` + +
+ slider start value is {{startValue}} + slider current value is {{currentValue}} + slider end value is {{endValue}} + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +``` + + +``` +// xxx.js +export default { + data: { + value: 0, + startValue: 0, + currentValue: 0, + endValue: 0, + }, + setvalue(e) { + if (e.mode == "start") { + this.value = e.value; + this.startValue = e.value; + } else if (e.mode == "move") { + this.value = e.value; + this.currentValue = e.value; + } else if (e.mode == "end") { + this.value = e.value; + this.endValue = e.value; + } + } +} +``` + +![en-us_image_0000001275803169](figures/en-us_image_0000001275803169.gif) + + +## Example Scenario + +Adjust the value of the slider to change the image size and dynamically print the width and height of the current image. + + +``` + +
+ +
+ + The width of this picture is {{WidthVal}} + The height of this picture is {{HeightVal}} +
+
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +.txt{ + flex-direction: column; + justify-content: center; + align-items: center; + position: fixed; + top: 65%; +} +text{ + margin-top: 30px; +} +``` + + +``` +// xxx.js +export default{ + data: { + value: 0, + WidthVal: 200, + HeightVal: 200 + }, + setvalue(e) { + this.WidthVal = 200 + e.value; + this.HeightVal = 200 + e.value + } +} +``` + +![en-us_image_0000001275922997](figures/en-us_image_0000001275922997.gif) diff --git a/en/application-dev/ui/ui-js-components-stepper.md b/en/application-dev/ui/ui-js-components-stepper.md index d9a13be87c74e1e602c5352f6f324cf5d08ed6ea..40fd14674c95de76bf063ff010264c6a19663e48 100644 --- a/en/application-dev/ui/ui-js-components-stepper.md +++ b/en/application-dev/ui/ui-js-components-stepper.md @@ -1,28 +1,28 @@ # <stepper> Development -When multiple steps are required to complete a task, you can use the <stepper> component to navigate your users through the whole process. For details, see [stepper](../reference/arkui-js/js-components-container-stepper.md). +When multiple steps are required to complete a task, you can use the **<stepper>** component to navigate your users through the whole process. For details, see [stepper](../reference/arkui-js/js-components-container-stepper.md). -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > This component is supported since API version 5. ## Creating a <stepper> Component -Create a <stepper> component in the .hml file under pages/index. +Create a **<stepper>** component in the .hml file under **pages/index**. ```
- + Step 1 Step 2 - +
``` @@ -30,6 +30,8 @@ Create a <stepper> component in the .hml file under pages/index. ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; @@ -47,7 +49,7 @@ text{ ## Setting the Index -Set index to the index value of the step that you want to display by default. +Set **index** to the index value of the step that you want to display by default. ``` @@ -71,6 +73,8 @@ Set index to the index value of the step that you want to display by default. ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; background-color:#F1F3F5; } @@ -83,7 +87,7 @@ text{ ![en-us_image_0000001267767837](figures/en-us_image_0000001267767837.gif) -Set the label attribute to customize the button text for the <stepper-item>. +Set the **label** attribute to customize the button text for the **<stepper-item>**. ``` @@ -110,6 +114,8 @@ Set the label attribute to customize the button text for the <stepper-item> ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; background-color:#F1F3F5; } @@ -125,7 +131,10 @@ text{ /* index.js */ export default { data: { - label_1:{ nextLabel: 'NEXT', status: 'normal' }, + label_1:{ + nextLabel: 'NEXT', + status: 'normal' + }, label_2:{ prevLabel: 'BACK', nextLabel: 'NEXT', @@ -143,9 +152,9 @@ export default { ![en-us_image_0000001267767841](figures/en-us_image_0000001267767841.gif) -## Setting the Style +## Setting Styles - By default, the <stepper> component fills entire space of its container. The sample code below shows how to set the border and background color using the border and background-color attributes. + By default, the **<stepper>** component fills entire space of its container. The sample code below shows how to set the border and background color using the **border** and **background-color** attributes. ``` @@ -164,6 +173,8 @@ export default { ``` /* index.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -174,7 +185,8 @@ export default { height: 300px; } .stepperClass{ - border:1px solid silver ; background-color: white; + border:1px solid silver; + background-color: white; } text{ width: 100%; @@ -188,12 +200,13 @@ text{ ## Adding Events -The <stepper> component supports the finish, change, next, back, and skip events. +The **<stepper>** component supports the **finish**, **change**, **next**, **back**, and **skip** events. -- When the change and next or back events exist at the same time, the next or back event is executed before the change event. +- When the **change** and **next** or **back** events exist at the same time, the **next** or **back** event is executed before the **change** event. -- Before resetting the index attribute, you must remove the current value. Otherwise, the value change cannot be detected. +- Before resetting the **index** attribute, you must remove the current value. Otherwise, the value change cannot be detected. + ```
@@ -219,6 +232,8 @@ The <stepper> component supports the finish, change, next, back, and skip ``` /* xxx.css */ .doc-page { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; @@ -339,6 +354,8 @@ Use the <stepper> component to navigate through the steps. Create a [<t ``` /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; align-items: center; justify-content: center; diff --git a/en/application-dev/ui/ui-js-components-svg-graphics.md b/en/application-dev/ui/ui-js-components-svg-graphics.md new file mode 100644 index 0000000000000000000000000000000000000000..c877843b9eae3428095c5f7ba4cf9eb370b3952e --- /dev/null +++ b/en/application-dev/ui/ui-js-components-svg-graphics.md @@ -0,0 +1,41 @@ +# Graph Drawing + + +The **<svg>** component can be used to draw simple shapes, such as rectangles, circles, and lines. For details about the supported shapes, see <svg>. + + +In this example, you can draw different shapes and stitch them to form a house graph. + + +``` + +
+ + // Rooftop + // Chimney + // Main body + + // Window + + // Window frame + // Window frame + // Door + // Doorknob + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001232162288](figures/en-us_image_0000001232162288.png) diff --git a/en/application-dev/ui/ui-js-components-svg-overview.md b/en/application-dev/ui/ui-js-components-svg-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..cfe1a30c7344b141945da065f14775cc04cb60e0 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-svg-overview.md @@ -0,0 +1,83 @@ +# Basics + + +The **<svg>** component is used as the root node of the SVG canvas and can be nested in the SVG. For details, see [svg](../reference/arkui-js/js-components-svg.md). + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The APIs of this component are supported since API version 7. +> +> - The width and height must be defined for the **<svg>** parent component or **<svg>** component. Otherwise, the component is not drawn. + + +## Creating an <svg> Component + +Create a **<svg>** component in the .hml file under **pages/index**. + + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +svg{ + background-color: blue; +} +``` + +![en-us_image_0000001232162324](figures/en-us_image_0000001232162324.png) + + +## Setting Attributes + +Set the **width**, **height**, **x**, **y**, and **viewBox** attributes to define the width, height, X coordinate, Y coordinate, and SVG viewport of the **<svg>** component. + + +``` + +
+ + + + +
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + align-items: center; + justify-content: center; + background-color: #F1F3F5; +} +svg{ + background-color: yellow; +} +.rect{ + background-color: red; +} +``` + +![en-us_image_0000001231683152](figures/en-us_image_0000001231683152.png) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - If the **<svg>** component is the root node, the X-axis and Y-axis attributes are invalid. +> +> - If the width and height of **viewBox** are inconsistent with those of the **<svg>** component, the view box will be scaled in center-aligned mode. diff --git a/en/application-dev/ui/ui-js-components-svg-path.md b/en/application-dev/ui/ui-js-components-svg-path.md new file mode 100644 index 0000000000000000000000000000000000000000..646fd7215e9daf06225aeda9f0339a8edb0d6551 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-svg-path.md @@ -0,0 +1,57 @@ +# Path Drawing + + +The **<svg>** component uses instructions **M** (start point), **H** (horizontal line), and **a** (drawing an arc to a specified position) to control a path and sets the fill colors to create a pie chart. + + + +``` + +
+ + + + + + +
+``` + + + +``` +/* xxx.css */ +.container { + flex-direction: row; + justify-content: flex-start; + align-items: flex-start; + height: 1200px; + width: 600px; + background-color: #F1F3F5; +} +``` + + +![en-us_image_0000001232162340](figures/en-us_image_0000001232162340.png) + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - M/m = moveto The **x** and **y** parameters indicate the destination X and Y coordinates of a point. The **M** command only moves the brush, but does not draw a line between two points. Therefore, the **M** command is often used at the beginning of a path to indicate the start point. +> +> - L/l = lineto The **x** and **y** parameters indicate the X and Y coordinates of a point. The **L** command draws a line between the current position and the destination position (the previous point of the brush). +> +> - H/h = horizontal lineto Draws a horizontal line. +> +> - V/v = vertical lineto Draws a vertical line. +> +> - C/c = curveto Draws a cubic Bezier curve. Three groups of coordinate parameters are required: **x1 y1**, **x2 y2**, **x y**. +> +> - S/s = smooth curveto Draws a cubic Bezier curve. Two groups of coordinate parameters are required: **x2 y2**, **x y**. +> +> - Q/q = quadratic Belzier curve Draws a quadratic Bezier curve. Two groups of coordinate parameters are required: **x1 y1**, **x y**. +> +> - T/t = smooth quadratic Belzier curveto Draws a quadratic Bezier curve. One group of coordinate parameters are required: **x y**. +> +> - A/a = elliptical Arc Draw an arc. The following parameters are required: **rx ry x-axis-rotation** (rotation angle), **large-arc-flag** (angle), **sweep-flag** (arc direction), and **x y**. **large-arc-flag** determines whether the arc is less than 180 degrees. **0** indicates yes, and **1** indicates no. **sweep-flag** indicates the direction in which an arc is drawn. **0** indicates that the arc is drawn counterclockwise from the start point to the end point. **1** indicates that the arc is drawn clockwise from the start point to the end point. +> +> - Z/z = closepath Draws a straight line from the current point to the start point of the path. diff --git a/en/application-dev/ui/ui-js-components-svg-text.md b/en/application-dev/ui/ui-js-components-svg-text.md new file mode 100644 index 0000000000000000000000000000000000000000..782580e47ad75c0b28c1f233041fa95cdd8235c7 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-svg-text.md @@ -0,0 +1,54 @@ +# Text Drawing + + +The **<svg>** component can also be used to draw text. + + +## Text + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The text content must be written in the **<text>** area. The **<tspan>** child element label can be nested. +> +> - **<text>** can be nested only by the parent element label **svg**. +> +> - Only the default font **sans-serif** is supported. + +Set the following attributes to define text styles: **x** (X coordinate), **y** (Y coordinate), **dx** (x-axis offset of the text), **dy** (y-axis offset of the text), **fill** (font fill color), **stroke** (text border color), and **stroke-width** (text border width). + + +``` + +
+ + Hello World + Hello World + + Hello World + + +
+``` + +![en-us_image_0000001275803145](figures/en-us_image_0000001275803145.png) + + +## Drawing Text Along the Path + +Set **textpath** to draw text along the path. + + +``` + +
+ + + + + This is textpath test. + + + +
+``` + +![en-us_image_0000001231843084](figures/en-us_image_0000001231843084.png) diff --git a/en/application-dev/ui/ui-js-components-swiper.md b/en/application-dev/ui/ui-js-components-swiper.md new file mode 100644 index 0000000000000000000000000000000000000000..64e34ada4fb38b19fb61471fcbfda22bce29451a --- /dev/null +++ b/en/application-dev/ui/ui-js-components-swiper.md @@ -0,0 +1,370 @@ +# <swiper> Development + + +The **<swiper>** component is a sliding container used to switch between child components. For details, see [swiper](../reference/arkui-js/js-components-container-swiper.md). + + +## Creating a <swiper> Component + +Create a **<swiper>** component in the .hml file under **pages/index**. + + + +``` + +
+ +
+ item1 +
+
+ item2 +
+
+ item3 +
+
+
+``` + + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +swiper{ + height: 30%; +} +.item{ + width: 100%; + height: 500px; +} +text{ + width: 100%; + height: 100%; + text-align: center; + font-size: 50px; + color: white; +} +``` + + +![en-us_image_0000001232003028](figures/en-us_image_0000001232003028.gif) + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The **<swiper>** component supports child components except **<list>**. + + +## Adding Attributes + +When **loop** is set to **false**, the **autoplay** attribute is added to the **<swiper>** component and the autoplay interval (**interval**) is set. The component automatically switches between child components and stops at the last one. Add the **digital** attribute to enable the digital navigation point and set **scrolleffect** to **fade**. + + +``` + +
+ +
+ item1 +
+
+ item2 +
+
+ item3 +
+
+ item4 +
+
+
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +swiper{ + height: 30%; +} +.item{ + width: 100%; + height: 500px; +} +text{ + width: 100%; + height: 100%; + text-align: center; + font-size: 50px; + color: white; +} +``` + +![en-us_image_0000001275923021](figures/en-us_image_0000001275923021.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> - The **digital** attribute takes effect only when the **indicator** attribute is set to **true**. +> +> - The **loop** attribute takes effect only when there are two or more than two child components of the **<swiper>** component. +> +> - The **scrolleffect** attribute takes effect only when the **loop** attribute value is set to **false**. + + +## Setting Styles + +Set the width and height of the **<swiper>** component, the indicator's size (**indicator-size**), color (**indicator-color**), relative position (**indicator-top**), and color when it is selected (**indicator-selected-color**). + + +``` + +
+ +
+ item1 +
+
+ item2 +
+
+ item3 +
+
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +swiper{ + width: 500px; + height: 500px; + border-radius: 250px; + indicator-color: white; + indicator-selected-color: blue; + indicator-size: 40px; + indicator-top: 100px; + overflow: hidden ; +} +.item{ + width: 100%; + height: 500px; +} +text{ + width: 100%; + text-align: center; + margin-top: 150px; + font-size: 50px; + color: white; +} +``` + +![en-us_image_0000001275803189](figures/en-us_image_0000001275803189.gif) + + +## Binding Events + +Create two **<text>** components and bind click events. Clicking the component will call **showPrevious** to display the previous child component or **showNext** to display the next child component. Add a **<select>** component. A **change** event is triggered when a user selects a value from the drop-down list box and the **swipeTo** method is called to go to the specified page. Bind the **<swiper>** component with the **change** event (triggered when the index of the currently displayed component changes) and the **finish** event (triggered when the switchover animation ends). + + +``` + +
+ +
+ item1 +
+
+ item2 +
+
+ item3 +
+
+ item4 +
+
+
+ + + +
+
+``` + + +``` +/* xxx.css */ +.container{ + width: 100%; + height: 100%; + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +swiper{ + height: 30%; +} +.item{ + width: 100%; + height: 500px; +} +text{ + width: 100%; + height: 100%; + text-align: center; + font-size: 50px; + color: white; +} +select{ + background-color: white; + width: 250px; + height: 80px; +} +.content{ + margin-top: 100px; + justify-content: space-around; +} +.pnbtn{ + width: 200px; + height: 80px; + font-size: 30px; +} +``` + + +``` +import prompt from '@system.prompt'; +export default{ + change(e){ + prompt.showToast({duration:2000,message:"current index:"+e.index}); + }, + finish(){ + prompt.showToast({duration:2000,message:"The switchover ends"}); + }, + selectChange(e){ + this.$element('swiper').swipeTo({index: Number(e.newValue)}); + }, + previous(){ + this.$element('swiper').showPrevious(); + }, + next(){ + this.$element('swiper').showNext(); + } +} +``` + +![en-us_image_0000001231843128](figures/en-us_image_0000001231843128.gif) + + +## Example Scenario + +Use the **<swiper>** component to create an image carousel and a thumbnail module at the bottom of the carousel. After a thumbnail is clicked, the **swipeTo** method is called to switch to the corresponding image. + + +``` + +
+ +
+ +
+
+
+
+ +
+
+
+``` + + +``` +/* xxx.css */ +.container{ + flex-direction: column; + background-color: #F1F3F5; + align-items: center; + justify-content: center; + width: 100%; +} +swiper{ + width: 100%; + height: 500px; +} +.item{ + width: 100%; + height: 500px; +} +.content{ + margin-top: -120px; + width: 70%; + display: flex; + justify-content: space-around; + height: 100px; +} +.content_item{ + padding: 5px; + transform: scale(0.5); +} +.actived{ + transform: scale(1); + border: 1px solid #b20937ea; +} +``` + + +``` +// index.js +import prompt from '@system.prompt'; +export default { + data:{ + index: 0, + list:[ + {src: 'common/images/1.png'}, + {src: 'common/images/2.png'}, + {src: 'common/images/3.png'}, + {src: 'common/images/4.png'},] + }, + imageTo(index){ + this.index = index; + this.$element('swiper').swipeTo({index: index}); + }, + change(e){ + this.index = e.index; + } +} +``` + +![en-us_image_0000001231843132](figures/en-us_image_0000001231843132.gif) diff --git a/en/application-dev/ui/ui-js-components-switch.md b/en/application-dev/ui/ui-js-components-switch.md new file mode 100644 index 0000000000000000000000000000000000000000..4eeffd99b1bac376b5d8e6db2298ec9232003c70 --- /dev/null +++ b/en/application-dev/ui/ui-js-components-switch.md @@ -0,0 +1,197 @@ +# <switch> Development + + +The **<switch>** component is used to switch between the on and off states. For details, see [switch](../reference/arkui-js/js-components-basic-switch.md). + + +## Creating a <switch> Component + +Create a **<switch>** component in the .hml file under **pages/index**. + + +``` +
+ +
+``` + + +``` +/* xxx.css */ +.container { + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +``` + +![en-us_image_0000001231843096](figures/en-us_image_0000001231843096.png) + + +## Adding Attributes and Methods + + Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off). + +``` + +
+ +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + display: flex; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +switch{ + // Color of the selected text + texton-color: #002aff; + // Color of the unselected text +textoff-color: silver; + text-padding: 20px; + font-size: 50px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + switchChange(e){ + if(e.checked){ + prompt.showToast({ + message: "open" + }); + }else{ + prompt.showToast({ + message: "close" + }); + } + } +} +``` + + +![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif) + + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**. + + +## Example Scenario + +Turn on the switch and the default delivery address is used. When the switch is turned off, the address selection button is displayed on the page. Clicking the button can change the delivery address. + + Implementation method: Create a **<switch>** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color. + +``` + +
+
+ Choose default address: + +
+
+ Shipping address:{{address}} +
+
+ Choose an address: + {{item}} +
+
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + background-color: #F1F3F5; + flex-direction: column; + padding: 50px; +} +.change{ + margin-top: 20%; + width: 100%; + justify-content: center; +} +switch{ + texton-color: #002aff; + textoff-color: silver; + text-padding: 20px; +} +.content{ + width: 70%; + text-align: center; + flex-direction: column; + border: 1px solid #002aff; + margin-left: 15%; + text-align: center; +} +.address{ + width: 100%; + height: 100px; + line-height: 100px; + text-align: center; + font-size: 28px; + margin-bottom: 50px; +} +.textSpan{ + color: #0aa9f1; +} +.myAddress{ + flex-direction: column; + margin-top: 50px; +} +.addressText{ + margin-left: 35%; + width: 30%; + height: 75px; + text-align: center; + color: white; + margin-bottom: 30px; + border-radius: 10px; + border: 1px solid #0fabe7; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + address: '', + addressDisplay: 'none', + addressList: ['family','company','commissary'], + }, + onInit(){ + // Initialize the default address to the first one in the address list. + this.address = this.addressList[0]; + }, + switchChange(e){ + if(e.checked){ + this.addressDisplay = "none"; + }else{ + this.addressDisplay = "flex"; + } + }, + changeAddress(i){ + this.address= this.addressList[i]; + } +} +``` + +![en-us_image_0000001231843100](figures/en-us_image_0000001231843100.gif) diff --git a/en/application-dev/ui/ui-js-components-text.md b/en/application-dev/ui/ui-js-components-text.md index 68fc3006a34b48456df5a99ebbbcf39fd338f5d4..803f74378334f49c13cb5ce431967f6dd3d05d23 100644 --- a/en/application-dev/ui/ui-js-components-text.md +++ b/en/application-dev/ui/ui-js-components-text.md @@ -1,18 +1,20 @@ # <text> Development -The <text> component is used to display a piece of textual information. For details, see [text](../reference/arkui-js/js-components-basic-text.md). +The **<text>** component is used to display a piece of textual information. For details, see [text](../reference/arkui-js/js-components-basic-text.md). ## Creating a <text> Component -Create a <text> component in the .hml file under pages/index. +Create a **<text>** component in the .hml file under **pages/index**. ```
- Hello World + + Hello World +
``` @@ -35,10 +37,9 @@ Create a <text> component in the .hml file under pages/index. ## Setting the Text Style and Attributes - Adding a text style + Set the color, font-size, allow-scale, word-spacing and text-align properties to add the color, size, zoom, text spacing, and vertical alignment of the text. - - Set the color, font-size, allow-scale, word-spacing, and text-valign attributes to apply the color, size, zoom, spacing, and vertical alignment styles to the text. - + ```
@@ -52,7 +53,6 @@ Create a <text> component in the .hml file under pages/index. ``` - ``` /* xxx.css */ .container { @@ -65,14 +65,13 @@ Create a <text> component in the .hml file under pages/index. } ``` + ![en-us_image_0000001222967764](figures/en-us_image_0000001222967764.png) - ![en-us_image_0000001222967764](figures/en-us_image_0000001222967764.png) - Adding a text modifier + Set the **text-decoration** and **text-decoration-color** attributes to add an underline, overline, line-through, or a combination of lines in the specified color to selected text. For values of **text-decoration**, see [Text Style](../reference/arkui-js/js-components-basic-text.md). - - Set the text-decoration attribute to add a line to selected text. Set the text-decoration-color attribute to apply specific color to the added line. For values of text-decoration, see [Text Style](../reference/arkui-js/js-components-basic-text.md). - + ```
@@ -85,6 +84,7 @@ Create a <text> component in the .hml file under pages/index.
``` + ``` /* xxx.css */ .container { @@ -99,14 +99,13 @@ Create a <text> component in the .hml file under pages/index. } ``` - ![en-us_image_0000001223287688](figures/en-us_image_0000001223287688.png) -- Hiding text content - - Set the text-overflow attribute to ellipsis so that overflowed text is displayed as an ellipsis. +- Hiding text content + Set the **text-overflow** attribute to **ellipsis** so that overflowed text is displayed as an ellipsis. + ```
@@ -116,6 +115,7 @@ Create a <text> component in the .hml file under pages/index.
``` + ``` /* xxx.css */ .container { @@ -129,25 +129,22 @@ Create a <text> component in the .hml file under pages/index. .text{ width: 200px; max-lines: 1; - text-overflow:ellipsis; + text-overflow:ellipsis; } ``` + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** + > - **text-overflow** must be used together with **max-lines**. + > + > - **max-lines** indicates the maximum number of lines in the text. - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: - > - text-overflow must be used together with max-lines. - > - > - max-lines indicates the maximum number of lines in the text. - - -![en-us_image_0000001267647865](figures/en-us_image_0000001267647865.png) + ![en-us_image_0000001267647865](figures/en-us_image_0000001267647865.png) - Setting the text line breaking mode + Set the **word-break** attribute to specify how to break lines of text. For values of **word-break**, see [Text Styles](../reference/arkui-js/js-components-basic-text.md). - - Set the word-break attribute to specify how to break lines of text. For values of word-break, see [Text Styles](../reference/arkui-js/js-components-basic-text.md). - + ```
@@ -162,6 +159,7 @@ Create a <text> component in the .hml file under pages/index.
``` + ``` /* xxx.css */ .container { @@ -188,66 +186,74 @@ Create a <text> component in the .hml file under pages/index. height: 200px; border:1px solid #0931e8; text-align: center; - word-break: break-all; + word-break: break-all; font-size: 40px; } ``` + ![en-us_image_0000001267767865](figures/en-us_image_0000001267767865.png) - ![en-us_image_0000001267767865](figures/en-us_image_0000001267767865.png) - -- Setting the [<span>](../reference/arkui-js/js-components-basic-span.md)child component -``` - -
- - This is a passage - - - This 1 is a 1 passage - -
-``` +- Setting the [<span>](../reference/arkui-js/js-components-basic-span.md) child component. + + ``` + +
+ + This is a passage + + + This + + 1 + + is a + + 1 + + passage + +
+ ``` + ![en-us_image_0000001223127720](figures/en-us_image_0000001223127720.png) -![en-us_image_0000001223127720](figures/en-us_image_0000001223127720.png) + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** + > - When the **<span>** child component is used to form a text paragraph, incorrect **<span>** attribute settings (for example, setting of **font-weight** to **1000**) will result in abnormal display of the text paragraph. + > + > - When the **<span>** child component is being used, do not include any text you want to show in the **<text>** component, as such text will not be displayed if you do so. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: -> - When the <span> child component is used to form a text paragraph, incorrect <span> attribute settings (for example, setting of font-weight to 1000) will result in abnormal display of the text paragraph. -> -> - When the <span> child component is being used, do not include any text you want to show in the <text> component, as such text will not be displayed if you do so. +## Example Scenario +Use the **<text>** component to display text content through data binding. Use the **<span>** child component to hide or display text content by setting the **show** attribute. -## Example Scenario -Use the <text> component to display text content through data binding. Use the <span> child component to hide or display text content by setting the show attribute. - - - ``` - -
-
- - {{ content }} - - -
- - {{ content }} - - 1 - - Hide clip - -
- ``` +``` + +
+
+ + {{ content }} + + +
+ + {{ content }} + + 1 + + Hide clip + +
+``` ``` /* xxx.css */ .container { + width: 100%; + height: 100%; align-items: center; flex-direction: column; justify-content: center; @@ -266,7 +272,7 @@ Use the <text> component to display text content through data binding. Use // xxx.js export default { data: { - isShow:true, + isShow:true, content: 'Hello World' }, onInit(){ }, diff --git a/en/application-dev/ui/ui-js-components-toolbar.md b/en/application-dev/ui/ui-js-components-toolbar.md new file mode 100644 index 0000000000000000000000000000000000000000..90971232ef1cdbff23ff3517553649c3e49d652a --- /dev/null +++ b/en/application-dev/ui/ui-js-components-toolbar.md @@ -0,0 +1,229 @@ +# <toolbar> Development + + +The **<toolbar>** component shows actions available on the current screen and can be used for level-1 navigation. For details, see [toolbar](../reference/arkui-js/js-components-basic-toolbar.md). + + +## Creating a <toolbar> Component + +Create a **<toolbar>** component in the .hml file under **pages/index**. + + +``` + +
+ + + + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +toolbar-item{ + font-size: 35px; +} +``` + +![en-us_image_0000001275922977](figures/en-us_image_0000001275922977.gif) + + +## Add Child Components + + The **<toolbar>** component supports only the **<toolbar-item>** child component and can display a maximum of five **<toolbar-item>** child components on a page. If there are six or more **<toolbar-item>** child components, the first four child components are retained, and the rest are moved to the **More** option on the toolbar and can be displayed on a pop-up window by clicking **More**. Under **More**, the child components are displayed in the default style; the custom style settings do not take effect. + +``` + +
+ + + + + + + + +
+``` + + +``` +/* xxx.css */ +.container { + width: 100%; + height: 100%; + flex-direction: column; + justify-content: center; + align-items: center; + background-color: #F1F3F5; +} +toolbar-item{ + font-size: 35px; +} +``` + +![en-us_image_0000001232002988](figures/en-us_image_0000001232002988.gif) + + +## Setting Styles + +Set the **position** style for the **<toolbar>** component and set the font color, size, and background color of **<toolbar-item>** child components. + + + +``` + +
+ + + + + + +
+``` + + + +``` +/* xxx.css */ +.container { + background-color: #F1F3F5; + flex-direction: column; + width: 100%; + justify-content: center; + align-items: center; +} +toolbar-item{ + font-size: 35px; +} +.toolbarActive{ + color: red; + background-color: #daebef; +} +``` + + +![en-us_image_0000001275803149](figures/en-us_image_0000001275803149.png) + + +## Binding Events + +Bind the click event and long press event to the **<toolbar-item>** child components, so that the text of these components turns red upon click and turns blue upon long press. + + +``` + +
+ + + + + +
+``` + + +``` +/* xxx.css */ +.container { + background-color: #F1F3F5; + flex-direction: column; + width: 100%; + justify-content: center; + align-items: center; +} +toolbar-item{ + font-size: 35px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + itemColor:'black' + }, + itemClick(){ + this.itemColor= "red"; + prompt.showToast({duration:2000,message:'item click'}); + }, + itemLongPress(){ + prompt.showToast({duration:2000,message:'item long press'}); + this.itemColor= "blue"; + }, +} +``` + +![en-us_image_0000001275803153](figures/en-us_image_0000001275803153.gif) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** +> The **<toolbar>** component does not allow adding of events or methods, but its child components do. + + +## Example Scenario + +In this example, you'll implement a **<toolbar-item>** component, clicking which will trigger a change in the text color and the image corresponding to the component. + + Use the **for** loop to create a **<toolbar-item>** component and bind a click event to it, so that clicking the component will obtain and store an index value. When setting the text color, the system checks whether the current index value is the stored value. If yes, the system sets the color to red. If no, the system uses the default color. + +``` + +
+ + + + +
+``` + + +``` +/* xxx.css */ +.container { + background-color: #F1F3F5; + flex-direction: column; + width: 100%; + justify-content: center; + align-items: center; +} +toolbar-item{ + font-size: 35px; +} +``` + + +``` +// xxx.js +import prompt from '@system.prompt'; +export default { + data:{ + active: 0, + imgList:["common/images/1.png","common/images/2.png","common/images/3.png","common/images/4.png"], + itemList:[ + {option:'item1',icon:'common/images/1.png'}, + {option:'item2',icon:'common/images/2.png'}, + {option:'item3',icon:'common/images/3.png'}, + {option:'item4',icon:'common/images/4.png'}, + ] + }, + itemClick(id){ + this.active= id; + }, +} +``` + +![en-us_image_0000001231683128](figures/en-us_image_0000001231683128.gif) diff --git a/en/application-dev/ui/ui-ts-basic-components-button.md b/en/application-dev/ui/ui-ts-basic-components-button.md new file mode 100644 index 0000000000000000000000000000000000000000..8f13accaa19720e3fd8acff04ee2ccd2a30c3c84 --- /dev/null +++ b/en/application-dev/ui/ui-ts-basic-components-button.md @@ -0,0 +1,188 @@ +# Button + + +The **\